服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - NPOI实现两级分组合并功能(示例讲解)

NPOI实现两级分组合并功能(示例讲解)

2022-02-15 16:44Tiger.liang C#

下面小编就为大家分享一篇NPOI实现两级分组合并功能的示例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

NPOI版本:2.2.1.0

最近公司有这样的需求:

统计每个部门下面,多个费用使用情况。部门存在多级,但统计时,只需统计到2级,2级以下的,归到第2级的部门下。并且要求,第2级部门有个小计,第1级部门需要有个合计。最后,还需提供总计。

本来对NPOI研究的还不够深入的,以前都是直接通过别人提供的代码来实现对DataTable中的数据进行全部导出,但里面不带合并,及合计功能,不满足当前需求。不得已,只有好好地研究一下了。还好,最终实现了要求。

在此,也感谢其他提供相关资料的人员,让我实现了此功能。

简要说明一下使用:

1、Export2Template2方法直接使用。DataTable原始数据,必须是已经按要求排好序的数据。全部是逐行向下处理。

2、要导出的列名,取自cellKeys中。列名必须为source中存在的。

3、相同值合并的第1列,为cellKeys[0],合并的第2列,为cellKeys[1],如需要其它列的合并,可以此基础上,按自己的需求进行调整。(合并时,只会比较上下行的数据内容)

4、要导出的数据中,数值类型,自动居右。其它类型,自动居中。

5、小计,合计,总计的字体,全部加黑

6、小计,合计,总计,自动对数值类型进行汇总。其它类型数据全部置空。

7、合并的列数:mergeColumns。如果>2,自动只处理前2列。如果<1,则不做合并处理。

直接上可用的代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
/// <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;
}

保存文件的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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实现两级分组合并功能(示例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:http://www.cnblogs.com/zyxlsh/archive/2017/12/07/8000166.html

延伸 · 阅读

精彩推荐
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21