您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在NPOI中實現兩級分組合并功能,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
/// <summary> /// 根據模版導出Excel -- 特別處理,每個分組帶合計 /// </summary> /// <param name="source">源DataTable</param> /// <param name="cellKeys">需要導出的對應的列字段 例:string[] cellKeys = { "Date","Remarks" };</param> /// <param name="strFileName">要保存的文件名稱(包含后綴) 例:"要保存的文件名.xls"</param> /// <param name="templateFile">模版文件名(包含路徑后綴) 例:"模板文件名.xls"</param> /// <param name="rowIndex">從第幾行開始創建數據行,第一行為0</param> /// <param name="mergeColumns">值相同時,可合并的前幾列 最多支持2列 1=只合并第一列,2=判斷前2列</param> /// <param name="isConver">是否覆蓋數據,=false,將把原數據下移。=true,將覆蓋插入行后面的數據</param> /// <param name="isTotal">是否帶小計/合計項</param> /// <param name="addAllTotal">是否添加總計項</param> /// <returns>是否導出成功</returns> public static bool Export2Template2(DataTable source, string[] cellKeys, string strFileName, string templateFile, int rowIndex, int mergeColumns, bool isConver, bool isTotal, bool addAllTotal) { bool bn = false; int cellCount = cellKeys.Length; //總列數,第一列為0 // IWorkbook workbook = null; HSSFWorkbook workbook = null; string temp0 = "", temp1 = ""; int start0 = 0, start1 = 0; // 記錄1,2列值相同的開始序號 int end0 = 0, end1 = 0;// 記錄1,2列值相同的結束序號 try { using (FileStream file = new FileStream(templateFile, FileMode.Open, FileAccess.Read)) { workbook = new HSSFWorkbook(file); } #region 定義四類數據的單元格樣式 // 內容數據格式 -- 數值 ICellStyle styleNum = workbook.CreateCellStyle(); styleNum.BorderBottom = BorderStyle.Thin; styleNum.BorderLeft = BorderStyle.Thin; styleNum.BorderRight = BorderStyle.Thin; styleNum.BorderTop = BorderStyle.Thin; // styleNum.VerticalAlignment = VerticalAlignment.Center; // styleNum.Alignment = HorizontalAlignment.Center; // 內容數據格式 -- 字符串(做居中處理) ICellStyle styleStr = workbook.CreateCellStyle(); styleStr.BorderBottom = BorderStyle.Thin; styleStr.BorderLeft = BorderStyle.Thin; styleStr.BorderRight = BorderStyle.Thin; styleStr.BorderTop = BorderStyle.Thin; styleStr.VerticalAlignment = VerticalAlignment.Center; styleStr.Alignment = HorizontalAlignment.Center; // 匯總數據格式 -- 數值 ICellStyle styleTotalNum = workbook.CreateCellStyle(); styleTotalNum.BorderBottom = BorderStyle.Thin; styleTotalNum.BorderLeft = BorderStyle.Thin; styleTotalNum.BorderRight = BorderStyle.Thin; styleTotalNum.BorderTop = BorderStyle.Thin; styleTotalNum.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; styleTotalNum.FillPattern = FillPattern.SolidForeground; styleTotalNum.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.Red.Index; // 設置字體顏色 HSSFFont ffont0 = (HSSFFont)workbook.CreateFont(); // ffont0.FontHeight = 14 * 14; // ffont0.FontName = "宋體"; ffont0.IsBold = true; //ffont0.Color = HSSFColor.Red.Index; styleTotalNum.SetFont(ffont0); // 匯總數據格式 -- 字符串(做居中處理) ICellStyle styleTotalStr = workbook.CreateCellStyle(); styleTotalStr.BorderBottom = BorderStyle.Thin; styleTotalStr.BorderLeft = BorderStyle.Thin; styleTotalStr.BorderRight = BorderStyle.Thin; styleTotalStr.BorderTop = BorderStyle.Thin; styleTotalStr.VerticalAlignment = VerticalAlignment.Center; styleTotalStr.Alignment = HorizontalAlignment.Center; styleTotalStr.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index; styleTotalStr.FillPattern = FillPattern.SolidForeground; // 設置字體顏色 HSSFFont ffont1 = (HSSFFont)workbook.CreateFont(); // ffont1.FontHeight = 14 * 14; // ffont1.FontName = "宋體"; ffont1.IsBold = true; //ffont.Color = HSSFColor.Red.Index; styleTotalStr.SetFont(ffont1); #endregion ISheet sheet = workbook.GetSheetAt(0); // 打開第一個sheet頁 if (sheet != null && source != null && source.Rows.Count > 0) // 模板內容為空,不做處理 { IRow row; for (int i = 0, len = source.Rows.Count; i < len; i++) { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 #region 第一行,寫入數據后,對變量賦初值 if (i == 0) // 第一行,賦初值 { row = sheet.CreateRow(rowIndex); #region 創建列并插入數據 //創建列并插入數據 for (int index = 0; index < cellCount; index++) { ICell cell = row.CreateCell(index); string strValue = !(source.Rows[i][cellKeys[index]] is DBNull) ? source.Rows[i][cellKeys[index]].ToString() : string.Empty; // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(strValue, out intV); cell.CellStyle = styleNum; // 設置格式 cell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": double doubV = 0; double.TryParse(strValue, out doubV); cell.CellStyle = styleNum; // 設置格式 cell.SetCellValue(doubV); break; default: cell.CellStyle = styleStr; // 設置格式 cell.SetCellValue(strValue); break; } } #endregion if (mergeColumns > 0) { temp0 = source.Rows[i][cellKeys[0]].ToString(); // 保存第1列值 start0 = rowIndex; end0 = rowIndex; } if (mergeColumns > 1) { temp1 = source.Rows[i][cellKeys[1]].ToString(); // 保存第2列值 start1 = rowIndex; end1 = rowIndex; } rowIndex++; continue; } #endregion // 不是第一行數據的處理 // 判斷1列值變化沒 string cellText0 = source.Rows[i][cellKeys[0]].ToString(); if (temp0 != cellText0) // 第1列值有變化 { #region 第2列要合并 if (mergeColumns > 1) // 第2列要合并 { if (start1 != end1) // 開始行和結束行不相同,才進行合并 { CellRangeAddress region1 = new CellRangeAddress(start1, end1, 1, 1); // 合并第二列 sheet.AddMergedRegion(region1); } #region 第2列加小計 if (isTotal) // 加小計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal1 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 插入小計數據 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal1.CreateCell(index); if (index == 0) //第1列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(temp0); continue; } if (index == 1) // 第2列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("小計"); continue; } // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); int intV = 0; int.TryParse(obj1.ToString(), out intV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } } #endregion // 合并小計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 1, 2); // 合并小計 sheet.AddMergedRegion(region0); } #endregion temp1 = source.Rows[i][cellKeys[1]].ToString(); end0++; rowIndex++; } #endregion #region 第1列要合并 if (mergeColumns > 0) // 第1列要合并 { if (start0 != end0) // 開始行和結束行不相同,才進行合并 { CellRangeAddress region0 = new CellRangeAddress(start0, end0, 0, 0); // 合并第二列 sheet.AddMergedRegion(region0); } #region 第1列加合計 if (isTotal) // 加合計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal0 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 加合計列 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal0.CreateCell(index); if (index == 0) { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("合計"); //第1列 continue; } if (index == 1) { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); // 第2列 continue; } switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' ", cellKeys[0], temp0)); int intV = 0; int.TryParse(obj1.ToString(), out intV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' ", cellKeys[0], temp0)); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } } #endregion // 合并合計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 0, 2); // 合并合計 sheet.AddMergedRegion(region0); end0++; rowIndex++; } #endregion temp0 = cellText0; } #endregion // 重新賦值 start0 = rowIndex; end0 = rowIndex; start1 = rowIndex; end1 = rowIndex; } else // 第1列值沒有變化 { end0++; // 判斷第2列是否有變化 string cellText1 = source.Rows[i][cellKeys[1]].ToString(); if (cellText1 != temp1) // 第1列沒變,第2列變化 { #region 第2列要合并 if (mergeColumns > 1) // 第2列要合并 { if (start1 != end1) // 開始行和結束行不相同,才進行合并 { CellRangeAddress region1 = new CellRangeAddress(start1, end1, 1, 1); // 合并第二列 sheet.AddMergedRegion(region1); } #region 第2列加小計 if (isTotal) // 加小計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal1 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 插入小計數據 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal1.CreateCell(index); if (index == 0) //第1列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(temp0); continue; } if (index == 1) // 第2列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("小計"); continue; } // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); int intV = 0; int.TryParse(obj1.ToString(), out intV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } } #endregion // 合并小計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 1, 2); // 合并小計 sheet.AddMergedRegion(region0); end0++; rowIndex++; } temp1 = cellText1; // 要合并,才進行重新賦值 start1 = rowIndex; end1 = rowIndex; #endregion } #endregion } else // 第1列值沒變,第2列也沒變 end1++; } // 插入當前數據 row = sheet.CreateRow(rowIndex); #region 創建行并插入當前記錄的數據 //創建行并插入當前記錄的數據 for (int index = 0; index < cellCount; index++) { ICell cell = row.CreateCell(index);<br> string strValue = !(source.Rows[i][cellKeys[index]] is DBNull) ? source.Rows[i][cellKeys[index]].ToString() : string.Empty; // 取值 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(strValue, out intV); cell.CellStyle = styleNum; cell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": double doubV = 0; double.TryParse(strValue, out doubV); cell.CellStyle = styleNum; cell.SetCellValue(doubV); break; default: cell.CellStyle = styleStr; cell.SetCellValue(strValue); break; } } #endregion // 下移一行 rowIndex++; } // 最后一條記錄的合計 #region 對第2列進行合并 if (mergeColumns > 1) // 對第2列合并 { if (start1 != end1) // 開始行和結束行不等,進行合并 { CellRangeAddress region1 = new CellRangeAddress(start1, end1, 1, 1); // 合并第二列 sheet.AddMergedRegion(region1); } #region 第2列加小計 if (isTotal) // 加小計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal1 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 插入小計數據 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal1.CreateCell(index); #region 列值處理 if (index == 0) //第1列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(temp0); continue; } if (index == 1) // 第2列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("小計"); continue; } // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); int intV = 0; int.TryParse(obj1.ToString(), out intV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' and {2} = '{3}' ", cellKeys[0], temp0, cellKeys[1], temp1)); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } #endregion } #endregion // 合并小計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 1, 2); // 合并小計 sheet.AddMergedRegion(region0); rowIndex++; end0++; } #endregion } #endregion #region 對第1列合并 if (mergeColumns > 0) // 對第1列合并 { if (start0 != end0) // 開始行和結束行不等,進行合并 { CellRangeAddress region1 = new CellRangeAddress(start0, end0, 0, 0); // 合并第二列 sheet.AddMergedRegion(region1); } #region 第1列加合計 if (isTotal) // 加合計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal0 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 插入合計數據 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal0.CreateCell(index); #region 列值處理 if (index == 0) //第1列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("合計"); continue; } if (index == 1) // 第2列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); continue; } // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' ", cellKeys[0], temp0)); int intV = 0; newcell.CellStyle = styleTotalNum; int.TryParse(obj1.ToString(), out intV); newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), string.Format("{0} = '{1}' ", cellKeys[0], temp0)); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } #endregion } #endregion // 合并合計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 0, 2); // 合并合計 sheet.AddMergedRegion(region0); } rowIndex++; #endregion } #endregion #region 進行匯總 - 加總計 if (addAllTotal) // 加總計 { if (!isConver) sheet.ShiftRows(rowIndex, sheet.LastRowNum, 1, true, false); // 不覆蓋,數據向下移 IRow rowTotal0 = sheet.CreateRow(rowIndex); //創建列并插入數據 #region 插入總計數據 for (int index = 0; index < cellCount; index++) { object obj1; ICell newcell = rowTotal0.CreateCell(index); #region 列值處理 if (index == 0) //第1列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue("總計"); continue; } if (index == 1) // 第2列 { newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); continue; } // 其它列數據,數值進行匯總 switch (source.Columns[cellKeys[index]].DataType.ToString()) { case "System.Int16": //整型 case "System.Int32": case "System.Int64": case "System.Byte": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), ""); int intV = 0; int.TryParse(obj1.ToString(), out intV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(intV); break; case "System.Decimal": //浮點型 case "System.Double": case "System.Single": obj1 = source.Compute(string.Format("sum({0})", cellKeys[index]), ""); double doubV = 0; double.TryParse(obj1.ToString(), out doubV); newcell.CellStyle = styleTotalNum; newcell.SetCellValue(doubV); break; default: newcell.CellStyle = styleTotalStr; newcell.SetCellValue(""); break; } #endregion } #endregion // 合并總計 CellRangeAddress region0 = new CellRangeAddress(rowIndex, rowIndex, 0, 2); // 合并總計 sheet.AddMergedRegion(region0); } #endregion } return Save2Xls(strFileName, workbook); // 保存為xls文件 } catch (Exception ex) { // FileHelper.WriteLine(logfile, "處理數據異常:" + ex.Message); // msg = ex.Message; } return bn; }
保存文件的代碼:
public static bool Save2Xls(string fileName, IWorkbook workbook) { bool bn = false; try { FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate); MemoryStream ms = new MemoryStream(); workbook.Write(ms); BinaryWriter w = new BinaryWriter(fs); w.Write(ms.ToArray()); fs.Close(); ms.Close(); bn = true; } catch(Exception ex) { //FileHelper.WriteLine(logfile, "保存文件異常:" + ex.Message); } return bn; }
上述內容就是怎么在NPOI中實現兩級分組合并功能,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。