NPOI操作Excel之三解析Excel

开发 前端
通过前面两篇的基础学习,我们对NPOI有了一定了了解,下面就开始进入实战,解析下面格式的Excel(下面只是列举了几个例子),并保存入库。

[[380425]]

通过前面两篇的基础学习,我们对NPOI有了一定了了解,下面就开始进入实战,解析下面格式的Excel(下面只是列举了几个例子),并保存入库

首先我们先分析一下,要解析这样的Excel,需要把指标【橘色背景和蓝色背景】(作为指标入库)、科目【棕色背景和黄色背景】(作为X轴入库)、数据【乳白色背景和白色背景】(作为Y轴入库)的数据分开入库。

第一张图我们得到的指标毫无疑问应该是第三行从第二列开始到最后一列的数据,而第二张图我们得到的指标应该是非金融企业部门-使用、非金融企业部门-来源、金融机构部门-使用、金融机构部门-来源,以此类推,我们要想取到这样的数据,首先需要把合并行的单元格填充、然后把合并列的数据合并,我们可以通过二维数组来实实现。

由于每个Excel的格式不一样,指标数据的行数,列数也不一样,所以我们要想把数据区分开只能通过背景颜色,把三部分是数据分开并放到三个二维数组里,然后解析入库,由于Excel的背景颜色存在不一样,所以不能写死,通过观察我们可以发现,每个Excel都是从指标行开始有背景颜色到数据行开始变背景颜色,这样我们就可以区分开来,到这里相信聪明的你已经知道怎么做了,下面我们就开始实现吧

1、获取Excel的扩展名并创建工作簿,如果是xls创建HSSFWorkbook工作簿,如果是xlxs创建XSSFWorkbook工作簿

  1. public static void ReadFromExcelFile(string filePath) 
  2.     IWorkbook wk = null
  3.     string extension = System.IO.Path.GetExtension(filePath);//GetExtension获取Excel的扩展名 
  4.     try 
  5.     { 
  6.        FileStream fs = File.OpenRead(filePath); 
  7.        if (extension.Equals(".xls")) 
  8.        {                    
  9.            wk = new HSSFWorkbook(fs); //把xls文件中的数据写入wk中 
  10.        } 
  11.        else 
  12.        {                     
  13.            wk = new XSSFWorkbook(fs);//把xlsx文件中的数据写入wk中 
  14.        } 
  15.        fs.Close();                 
  16.        sheet = wk.GetSheetAt(0);//读取当前表数据   20            GetIndexRow();//获取【指标、科目、数据】的行数列数 
  17.        ReadData();//读数据并保存到数组中 
  18.        SaveData();//解析数组数据并保存入库 
  19.     } 
  20.     catch (Exception e) 
  21.     {                
  22.        Console.WriteLine(e.Message); //只在Debug模式下才输出 
  23.     } 

