NPOI导出Excel-树状格式.docx
文本预览下载声明
? ? ? ??大家都知道使用NPOI导出Excel格式数据 很简单,网上一搜,到处都有示例代码。? ? ? ? ?因为工作的关系,经常会有处理各种数据库数据的场景,其中处理Excel 数据导出,以备客户人员确认数据,场景很常见。? ? ? ? ?一个系统开发出来,系统要运行起来,很多数据要初始化,这个时候也是需要客户提供各种业务的基础数据。客户提供的数据中,其中除了word、pdf,最常见的就是Excel。? ? ? ? 废话不多说,直接上图上代码:? ? ? 如图,??? ? ? ? 左侧三列,作为 一个系统 所有菜单的树状结构。? ? ? ? ?其他列 以用户的信息(如用户名、登录名) 作为表头,需要注意的是,在整理数据进行导出时,需保证列名不能重复。??publicstaticvoidDataTree(string path, DataTable table, inttreeIndex = 10000) {using (FileStreamfs = newFileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) {IWorkbookworkBook = newHSSFWorkbook();//现在使用的仍然是生成Excel2003的Excel文件,由于03对行数(65535)和列数(255)有限制,所以当数据超出范围后难免出错 //ArgumentException: Invalid column index (256). Allowable column range for BIFF8 is (0..255) or (A..IV) ...if (Path.GetExtension(path).Equals(.xlsx, System.StringComparison.OrdinalIgnoreCase)) {workBook = newXSSFWorkbook(); }stringsheetName = string.IsNullOrWhiteSpace(table.TableName) ? Sheet1 :table.TableName;ISheet sheet = workBook.CreateSheet(sheetName);IRow row = null;intcolNum = table.Columns.Count;if (treeIndex table.Columns.Count || treeIndex 0) {colNum = treeIndex; }ICellStylecellCenterStyle = GetCenter(workBook);intbeginNum = 1;//排除列头,从1开始 //处理表格列头row = sheet.CreateRow(beginNum - 1);for (int i = 0; i table.Columns.Count; i++) {stringstrVal = table.Columns[i].ColumnName;ICell cell = row.CreateCell(i);cell.SetCellValue(strVal);cell.CellStyle = cellCenterStyle;row.Height = 350;sheet.AutoSizeColumn(i); }//处理数据内容for (int i = 0; i table.Rows.Count; i++) {row = sheet.CreateRow(beginNum + i);row.Height = 250;for (int j = 0; j table.Columns.Count; j++) {stringstrVal = table.Rows[i][j].ToString();ICellcurrCell = row.CreateCell(j);currCell.SetCellValue(strVal);currCell.CellStyle = cellCenterStyle;sheet.SetColumnWidth(j, 256 * 15); } }for (int i = 0; i colNum;
显示全部