感謝群里的各位朋友的指導和教學,感謝Tony Qu的熱心指導,感謝阿修羅兄提供的Excelhelper類
談談個人對Excel的理解,結合NPOI,個人水平一般般,菜鳥一只
Excel 打開后,分為sheet-文件簿,Rows-行,Cell-單元格
要基於模板生成EXCEL,首先我們要明白的是我們要填充的數據在整個Excel的sheet中是處於頭,還是尾部,還是中間
我是這樣理解的,如果模板是含有風格的,比如說我這種含有三行內容的,計算的話,需要的模板列應該只包含下面這個表頭(模板XLS)
系統 | XXXX系統 | 數據庫表名 | BC(XX表) | ||||||
序號 | 字 段 名 稱 | 數 據 屬 性 | 邏 輯 條 件 | ||||||
中 文 | 英 文 | 類型 | 長度 | 小數 | 單位 | NULL | (數 據 值 范 圍) | (備 注) | |
而我們要生成的xls最終需要是這樣BC.7z
確定表頭無需動態生成(固定的行和列),內容(行和列不確定),表尾格式(表尾頭固定的行列,表尾內容行和列不確定)之后,我們就可以將代碼分為生成表頭,生成內容,生成表尾,接下來我就將生成內容的代碼公布出來,給大家看看,這個代碼是已經進行過重構的,是可以通用的哦,代碼里你可以清晰的看到我生成索引內容的時候也是動態的,其他代碼都是參考阿修羅兄提供的excelhelper類,如果需要查看,請到189925337(NPOI超級群)群里下載即可。
#region 單元格數據生成通用類 private static int CreateDataMethod(ISheet sheet1, ICellStyle style, DataTable dtGetRowTable, int rowIndex, HSSFCellStyle dateStyle) { foreach (DataRow row in dtGetRowTable.Rows) { #region 填充內容 HSSFRow dataRow = sheet1.CreateRow(rowIndex) as HSSFRow; foreach (DataColumn column in dtGetRowTable.Columns) { HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell; string drValue = row[column].ToString(); #region 字段類型處理 switch (column.DataType.ToString()) { case "System.String": //字符串類型 newCell.SetCellValue(drValue); newCell.CellStyle = style; break; case "System.DateTime": //日期類型 DateTime dateV; DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle; //格式化顯示 break; case "System.Boolean": //布爾型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); newCell.CellStyle = style; break; case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); newCell.CellStyle = style; break; case "System.Decimal": //浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); newCell.CellStyle = style; break; case "System.DBNull": //空值處理 newCell.SetCellValue(""); newCell.CellStyle = style; break; default: newCell.SetCellValue(drValue); newCell.CellStyle = style; break; } #endregion #region 插入留余空白列 int iLastCell = sheet1.GetRow(4).LastCellNum + 1 - dtGetRowTable.Columns.Count; for (int i = 1; i < iLastCell; i++) { HSSFCell newNullCell = dataRow.CreateCell(newCell.ColumnIndex + i) as HSSFCell; newNullCell.SetCellValue(""); newNullCell.CellStyle = style; } #endregion } #endregion rowIndex++; } return rowIndex; } #endregion
int iLastCell = sheet1.GetRow(4).LastCellNum + 1 - dtGetRowTable.Columns.Count;//這個地方是根據模板表頭所占數據計算的,這個是通用的留余做法。
源文件提供下載:Form1.7z
模板(帶表頭):表頭(模板XLS)
xls:BC.7z
其實這就是一種簡單的報表做法,下圖所示是在實際項目當中使用的數據字典功能模塊的效果圖。