前言
从excel表格统计数据,可能会出现同一字段名的数据需要累加的情况,本文使用List集合存储数据;使用C#的NPOI类进行实现如下
一、首先需要excel文件的导入导出,链接如下:
二、实现数据统计
1.定义存放数据的List集合与存放待统计数据所在Cell索引的int类型变量
代码如下:
List<string> list1 = new List<string>(); //存放索引字段名
List<double> list2 = new List<double>(); //存放与list1中索引字段名对应的数据
int define_index = -1; //存放索引所在Cell的列数
int ob_value_index = -1; //存放数据所在Cell的列数
2.遍历代统计列索引
行总数rowCount可以通过LastRowNum最后一行行数的方法获得;列总数cellCount可以通过LastCellNum最后一列列数的方法获得。
注:由于编程中数组正常从0开始,RowNum也同样是从0开始,LastRowNum会比实际小1。
这里很迷的是:FirstRowNum、LastRowNum和FirstCellNum都遵循从0开始,即比实际小1;LastCellNum会自动加1,与实际列数相匹配。
代码如下:
IRow firstrow = sheet.GetRow(0);
int cellCount = firstrow.LastCellNum;
for (int i = 0; i <= cellCount - 1; i++)
{
if ("索引列名".Equals(firstrow.Cells[i].StringCellValue))
{
define_index = i; //将待统计数据的索引所在列记录下来
}
if ("数据列名".Equals(firstrow.Cells[i].StringCellValue))
{
ob_value_index = i; //将待统计数据的数据所在列记录下来
}
}
3.遍历数据,进行汇总统计
遍历所有的数据,若List1中已存在该索引名,则在List2中对应位置的数据值进行累加;若不存在,则将索引名和数据新插入List集合
代码如下:
for (int i = 0; i <= rowCount - 1; i++)
{
row = sheet.GetRow(i + 1);
if (!"".Equals(row.Cells[define_index].StringCellValue)) //excel表格式的特殊性,有数据重复,重复数据行的索引名为空;根据此特点进行筛选
{
if (list1.Contains(row.Cells[define_index].StringCellValue)) //如果list1中包含此索引名称
{
for (int j = 0; j < list1.Count; j++)
{
if (list1[j].Equals(row.Cells[define_index].StringCellValue)) //遍历获取到索引名称所在位置
{
list2[j] += row.Cells[ob_value_index].NumericCellValue; //在相应位置对list2数据进行累加操作
}
}
}
else //list1中不存在该索引名称时,进行新插入数据
{
list1.Add(row.Cells[define_index].StringCellValue);
list2.Add(row.Cells[ob_value_index].NumericCellValue);
}
}
}