NPOI的使用

时间:2024-01-03 22:18:02

简介NPOI是POI(APATCH的一个开源项目)项目的.NET版本,最初的POI只用于JAVA来操作EXCEL or WORD等微软OLE2组件项目。使用NPOI可以完成在你没有安装Office或者相应环境的机器上对WORD/EXCEL文档进行读写。

使用案例分享(NPOI针对DATATABLE导出EXCEL):

完成此任务应该准备的DLL:NPOI.DLL ,官网下载链接:http://npoi.codeplex.com/

1.将npoi.dll引用到项目的bin目录中:

NPOI的使用

2.添加完成之后,代码例子开始:

(对于这种以后项目里可能会经常使用到的工具类,本人建议直接创建一个公共的Respository,相信你懂我的用意)

这里我创建了一个ExcelHelper.cs类,其中需要引用以下几个npoi相关的namespace

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

导出的测试代码:(经过测试,可正常使用,这个方法需要优化的地方挺多,有兴趣的话可以自己拿去改善)

 public static void TableToExcelForXLS(DataTable dt, string file,string entityName) //dt:你需要导出的数据,file:导出路径,entityName:实体名称
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
//for (int i = 0; i < dt.Columns.Count; i++)
//{
string[] str = { "a", "b", "c", "d", "e", "f" };
string[] sysSelect = {"A", "B", "C", "D"};
if (entityName == "XuDaxia")
{
//表头
for (int j = ; j < str.Count(); j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(str[j]);
}
//数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}
else
{
//表头
for (int j = ; j < sysSelect.Count(); j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(sysSelect[j]);
}
//数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
}

方法调用:

  protected void btn_ExportExcel(object sender, ImageClickEventArgs e)
{
var name = DateTime.Now.ToString("yyyyMMdd") + new Random(DateTime.Now.Second).Next();//导出的Excel默认名称
var path = Server.MapPath("XUDAXIA_TEST/" + name + ".xls");//导出路径
var dt = list.ToDataTable();
string ef= "Xudaxia";
ExcelHelper.x2003.TableToExcelForXLS(dt, path, ef); //2003 版Excel示例
downloadfile(path);
}

输出参数配置:

void downloadfile(string s_path)
{
System.IO.FileInfo file = new System.IO.FileInfo(s_path);
HttpContext.Current.Response.ContentType = "application/ms-download";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();
}