.net mvc epplus简单的导出excel如何运行
时间: 2023-05-15 18:05:45 浏览: 100
excel-handler:使用ASP.Net Core Webapi,EPPlus,ExcelDataReader读取和导出Excel文件
您可以使用以下代码来导出 Excel 文件:
```
public ActionResult ExportToExcel()
{
var products = new List<Product>
{
new Product { Id = 1, Name = "Product 1", Price = 10 },
new Product { Id = 2, Name = "Product 2", Price = 20 },
new Product { Id = 3, Name = "Product 3", Price = 30 },
new Product { Id = 4, Name = "Product 4", Price = 40 },
new Product { Id = 5, Name = "Product 5", Price = 50 }
};
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package = new ExcelPackage())
{
var worksheet = package.Workbook.Worksheets.Add("Products");
worksheet.Cells["A1"].Value = "Id";
worksheet.Cells["B1"].Value = "Name";
worksheet.Cells["C1"].Value = "Price";
var row = 2;
foreach (var product in products)
{
worksheet.Cells[string.Format("A{0}", row)].Value = product.Id;
worksheet.Cells[string.Format("B{0}", row)].Value = product.Name;
worksheet.Cells[string.Format("C{0}", row)].Value = product.Price;
row++;
}
package.Save();
var memoryStream = new MemoryStream();
package.SaveAs(memoryStream);
return File(memoryStream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Products.xlsx");
}
}
```
这个示例使用 EPPlus 库来创建 Excel 文件。它创建一个包含产品信息的列表,然后将其写入 Excel 文件。最后,它将 Excel 文件作为响应返回给客户端。
阅读全文