2、获取指标从哪行开始

 

  1. for (int i = 0; i < sheet.LastRowNum; i++)//sheet.LastRowNum当前表的行数 
  2.    IRow row = sheet.GetRow(i);  //读取当前行数据 
  3.    if (row != null
  4.    { 
  5.       if (row.GetCell(0) != null)  //读取该行的第1列数据 
  6.       { 
  7.         ICellStyle style = row.GetCell(0).CellStyle;//当前行第一列的样式 
  8.         row.GetCell(0).SetCellType(CellType.String);//把第一行第一列的值类型转换成string类型 
  9.         short GroundColor = style.FillForegroundColor;//获取当前行第一列的背景色 
  10.         if (i == 0)//若或i=0说明是第一行,没有背景色的 
  11.         { 
  12.            Title = row.GetCell(0).StringCellValue;//获取第一行第一列的值即标题的值 
  13.            TitleColor = GroundColor;//第一行第一列背景色的值付给TitleColor 
  14.            continue
  15.         } 
  16.         else//如果不是第一行 
  17.         { 
  18.            if (GroundColor == TitleColor) 
  19.            { 
  20.               if (row.GetCell(0).StringCellValue.Contains("单位")) 
  21.               { 
  22.                  IndexUnit = row.GetCell(0).StringCellValue.Replace("单位:""").Replace("单位:"""); 
  23.                  continue
  24.                } 
  25.            } 
  26.            else if (GroundColor != TitleColor && IndexColor == 0)//如果GroundColor不等于TitleColor说明改行是指标行 
  27.            { 
  28.                IndexColor = GroundColor;// 把GroundColor的值赋值给IndexColor 
  29.                IndexStart = i;//记录改行,改行是指标行的起始行 
  30.                break; 
  31.            } 
  32.        } 
  33.    } 
  34.  } 
  35.      

3、获取指标从哪行结束

  1. for (int i = IndexStart + 1; i < sheet.LastRowNum; i++) 
  2.  { 
  3.      IRow row = sheet.GetRow(i);  //读取当前行数据 
  4.       if (row != null
  5.       { 
  6.            if (row.GetCell(0) != null)  //读取该行的第1列数据 
  7.            { 
  8.                 ICellStyle style = row.GetCell(0).CellStyle; 
  9.                 short GroundColor = style.FillForegroundColor; 
  10.                 if (IndexColor != GroundColor) 
  11.                 { 
  12.                       LeftDataColor = GroundColor; 
  13.                       IndexEnd = i - 1; 
  14.                       break; 
  15.                 } 
  16.             } 
  17.        } 
  18.  } 

4、获取数据从哪行开始到哪行结束

  1. for (int i = IndexEnd + 1; i < sheet.LastRowNum; i++) 
  2.  { 
  3.       DataRowStart = IndexEnd + 1;//数据开始行 
  4.       IRow row = sheet.GetRow(i);  //读取当前行数据 
  5.       if (row != null
  6.       { 
  7.            if (row.GetCell(0) != null)  //读取该行的第1列数据 
  8.            { 
  9.                  ICellStyle style = row.GetCell(0).CellStyle; 
  10.                  short GroundColor = style.FillForegroundColor; 
  11.                  if (LeftDataColor != GroundColor) 
  12.                  { 
  13.                        DataRowEnd = i - 1;//数据结束行 
  14.                        break; 
  15.                   } 
  16.             } 
  17.       } 
  18.  } 

5、获取科目【左侧】的列数

  1. if (sheet.GetRow(IndexEnd + 1) != null
  2.        for (int i = 0; i < sheet.GetRow(IndexEnd + 1).LastCellNum; i++) 
  3.         { 
  4.               if (sheet.GetRow(IndexEnd + 1).GetCell(i) != null
  5.                { 
  6.                      ICellStyle style = sheet.GetRow(IndexEnd + 1).GetCell(i).CellStyle; 
  7.                       short GroundColor = style.FillForegroundColor; 
  8.                       sheet.GetRow(IndexEnd + 1).GetCell(i).SetCellType(CellType.String); 
  9.                        if (GroundColor != LeftDataColor) 
  10.                         { 
  11.                             DataLeftCell = i;//科目的列数 
  12.                             break; 
  13.                         } 
  14.                  }  
  15.            } 

6、把数据保存到数组中【指标数组】

  1. string[,] IndexArray = new string[IndexEnd-IndexStart+1, sheet.GetRow(0).LastCellNum - DataLeftCell];//指标 
  2.  
  3.  4  //循环指标行 
  4. for (int r = IndexStart; r <= IndexEnd; r++) 
  5.    IRow row = sheet.GetRow(r);  //读取当前行数据 
  6.    if (row != null
  7.    { 
  8.       for (int c = DataLeftCell; c <= row.LastCellNum - DataLeftCell; c++) 
  9.       { 
  10.           if (row.GetCell(c) != null
  11.           { 
  12.               row.GetCell(c).SetCellType(CellType.String); 
  13.               #region 判断是否是合并单元格 
  14.               if (string.IsNullOrEmpty(row.GetCell(c).StringCellValue)) 
  15.               { 
  16.                    ICell cell = row.GetCell(c); 
  17.                    Dimension dimension = new Dimension(); 
  18.                    if (IsMergedRegions.IsMergeCell(cell, out dimension))//如果是空判断是否是合并单元格 
  19.                    { 
  20.                         IndexArray[r - IndexStart, c- DataLeftCell] = dimension.DataCell.StringCellValue;//如果是取合并单元格的值 
  21.                    } 
  22.                    else 
  23.                    { 
  24.                         IndexArray[r - IndexStart, c- DataLeftCell] = row.GetCell(c).StringCellValue;//否则取改单元格本身的值 
  25.                    } 
  26.               } 
  27.               else 
  28.               { 
  29.                    IndexArray[r - IndexStart, c- DataLeftCell] = row.GetCell(c).StringCellValue; 
  30.               } 
  31.               #endregion 
  32.           } 
  33.       } 
  34.    } 

7、把数据保存到数组中【科目数组】

  1. string[,]  LeftDataArray = new string[DataRowEnd-DataRowStart+1, DataLeftCell];//科目 
  2.   for (int r = DataRowStart; r <= DataRowEnd; r++) 
  3.              { 
  4.                  IRow row = sheet.GetRow(r);  //读取当前行数据 
  5.                  if (row != null
  6.                  { 
  7.                      for (int c = 0; c < DataLeftCell; c++) 
  8.                      { 
  9.                          if (row.GetCell(c) != null
  10.                          { 
  11.                              row.GetCell(c).SetCellType(CellType.String); 
  12.   
  13.                              #region 判断是否是合并单元格 
  14.                              if (string.IsNullOrEmpty(row.GetCell(c).StringCellValue)) 
  15.                              { 
  16.                                  ICell cell = row.GetCell(c); 
  17.                                  Dimension dimension = new Dimension(); 
  18.                                  if (IsMergedRegions.IsMergeCell(cell, out dimension)) 
  19.                                  { 
  20.                                      LeftDataArray[r - DataRowStart, c] = dimension.DataCell.StringCellValue; 
  21.                                  } 
  22.                                  else 
  23.                                  { 
  24.                                      LeftDataArray[r - DataRowStart, c] = row.GetCell(c).StringCellValue; 
  25.                                  } 
  26.                              } 
  27.                              else 
  28.                              { 
  29.                                  LeftDataArray[r - DataRowStart, c] = row.GetCell(c).StringCellValue; 
  30.                              } 
  31.                              #endregion 
  32.                          } 
  33.                      } 
  34.                  } 
  35.              } 

8、把数据保存到数组中【数据数组】

  1. string[,]  RightDataArray= new string[DataRowEnd - DataRowStart + 1, sheet.GetRow(0).LastCellNum - DataLeftCell];//数据 
  2.   for (int r = DataRowStart; r <= DataRowEnd; r++) 
  3.              { 
  4.                  IRow row = sheet.GetRow(r);  //读取当前行数据 
  5.                  if (row != null
  6.                  { 
  7.                      for (int c = DataLeftCell; c < row.LastCellNum; c++) 
  8.                      { 
  9.                          if (row.GetCell(c) != null
  10.                          { 
  11.                              row.GetCell(c).SetCellType(CellType.String); 
  12.                              RightDataArray[r - DataRowStart, c- DataLeftCell] = row.GetCell(c).StringCellValue; 
  13.                          } 
  14.                      } 
  15.                  } 
  16.              } 

9、解析数组保存数据

  1. private static void SaveData() 
  2.       //IndexModel im = new IndexModel(); 
  3.       DataModel dm = new DataModel(); 
  4.       for (int ic = 0; ic < sheet.GetRow(0).LastCellNum - DataLeftCell ; ic++)//循环指标列 
  5.       { 
  6.          dm.IndexName = null
  7.          dm.IndexCode = IndexCode++.ToString().PadLeft(4, '0'); 
  8.          #region 获取指标名称 
  9.          for (int ir = 0; ir < IndexEnd - IndexStart + 1; ir++) 
  10.          { 
  11.              if (IndexArray[ir, ic] != null
  12.              { 
  13.                   if (dm.IndexName == null
  14.                   { 
  15.                       dm.IndexName = IndexArray[ir, ic];                         
  16.                   } 
  17.                   else 
  18.                   { 
  19.                       if (!dm.IndexName.Contains(IndexArray[ir, ic])) 
  20.                       { 
  21.                          dm.IndexName = dm.IndexName + "_" + IndexArray[ir, ic];//同一列字符串拼接 
  22.                       } 
  23.                   } 
  24.                } 
  25.           } 
  26.          #endregion 
  27.          //循环得右侧数据 
  28.          for (int rr = 0; rr < DataRowEnd - DataRowStart + 1; rr++)//循环右侧数据的行 
  29.          { 
  30.                #region 右侧数据 
  31.                if (RightDataArray[rr, ic] != null
  32.                { 
  33.                    dm.IndexYValue = RightDataArray[rr, ic]; 
  34.                } 
  35.                #endregion 
  36.                dm.IndexXValue = null
  37.                //循环得左侧数据 
  38.                for (int lc = 0; lc < DataLeftCell; lc++) 
  39.                { 
  40.                    if (LeftDataArray[rr, lc] !=null
  41.                    { 
  42.                         if (dm.IndexXValue == null
  43.                         { 
  44.                              dm.IndexXValue = LeftDataArray[rr, lc]; 
  45.                         } 
  46.                         else 
  47.                         { 
  48.                              if (!dm.IndexXValue.Contains(LeftDataArray[rr, lc])) 
  49.                              { 
  50.                                  dm.IndexXValue = dm.IndexXValue + "_" + LeftDataArray[rr, lc]; 
  51.                              } 
  52.                          }                               
  53.                      } 
  54.                  } 
  55.            Console.WriteLine($"指标名称:{dm.IndexName} 指标编码:{dm.IndexCode} IndexXValue:{dm.IndexXValue} IndexYValue:{dm.IndexYValue}"); 
  56.          } 
  57.      } 

10、上面用到的方法IsMergeCell判断是否是合并单元格

  1. /// <summary> 
  2. /// 判断指定单元格是否为合并单元格,并且输出该单元格的维度 
  3. /// </summary> 
  4. /// <param name="cell">单元格</param> 
  5. /// <param name="dimension">单元格维度</param> 
  6. /// <returns>返回是否为合并单元格的布尔(Boolean)值</returns
  7. public static bool IsMergeCell(this ICell cell, out Dimension dimension) 
  8.     return cell.Sheet.IsMergeCell(cell.RowIndex, cell.ColumnIndex, out dimension); 

https://www.cnblogs.com/zqyw/category/1070314.html

本文转载自微信公众号「CSharp编程大全」,可以通过以下二维码关注。转载本文请联系CSharp编程大全公众号。

 

责任编辑:武晓燕 来源: CSharp编程大全
相关推荐

2021-02-02 07:47:36

NPOI基础Excel

2021-02-03 10:31:10

NPOIExcel样式

2012-08-03 10:20:06

ASP.NET

2021-12-01 07:19:44

C# Npoi Excel

2009-08-18 16:14:05

C# 操作Excel

2009-08-18 16:20:09

C# 操作Excel

2009-09-01 13:59:01

C#操作Excel

2009-08-18 15:49:19

C# 操作Excel

2009-09-01 14:08:58

C#操作Excel

2023-11-02 08:01:50

NPOI开源

2009-08-25 16:49:28

.NET Excel

2011-07-13 14:02:42

OracleExcel

2011-06-23 11:16:39

Qt Excel

2023-04-09 15:26:02

PythonPandasopenpyxl

2009-08-18 13:49:21

C# 操作Excel

2011-06-27 10:35:21

Excel

2009-08-18 16:04:12

C# 操作Excel

2009-11-02 10:42:04

VB.NET EXCE

2020-08-10 15:35:14

Excel函数数据

2009-08-18 14:25:05

C# 操作Excel
点赞
收藏

51CTO技术栈公众号