1.在项目上右键——》管理Nuget包——》搜索NPOI——》安装
2.编写一个ExcelHelper类
class ExcelHelper
{
/// <summary>
/// 将DataTable数据保存至Excel文件
/// </summary>
/// <param name="dt"></param>
/// <param name="txtPath"></param>
/// <returns></returns>
public static bool DataTableToExcel(DataTable dt, string txtPath)
{
bool result = false;
IWorkbook workbook;
FileStream? fs = null;
IRow row;
ISheet sheet;
ICell cell;
try
{
if (dt != null && dt.Rows.Count > 0)
{
// 新建工作簿对象
workbook = new HSSFWorkbook();
sheet = workbook.CreateSheet("Sheet1");//创建一个名称为Sheet1的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数
//设置列头
row = sheet.CreateRow(0);//excel第一行设为列头
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
}
//设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 1);
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);//excel第二行开始写入数据
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(txtPath))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
}
}
MessageBox.Show("导出成功");
return result;
}
catch (Exception)
{
fs?.Close();
return false;
}
}
/// <summary>
///