在列中统计相同的值并写入新的Excel文件

我想用c#读取一个excel文件,并计算一列中所有相同的值,然后写入值+多久我在另一个excel文件中find值。 所以如果我有这样的事情:

ABC *something* 110 *something* *something* 120 *something* *something* 120 *something* *something* 130 *something* *something* 110 *something* *something* 120 *something* *something* 110 *something* 

而我的专栏是“B”,我想数。 我想进入一个新的excel输出如下所示:

  AB 110 3 120 3 130 1 

什么是最简单的方法?

虽然这是一个先进的,我会build议创build一个数据透视表来做你在问什么。 这是一个完美的适合,不需要太多的编码。

试试这个代码(不要忘记更改“相同”的实际列名称和工作簿位置以及):

 using System; using System.Collections.Generic; using System.Text; using Excel = Microsoft.Office.Interop.Excel; namespace ExcelFun01 { class Program { static void Main(string[] args) { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlWb = xlApp.Workbooks.Open(@"C:\stackoverflow.xlsx"); Excel.Worksheet xlWs = (Excel.Worksheet)xlWb.Sheets[1]; // Sheet1 Excel.Worksheet xlWsNew = (Excel.Worksheet)xlWb.Sheets.Add(); // find the data range Excel.Range dataRange = getDataRange(ref xlWs); // start by creating the PivotCache - this tells Excel that there is a data connection // to data inside the workbook (could be used to get external data, too) Excel.PivotCache pc = xlWb.PivotCaches().Create(Excel.XlPivotTableSourceType.xlDatabase ,dataRange ,Excel.XlPivotTableVersionList.xlPivotTableVersion14); // create the pivot table and set the destination to the new sheet at A1 Excel.PivotTable pt = pc.CreatePivotTable(xlWsNew.Range["A1"]); // get the PivotField "Same" for easy referencing Excel.PivotField pf = (Excel.PivotField)pt.PivotFields("Same"); // first add the count pt.AddDataField(pf, "Count of Same", Excel.XlConsolidationFunction.xlCount); // now add the row with the same field pf.Orientation = Excel.XlPivotFieldOrientation.xlRowField; pf.Position = 1; // behold!!! xlWsNew.Select(); xlApp.Visible = true; } private static Excel.Range getDataRange(ref Excel.Worksheet xlWs) { Excel.Range rng = xlWs.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell); Excel.Range dataRange = xlWs.Range["A1", rng.Address]; return dataRange; } } } 

以下是数据透视表的样子:

在这里输入图像说明

在这里阅读Excel文件检查这个类似的post: 从C#读取Excel文件 。 至于写作,您可以写入CSV文件,并在Excel中打开它。