用NPOI插件实现Excel导出
1.只需要引用NPOI的dll文件》创建Excel模版》引用创建好的Excel模版,OK,Done!就是这么简单
注意事项:要导出的数据源列的数量应和模版定义的列的数量相同
示例demo(下载)
using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; namespace testDemoNpoi { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void exlBtn_Click(object sender, EventArgs e) { int sucCount = 0; int errorCount = 0; #region 数据源赋值 DataTable ds = new DataTable(); ds.Columns.Add("序号"); ds.Columns.Add("1列"); ds.Columns.Add("2列"); ds.Columns.Add("3列"); ds.Columns.Add("4列"); ds.Columns.Add("5列"); ds.Columns.Add("6列"); for (int i = 0; i < 100; i++) { ds.Rows.Add(i, "1列", "2列", "3列", "4列", "5列", "6列"); } #endregion //导出 string TemplateUrl = "~/XLSTemplate/自定义导出模版.xls"; HSSFWorkbook hssfworkbook = ExcelHelper.DataSetExportToExcel(ds, TemplateUrl, "Sheet1", 2); ISheet sheet = hssfworkbook.GetSheet("Sheet1"); string dateTimeString = DateTime.Now.ToString("yyyy-MM-dd HH点mm分"); //填充表头内容 string strReportTitle = "自定义导出-【" + dateTimeString + "】"; sheet.GetRow(0).GetCell(0).SetCellValue(strReportTitle); sheet.GetRow(1).GetCell(0).SetCellValue("该数据统计报表截止至" + dateTimeString); //下载 ExcelHelper.DownloadExcelFile(hssfworkbook, strReportTitle + ".xls"); } } } using System.Web; using System.Data; using System.Data.OleDb; using System.IO; using NPOI.SS.UserModel; using System; using NPOI.HSSF.UserModel; namespace testDemoNpoi { public abstract class ExcelHelper { /// <summary> /// 创建一个NPOI工作薄 /// </summary> public static HSSFWorkbook CreateWorkbook(string TemplateUrl) { HSSFWorkbook hssfworkbook; using (FileStream file = new FileStream(HttpContext.Current.Server.MapPath(TemplateUrl), FileMode.Open, FileAccess.Read)) { //启动NPOI引擎 hssfworkbook = new HSSFWorkbook(file); file.Close(); } return hssfworkbook; } /// <summary> /// 将DataSet中的数据导出到Excel /// </summary> /// <param name="ds">要导出的数据,DataSet格式</param> /// <param name="TemplateUrl">模板文件路径</param> /// <param name="SheetName">表名</param> /// <param name="HeaderRowIndex">表头序号</param> /// <returns></returns> public static HSSFWorkbook DataSetExportToExcel(DataSet ds, string TemplateUrl, string SheetName,int HeaderRowIndex) { HSSFWorkbook hssfworkbook = CreateWorkbook(TemplateUrl); if (SheetName == "") { SheetName = "Sheet1"; } ISheet sheet = hssfworkbook.GetSheet(SheetName); using (FileStream file = new FileStream(HttpContext.Current.Server.MapPath(TemplateUrl), FileMode.Open, FileAccess.Read)) { IRow dataRow; for (int i = 0; i < ds.Tables[0].Rows.Count; i++) { dataRow = sheet.CreateRow(i + HeaderRowIndex + 2); dataRow.HeightInPoints = sheet.GetRow(HeaderRowIndex + 1).HeightInPoints; for (int j = 0; j < ds.Tables[0].Columns.Count; j++) { if (ds.Tables[0].Rows[i][j].ToString().Trim() == "") { continue; } switch (ds.Tables[0].Columns[j].DataType.ToString()) { case "System.Int16"://integer case "System.Int32": case "System.Int64": int intV = 0; int.TryParse(ds.Tables[0].Rows[i][j].ToString(), out intV); dataRow.CreateCell(j).SetCellValue(intV); break; case "System.Decimal"://float case "System.Double": double doubV = 0; double.TryParse(ds.Tables[0].Rows[i][j].ToString(), out doubV); dataRow.CreateCell(j).SetCellValue(doubV); break; case "System.DateTime"://datetime DateTime DateTimeV; DateTime.TryParse(ds.Tables[0].Rows[i][j].ToString(), out DateTimeV); dataRow.CreateCell(j).SetCellValue(DateTimeV); break; case "System.DBNull": dataRow.CreateCell(j).SetCellValue(""); break; default://string dataRow.CreateCell(j).SetCellValue(ds.Tables[0].Rows[i][j].ToString()); break; } try { dataRow.GetCell(j).CellStyle = sheet.GetRow(HeaderRowIndex + 1).GetCell(j).CellStyle; } catch (Exception ex) { } } } try { sheet.ShiftRows((HeaderRowIndex + 2), sheet.LastRowNum, -1); } catch (Exception ex) { } return hssfworkbook; } } /// <summary> /// 将DataSet中的数据导出到Excel,并保存到指定路径 /// </summary> /// <param name="ds">要导出的数据,DataSet格式</param> /// <param name="TemplateUrl">模板文件路径</param> /// <param name="SheetName">表名</param> /// <param name="HeaderRowIndex">表头序号</param> /// <param name="XLSSavePath">结果保存路径</param> /// <returns></returns> public static void DataSetExportToExcel(DataSet ds, string TemplateUrl, string SheetName, int HeaderRowIndex, string XLSSavePath) { HSSFWorkbook hssfworkbook = DataSetExportToExcel(ds, TemplateUrl, SheetName, HeaderRowIndex); //另存为 using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath("~" + XLSSavePath), FileMode.Create, FileAccess.ReadWrite)) { hssfworkbook.Write(f); } } /// <summary> /// 将DataSet中的数据导出到Excel /// </summary> /// <param name="ds">要导出的数据,DataSet格式</param> /// <param name="TemplateUrl">模板文件路径</param> /// <param name="SheetName">表名</param> /// <param name="HeaderRowIndex">表头序号</param> /// <returns></returns> public static HSSFWorkbook DataSetExportToExcel(DataTable ds, string TemplateUrl, string SheetName, int HeaderRowIndex) { HSSFWorkbook hssfworkbook = CreateWorkbook(TemplateUrl); if (SheetName == "") { SheetName = "Sheet1"; } ISheet sheet = hssfworkbook.GetSheet(SheetName); using (FileStream file = new FileStream(HttpContext.Current.Server.MapPath(TemplateUrl), FileMode.Open, FileAccess.Read)) { IRow dataRow; for (int i = 0; i < ds.Rows.Count; i++) { dataRow = sheet.CreateRow(i + HeaderRowIndex + 2); dataRow.HeightInPoints = sheet.GetRow(HeaderRowIndex + 1).HeightInPoints; for (int j = 0; j < ds.Columns.Count; j++) { if (ds.Rows[i][j].ToString().Trim() == "") { continue; } switch (ds.Columns[j].DataType.ToString()) { case "System.Int16"://integer case "System.Int32": case "System.Int64": int intV = 0; int.TryParse(ds.Rows[i][j].ToString(), out intV); dataRow.CreateCell(j).SetCellValue(intV); break; case "System.Decimal"://float case "System.Double": double doubV = 0; double.TryParse(ds.Rows[i][j].ToString(), out doubV); dataRow.CreateCell(j).SetCellValue(doubV); break; case "System.DateTime"://datetime DateTime DateTimeV; DateTime.TryParse(ds.Rows[i][j].ToString(), out DateTimeV); dataRow.CreateCell(j).SetCellValue(DateTimeV); break; case "System.DBNull": dataRow.CreateCell(j).SetCellValue(""); break; default://string dataRow.CreateCell(j).SetCellValue(ds.Rows[i][j].ToString()); break; } try { dataRow.GetCell(j).CellStyle = sheet.GetRow(HeaderRowIndex + 1).GetCell(j).CellStyle; } catch (Exception ex) { } } } try { sheet.ShiftRows((HeaderRowIndex + 2), sheet.LastRowNum, -1); } catch (Exception ex) { } return hssfworkbook; } } /// <summary> /// 将DataSet中的数据导出到Excel,并保存到指定路径 /// </summary> /// <param name="ds">要导出的数据,DataSet格式</param> /// <param name="TemplateUrl">模板文件路径</param> /// <param name="SheetName">表名</param> /// <param name="HeaderRowIndex">表头序号</param> /// <param name="XLSSavePath">结果保存路径</param> /// <returns></returns> public static void DataSetExportToExcel(DataTable ds, string TemplateUrl, string SheetName, int HeaderRowIndex, string XLSSavePath) { HSSFWorkbook hssfworkbook = DataSetExportToExcel(ds, TemplateUrl, SheetName, HeaderRowIndex); //另存为 using (FileStream f = new FileStream(HttpContext.Current.Server.MapPath("~" + XLSSavePath), FileMode.Create, FileAccess.ReadWrite)) { hssfworkbook.Write(f); } } /// <summary> /// 下载Excel报表文件 /// </summary> /// <param name="hssfworkbook">NPOI工作薄</param> /// <param name="DefaultName">默认文件名称</param> public static void DownloadExcelFile(HSSFWorkbook hssfworkbook, string DefaultName) { HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(DefaultName)); HttpContext.Current.Response.Clear(); MemoryStream file = new MemoryStream(); hssfworkbook.Write(file); file.WriteTo(HttpContext.Current.Response.OutputStream); HttpContext.Current.Response.End(); } } }