1

我想用c#读取一个excel文件并计算一列中所有相同的值,然后写下这个值+我在另一个excel文件中找到该值的频率。所以如果我有这样的东西:

      A            B          C
  *something*      110    *something*   
  *something*      120    *something*  
  *something*      120    *something*  
  *something*      130    *something*  
  *something*      110    *something*
  *something*      120    *something*  
  *something*      110    *something*

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

 A             B
 110           3
 120           3
 130           1

最简单的方法是什么?

4

1 回答 1

0

虽然它有点先进,但我建议创建一个数据透视表来完成您的要求。它非常适合这个,不需要太多编码。

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

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;
        }
    }
}

这是数据透视表的样子:

在此处输入图像描述

于 2012-08-28T00:55:38.057 回答