1.安装对应的NuGet包
2.编写对应的NPOIHelper.cs
这里表头是业务代码中传入的一个字符串数组,也可以直接用dataset的columnName代替
创建的顺序是 book -> sheet -> row;同时也可以进行简单的style定义
using Microsoft.AspNetCore.Hosting;
using NPOI.SS.UserModel;
using System;
using System.Data;
using System.IO;
namespace ErpBarCodeService.Utils
{
public class NpoiHelper
{
private static IHostingEnvironment _environment;
public NpoiHelper(IHostingEnvironment iEnvironment)
{
_environment = iEnvironment;
}
/// <summary>
///
/// </summary>
/// <param name="dt">数据表</param>
/// <param name="title">文件名称</param>
/// <param name="headerarr">表头</param>
/// <param name="resultMsg">错误信息</param>
/// <param name="excelFilePath">文件路径</param>
/// <returns></returns>
public static bool NpoiExcel(DataTable dt,string title, string[] headerarr, out string resultMsg, out string excelFilePath)
{
bool result = true;
excelFilePath = "";
resultMsg = "";
try
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1");
NPOI.SS.UserModel.IRow headerrow = sheet.CreateRow(0);
ICellStyle style = book.CreateCellStyle();
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = VerticalAlignment.Center;
for (int i = 0; i < headerarr.Length; i++)
{
ICell headercell = headerrow.CreateCell(i);
headercell.CellStyle = style;
headercell.SetCellValue(headerarr[i]);
}
// i 为行 j 为列
for (int i = 1; i < dt.Rows.Count + 1; i++)
{
IRow temprow = sheet.CreateRow(i);
for (int j = 0; j < headerarr.Length; j++)
{
ICell cell = temprow.CreateCell(j);
cell.CellStyle = style;
cell.SetCellValue(dt.Rows[i-1][j].ToString());
}
}
//保存文件 应用程序目录
string rootPath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var uploadPath = rootPath + "/";
string excelFileName = title + ".xls";
string excelPath = uploadPath + excelFileName;
var fileStream = new FileStream(excelPath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
book.Write(fileStream);
fileStream.Close(); // 关闭文件流
fileStream.Dispose(); // 释放流所占用的资源
//excel文件保存的相对路径,提供给前端下载
var relativePositioning = "/" + excelFileName;
excelFilePath = relativePositioning;
}
catch (Exception e)
{
result = false;
resultMsg = e.Message;
}
return result;
}
}
}
3.在代码中调用即可
bool export = NpoiHelper.NpoiExcel(ds.Tables[0], filename, headerarr, out resultMsg, out excelFilePath);
if (export)
{
return new { code = 0, msg = excelFilePath };
}
else
{
return new { code = -1, msg = resultMsg };
}