在本文中,我们将探讨如何将数据从数据库导出到 Excel 文件并创建端点进行下载。我们将使用 NPOI 库来生成 Excel 文件。
首先,我们必须从 NuGet 包管理器安装 NPOI 库:
接下来,我们还将安装 Entity Framework Core。我们将使用 Entity Framework Core Sqlite 来简化该过程。我们还可以使用其他提供程序,例如 SqlServer 或 PostgreSQL。
如果使用的是 .NET 6.0,请确保选择实体框架的 6.x.x (6.0.20) 版本。
我们将使用实体模型,表示我们要存储在数据库中的数据结构。
namespace DownloadExcel.WebApi;
public class Product
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
public bool IsActive { get; set; }
public DateTime ExpiryDate { get; set; }
}
Product 类具有最常用的数据类型(string、int、decimal、bool、DateTime)的属性。
此外,我们还创建一个数据库上下文,该上下文继承自 Entity Framework Core 的 DbContext 类。此上下文将处理与数据库的通信。
using Microsoft.EntityFrameworkCore;
namespace UploadExcel.WebApi;
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> opt) : base(opt)
{
}
public DbSet<Product> Products { get; set; }
}
ExcelHelper 类是一个自定义类,它提供了一个帮助程序方法,用于从数据列表创建 Excel 文件。
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
namespace UploadExcel.WebApi;
public static class ExcelHelper
{
public static byte[] CreateFile<T>(List<T> source)
{
var workbook = new XSSFWorkbook();
var sheet = workbook.CreateSheet("Sheet1");
var rowHeader = sheet.CreateRow(0);
var properties = typeof(T).GetProperties();
//header
var font = workbook.CreateFont();
font.IsBold = true;
var style = workbook.CreateCellStyle();
style.SetFont(font);
var colIndex = 0;
foreach (var property in properties)
{
var cell = rowHeader.CreateCell(colIndex);
cell.SetCellValue(property.Name);
cell.CellStyle = style;
colIndex++;
}
//end header
//content
var rowNum = 1;
foreach (var item in source)
{
var rowContent = sheet.CreateRow(rowNum);
var colContentIndex = 0;
foreach (var property in properties)
{
var cellContent = rowContent.CreateCell(colContentIndex);
var value = property.GetValue(item, null);
if (value == null)
{
cellContent.SetCellValue("");
}
else if (property.PropertyType == typeof(string))
{
cellContent.SetCellValue(value.ToString());
}
else if (property.PropertyType == typeof(int) || property.PropertyType == typeof(int?))
{
cellContent.SetCellValue(Convert.ToInt32(value));
}
else if (property.PropertyType == typeof(decimal) || property.PropertyType == typeof(decimal?))
{
cellContent.SetCellValue(Convert.ToDouble(value));
}
else if (property.PropertyType == typeof(DateTime) || property.PropertyType == typeof(DateTime?))
{
var dateValue = (DateTime)value;
cellContent.SetCellValue(dateValue.ToString("yyyy-MM-dd"));
}
else cellContent.SetCellValue(value.ToString());
colContentIndex++;
}
rowNum++;
}
//end content
var stream = new MemoryStream();
workbook.Write(stream);
var content = stream.ToArray();
return content;
}
}
该方法是 ExcelHelper 类中的静态方法,用于从数据列表创建 Excel 电子表格。它采用通用类型 T 和 a 作为参数。T 表示列表中包含的数据类型。CreateFile()List<T>
若要生成 Excel 文件,该方法将创建一个新的 XSSFWorkbook 对象,并使用它来创建名为“Sheet1”的新工作表。然后,它使用该方法创建具有粗体字体的标题行,以获取泛型类型 T 的属性。然后,它通过循环访问传递给方法的数据列表并循环访问泛型类型 T 的属性,以使用数据列表中的相应属性值填充每行中的单元格,从而将行添加到工作表中。CreateFile()GetProperties()
接下来,我们必须创建 ProductController 类。
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace UploadExcel.WebApi.Controllers;
[ApiController]
[Route("products")]
public class ProductController : ControllerBase
{
private readonly DataContext _context;
public ProductController(DataContext context)
{
_context = context;
}
[HttpGet("download")]
public async Task<FileResult> Download(CancellationToken ct)
{
var products = await _context.Products.ToListAsync(ct);
var file = ExcelHelper.CreateFile(products);
return File(file, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "products.xlsx");
}
}
该方法是 ProductController 中的 HttpGet 方法,它返回一个包含数据库中产品数据的 Excel 电子表格。Download()
修改_Program.cs_以注册 DataContext 类并初始化数据库:
using Microsoft.EntityFrameworkCore;
using UploadExcel.WebApi;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DataContext>(opt => opt.UseSqlite("Data Source=data.db"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
var context = app.Services.CreateScope().ServiceProvider.GetRequiredService\<DataContext>();
context.Database.EnsureCreated();
app.UseHttpsRedirection();
app.MapControllers();
app.Run();
在下载文件之前,我们必须将产品数据插入数据库。
_context.Products.Add(new Product
{
Id = Guid.NewGuid(),
Name = "Product 1",
Quantity = 10,
Price = 100,
IsActive = true,
ExpiryDate = DateTime.Now.AddDays(10)
});
_context.Products.Add(new Product
{
Id = Guid.NewGuid(),
Name = "Product 2",
Quantity = 20,
Price = 200,
IsActive = true,
ExpiryDate = DateTime.Now.AddDays(20)
});
_context.SaveChanges();
按 F5 运行应用程序。可以通过访问下载 URL 下载文件:https://localhost:{PORT}/products/download
源代码获取:公众号回复消息【code:27223
】