Excel模版建議把需要添加數據行的樣式設置好
模版樣式,導出后效果
【2017-11-22 對獲取需插入數據的首行樣式有時為空報錯修改】

/// <summary> /// 根據模版導出Excel /// </summary> /// <param name="templateFile">模版路徑(包含后綴) 例:"~/Template/Exceltest.xls"</param> /// <param name="strFileName">文件名稱(不包含后綴) 例:"Excel測試"</param> /// <param name="source">源DataTable</param> /// <param name="cellKes">需要導出的對應的列字段 例:string[] cellKes = { "Date","Remarks" };</param> /// <param name="rowIndex">從第幾行開始創建數據行,第一行為0</param> /// <returns>是否導出成功</returns> public static string ExportScMeeting(string templateFile, string strFileName, DataTable source, string[] cellKes, int rowIndex) { templateFile = HttpContext.Current.Server.MapPath(templateFile); int cellCount = cellKes.Length;//總列數,第一列為0 IWorkbook workbook = null; try { using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read)) { if (Path.GetExtension(templateFile) == ".xls") workbook = new HSSFWorkbook(file); else if (Path.GetExtension(templateFile) == ".xlsx") workbook = new XSSFWorkbook(file); } ISheet sheet = workbook.GetSheetAt(0); if (sheet != null && source != null && source.Rows.Count > 0) { IRow row; ICell cell; //獲取需插入數據的首行樣式 IRow styleRow = sheet.GetRow(rowIndex); if (styleRow == null) { for (int i = 0, len = source.Rows.Count; i < len; i++) { row = sheet.CreateRow(rowIndex); //創建列並插入數據 for (int index = 0; index < cellCount; index++) { row.CreateCell(index) .SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty); } rowIndex++; } } else { for (int i = 0, len = source.Rows.Count; i < len; i++) { row = sheet.CreateRow(rowIndex); row.HeightInPoints = styleRow.HeightInPoints; row.Height = styleRow.Height; //創建列並插入數據 for (int index = 0; index < cellCount; index++) { cell = row.CreateCell(index, styleRow.GetCell(index).CellType); cell.CellStyle = styleRow.GetCell(index).CellStyle; cell.SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty); } rowIndex++; } } } return NPOIExport(strFileName + "." + templateFile.Split('.')[templateFile.Split('.').Length - 1], workbook); } catch (Exception ex) { return ex.Message; } }
附屬方法

public static string NPOIExport(string fileName, IWorkbook workbook) { try { System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ClearHeaders(); HttpContext.Current.Response.Cache.SetCacheability(System.Web.HttpCacheability.Private); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8; HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.End(); ms.Close(); ms.Dispose(); return "導出成功"; } catch (Exception ex) { return "導出失敗"; } }
調用方法
/// <summary> /// 后台調用方法 /// </summary> /// <returns></returns> public string Exc() { return ExcelUtil.ExportScMeeting("~/Template/MonthlyRepair.xls", "ExcelName", new DataTable(), new string[2] { "name1", "name2" }, 0); } //前台js調用 window.open('@Url.Action("Exc")');
注:需要在指定行插入數據的話請使用NPOI自帶的方法對Excel進行操作
sheet.ShiftRows(0/*開始行*/, sheet.LastRowNum/*結束行*/, 10/*插入總行數,移動大小(行數)--往下移動*/, true/*是否復制行高*/, false/*是否重置行高*/);
示例方法代碼

/// <summary> /// 根據模版導出Excel /// </summary> /// <param name="templateFile">模版路徑(包含后綴) 例:"~/Template/Exceltest.xls"</param> /// <param name="strFileName">文件名稱(不包含后綴) 例:"Excel測試"</param> /// <param name="isCover">是否向下覆蓋,不覆蓋則在rowIndex行插入數據</param> /// <param name="source">源DataTable</param> /// <param name="cellKes">需要導出的對應的列字段 例:string[] cellKes = { "Date","Remarks" };</param> /// <param name="rowIndex">從第幾行開始創建數據行,第一行為0</param> /// <returns>是否導出成功</returns> public static string ExportScMeeting(string templateFile, string strFileName, bool isCover, DataTable source, string[] cellKes, int rowIndex) { templateFile = HttpContext.Current.Server.MapPath(templateFile); int cellCount = cellKes.Length;//總列數,第一列為0 IWorkbook workbook = null; try { using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read)) { workbook = new HSSFWorkbook(file); } ISheet sheet = workbook.GetSheetAt(0); if (sheet != null && source != null && source.Rows.Count > 0) { IRow row; //是否向下覆蓋 if (!isCover) sheet.ShiftRows(rowIndex, sheet.LastRowNum, source.Rows.Count, true, false); //獲取需插入數據的首行樣式 IRow styleRow = sheet.GetRow(isCover ? rowIndex : (rowIndex + source.Rows.Count)); for (int i = 0, len = source.Rows.Count; i < len; i++) { row = sheet.CreateRow(rowIndex); //創建列並插入數據 for (int index = 0; index < cellCount; index++) { row.CreateCell(index) .SetCellValue(!(source.Rows[i][cellKes[index]] is DBNull) ? source.Rows[i][cellKes[index]].ToString() : string.Empty); } rowIndex++; } } return NPOIExport(strFileName + ".xls", workbook); } catch (Exception ex) { return ex.Message; } }