转自:http://www.yongfa365.com/Item/NPOI-MyXls-DataTable-To-Excel-From-Excel.html
NPOI开源地址:http://npoi.codeplex.com/
NPOI中文文档:http://www.cnblogs.com/tonyqus/archive/2009/04/12/1434209.html
MyXls开源地址:http://sourceforge.net/projects/myxls/
NPOI 快速入门例子:
- /// <summary>
- /// NPOI简单Demo,快速入门代码
- /// </summary>
- /// <param name="dtSource"></param>
- /// <param name="strFileName"></param>
- /// <remarks>NPOI认为Excel的第一个单元格是:(0,0)</remarks>
- /// <Author>柳永法 http://www.yongfa365.com/ 2010-5-8 22:21:41</Author>
- public static void ExportEasy(DataTable dtSource, string strFileName)
- {
- HSSFWorkbook workbook = new HSSFWorkbook();
- HSSFSheet sheet = workbook.CreateSheet();
- //填充表头
- HSSFRow dataRow = sheet.CreateRow(0);
- foreach (DataColumn column in dtSource.Columns)
- {
- dataRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
- }
- //填充内容
- for (int i = 0; i < dtSource.Rows.Count; i++)
- {
- dataRow = sheet.CreateRow(i + 1);
- for (int j = 0; j < dtSource.Columns.Count; j++)
- {
- dataRow.CreateCell(j).SetCellValue(dtSource.Rows[i][j].ToString());
- }
- }
- //保存
- using (MemoryStream ms = new MemoryStream())
- {
- using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
- {
- workbook.Write(fs);
- }
- }
- workbook.Dispose();
- }
接下来是柳永法(yongfa365)'Blog封装的可以用在实际项目中的类,实现的功能有(仅NPOI):
- 支持web及winform从DataTable导出到Excel。
- 生成速度很快。
- 准确判断数据类型,不会出现身份证转数值等上面提到的一系列问题。
- 如果单页条数大于65535时会新建工作表。
- 列宽自适应。
- 支持读取Excel。
- 调用方便,只一调用一个静态类就OK了。
因为测试期间发现MyXls导出速度要比NPOI慢3倍,而NPOI既能满足我们的导出需求,又能很好的满足我们的导入需求,所以只针对NPOI进行全方位功能实现及优化。
NPOI导入导出相关类: