1 /// <summary> 2 /// 绑定数据的方法 3 /// </summary> 4 /// <param name="ssfworkbook">HSSFWorkbook</param> 5 /// <param name="sheet1">HSSFSheet</param> 6 /// <param name="cateDt">数据源</param> 7 /// <param name="sheetName">页名</param> 8 /// <param name="dispName">显示名称</param> 9 /// <param name="row">属于第几列</param> 10 /// <param name="nextCount">相隔下一列的位置(只要有一列为1,后面便都为1,以此类推)</param> 11 private void GetCategoryData(HSSFWorkbook ssfworkbook, HSSFSheet sheet1, DataTable cateDt, string sheetName, string dispName, int row, int nextCount) 12 { 13 try 14 { 15 HSSFSheet sheet2 = ssfworkbook.CreateSheet("Sht" + sheetName); 16 int indexCate = 0; 17 ssfworkbook.SetSheetHidden(row - nextCount, true);//隐藏 18 19 foreach (DataRow cateItem in cateDt.Rows) 20 { 21 sheet2.CreateRow(indexCate).CreateCell(0).SetCellValue(cateItem[dispName].ToString());//列数据 22 indexCate++; 23 } 24 HSSFName range = ssfworkbook.CreateName();//创建名称 25 range.Reference = "Sht" + sheetName + "!$A$1:$A$" + indexCate;//格式 26 range.NameName = sheetName; 27 28 //将下拉列表添加 29 CellRangeAddressList regions = null; 30 regions = new CellRangeAddressList(1, 65535, row - 1, row - 1); 31 DVConstraint constraint = DVConstraint.CreateFormulaListConstraint(sheetName); 32 HSSFDataValidation dataValidate = new HSSFDataValidation(regions, constraint); 33 sheet1.AddValidationData(dataValidate); 34 } 35 catch { } 36 }
1 /// <summary> 2 /// 设置Excel表头(数组Length必须相同) 3 /// </summary> 4 /// <param name="strName">Excel中的名称</param> 5 /// <param name="width">宽</param> 6 /// <param name="headerRow">HSSFRow</param> 7 /// <param name="sheet1">HSSFSheet</param> 8 /// <param name="HSSFWorkbook">ssfworkbook</param> 9 private string SetUpExcelTitle(HSSFWorkbook ssfworkbook, string[] strName, int[] width, HSSFRow headerRow, HSSFSheet sheet1) 10 { 11 try 12 { 13 if (strName.Length != width.Length) 14 { 15 return "数组长度不同!"; 16 } 17 HSSFFont fontTitle = ssfworkbook.CreateFont(); 18 fontTitle.FontHeightInPoints = 11; 19 fontTitle.Boldweight = HSSFFont.BOLDWEIGHT_NORMAL; 20 HSSFCellStyle hssfCellTitle = ssfworkbook.CreateCellStyle(); 21 hssfCellTitle.SetFont(fontTitle); 22 23 for (int i = 0; i < strName.Length; i++) 24 { 25 //设置表头 26 headerRow.CreateCell(i).SetCellValue(strName[i]); 27 //设置表头的宽度 28 sheet1.SetColumnWidth(i, width[i]); 29 headerRow.GetCell(i).CellStyle = hssfCellTitle; 30 } 31 return "ok"; 32 } 33 catch (Exception ex) 34 { 35 return ex.Message; 36 } 37 }
1 /// <summary> 2 /// 设置Excel内容 3 /// </summary> 4 /// <param name="values">内容</param> 5 /// <param name="dataRow">HSSFRow</param> 6 private void SetUpExcelContent(string[] values, HSSFRow dataRow) 7 { 8 for (int i = 0; i < values.Length; i++) 9 { 10 //填充数据 11 dataRow.CreateCell(i).SetCellValue(values[i]); 12 } 13 }
时间: 2024-12-17 08:51:03