关于c#:如何在-AspNet-Core-实现-Excel-导出功能

5次阅读

共计 2833 个字符,预计需要花费 8 分钟才能阅读完成。

在 web 利用程序开发时,或者你会遇到这样的需要,如何在 Asp.Net Core 中实现 excel 或者 word 的导入导出,在 NuGet 上有大量的工具包能够实现这样的性能,本篇就探讨下如何应用 ClosedXML 实现 Excel 数据导出。

装置 ClosedXML

如果想实现 Excel 的导出性能,在 Asp.Net Core 中有很多的 dll 能够做到,其中的一个叫做 ClosedXML,你能够通过可视化界面 NuGet package manager 去装置,也能够应用命令行 NuGet package manager console 执行上面命令。


Install-Package ClosedXML

将数据导出成 CSV 文件

将数据导成 CSV 文件是非常简单的,毕竟每行数据都是用 , 隔开即可,能够用 NuGet 上的 CsvExport 或者 AWright18.SimpleCSVExporter 去实现,当然你感觉本人很 ????????,能够亲自操刀实现,上面我筹备亲自实现一下,先看上面定义的 Author 类。


public class Author
{public int Id { get; set;}
  public string FirstName {get; set;}
  public string LastName {get; set;}
}

而后塞一些数据到 authors 列表中,如下代码所示:


List<Author> authors = new List<Author>
{new Author { Id = 1, FirstName = "Joydip", LastName = "Kanjilal"},
    new Author {Id = 2, FirstName = "Steve", LastName = "Smith"},
    new Author {Id = 3, FirstName = "Anand", LastName = "Narayaswamy"}
};

定义一个 DownloadCommaSeperatedFile 办法,用于实现 Action 的 csv 导出性能。


public IActionResult DownloadCommaSeperatedFile()
{
    try
    {StringBuilder stringBuilder = new StringBuilder();
       stringBuilder.AppendLine("Id,FirstName,LastName");
       foreach (var author in authors)
       {stringBuilder.AppendLine($"{author.Id},
           {author.FirstName},{author.LastName}");
       }
      return File(Encoding.UTF8.GetBytes
      (stringBuilder.ToString()), "text/csv", "authors.csv");
    }
    catch
    {return Error();
    }
}

将数据导出成 XLSX 文件

Excel 中的 workbook 是由若干个 worksheet 组成,上面的代码可用来生成一个 workbook。


var workbook = new XLWorkbook();

接下来生成一个 worksheet,而后在 worksheet 中填一些数据,代码如下:


IXLWorksheet worksheet = workbook.Worksheets.Add("Authors");
worksheet.Cell(1, 1).Value = "Id";
worksheet.Cell(1, 2).Value = "FirstName";
worksheet.Cell(1, 3).Value = "LastName";
for (int index = 1; index <= authors.Count; index++)
{worksheet.Cell(index + 1, 1).Value = authors[index - 1].Id;
   worksheet.Cell(index + 1, 2).Value = authors[index - 1].FirstName;
   worksheet.Cell(index + 1, 3).Value = authors[index - 1].LastName;
}

最初,将 workbook 转成 内存流 (memory stream) 再通过 Controller.Action 的 FileContentResult 返回给客户端,代码如下:


using (var stream = new MemoryStream())
{workbook.SaveAs(stream);
     var content = stream.ToArray();
     return File(content, contentType, fileName);
}

下载 Excel

上面是导出 Excel 所有的业务逻辑代码,这个 Action 实现了 Excel 导出性能。


        public IActionResult DownloadExcelDocument()
        {
            string contentType = "application/vnd.openxmlformats-
            officedocument.spreadsheetml.sheet";
            string fileName = "authors.xlsx";
            try
            {using (var workbook = new XLWorkbook())
                {
                    IXLWorksheet worksheet =
                    workbook.Worksheets.Add("Authors");
                    worksheet.Cell(1, 1).Value = "Id";
                    worksheet.Cell(1, 2).Value = "FirstName";
                    worksheet.Cell(1, 3).Value = "LastName";
                    for (int index = 1; index <= authors.Count; index++)
                    {worksheet.Cell(index + 1, 1).Value =
                        authors[index - 1].Id;
                        worksheet.Cell(index + 1, 2).Value =
                        authors[index - 1].FirstName;
                        worksheet.Cell(index + 1, 3).Value =
                        authors[index - 1].LastName;
                    }
                    using (var stream = new MemoryStream())
                    {workbook.SaveAs(stream);
                        var content = stream.ToArray();
                        return File(content, contentType, fileName);
                    }
                }
            }
            catch(Exception ex)
            {return Error();
            }
        }

这篇就是 ClosedXML 的所有内容,如果你想对 Excel 中的数据进行更加简单的操控,能够应用 EPPlus 或者 NPOI,对于 ClosedXML 的更多内容,可参考:https://github.com/ClosedXML/…

译文链接:https://www.infoworld.com/art…

正文完
 0