用netcore语言用NPOI写一个Excel导出功能
下面是一个使用NPOI库在.NET Core中实现Excel导出功能的示例代码:
首先,确保你已经在项目中安装了NPOI NuGet包。可以通过在Package Manager Console中运行以下命令来安装:
Install-Package NPOI
然后,创建一个名为ExcelExporter.cs的新类,并添加以下代码:
using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
public class ExcelExporter
{
public static byte[] Export(List<Dictionary<string, object>> data)
{
// 创建工作簿
IWorkbook workbook = new XSSFWorkbook();
// 创建工作表
ISheet sheet = workbook.CreateSheet("Sheet1");
// 创建表头
IRow headerRow = sheet.CreateRow(0);
int columnIndex = 0;
foreach (string columnName in data[0].Keys)
{
headerRow.CreateCell(columnIndex).SetCellValue(columnName);
columnIndex++;
}
// 填充数据
int rowIndex = 1;
foreach (Dictionary<string, object> rowData in data)
{
IRow dataRow = sheet.CreateRow(rowIndex);
columnIndex = 0;
foreach (object value in rowData.Values)
{
dataRow.CreateCell(columnIndex).SetCellValue(value.ToString());
columnIndex++;
}
rowIndex++;
}
// 将工作簿转换为字节数组
using (MemoryStream stream = new MemoryStream())
{
workbook.Write(stream);
return stream.ToArray();
}
}
}
这个ExcelExporter类有一个静态方法Export,接受一个List<Dictionary<string, object>>类型的参数data,其中每个Dictionary对象表示一行数据,键是列名,值是对应的单元格的值。
要导出Excel,只需调用该方法并提供数据,然后将返回的字节数组保存为Excel文件即可。以下是一个导出Excel的示例代码:
List<Dictionary<string, object>> data = new List<Dictionary<string, object>>();
Dictionary<string, object> row1 = new Dictionary<string, object>
{
{ "Name", "John" },
{ "Age", 25 },
{ "Email", "john@example.com" }
};
data.Add(row1);
Dictionary<string, object> row2 = new Dictionary<string, object>
{
{ "Name", "Jane" },
{ "Age", 30 },
{ "Email", "jane@example.com" }
};
data.Add(row2);
byte[] excelFile = ExcelExporter.Export(data);
File.WriteAllBytes("exported_data.xlsx", excelFile);
这个示例将创建一个包含两行数据的Excel文件,并将其保存为名为exported_data.xlsx的文件。
希望这个示例对你有帮助
原文地址: https://www.cveoy.top/t/topic/hLP5 著作权归作者所有。请勿转载和采集!