0

我有一个包含多个工作表的 excel 文件 myexcel.xlsx。所有工作表在第一行中具有相同的列名。一列称为 ID,另一列称为 Total。我正在浏览每个工作表中的每一行,然后我想知道如果列 ID 存在于同一工作表或其他工作表的任何其他行中,我该如何检查它。如果在其他地方找不到 ID,则总数将仅等于该行的 Total 列,但如果相同/其他工作表的另一行中存在相同的 ID,那么我想添加另一行的 Total 列然后在 for 循环中忽略所有这些具有相同 ID 的行,以便它们不会重复。

            Excel.Application myapp = new Excel.Application();
            Excel.Workbook myworkbook = myapp(@"myexcel.xlsx");
            for (int i = 1; i <= myworkbook.Worksheets.Count; i++)
            {
                Excel._Worksheet myworksheet = myworkbook.Worksheets[i];
                Excel.Range myrange = myworksheet.UsedRange;
                int myrowCount = myrange.Rows.Count;
            }
4

1 回答 1

0

I don't know the correct syntax for working with Excel sheets, so I'll give you a basic example for what I think you are asking. You'll have to adjust the code so it works, but if you want to aggregate (get the sum) of the "Total" in all the rows with the same "ID" you should be able to do something like this:

var totalsDictionary = new Dictionary<int, int>();

for (var ws = 0; ws < worksheets.Count; ws++)
{
    var worksheet = worksheets[ws];
    for (var row = 0; row < worksheet.Rows.Count; row++)
    {
        var id = worksheet.Rows[row]["ID"];
        var total = worksheet.Rows[row]["Total"];
        if (totalsDictionary.ContainsKey(id))
        {
            totalsDictionary[id] += total;
        }
        else
        {
            totalsDictionary.Add(id, total);
        }
    }
}

// totalsDictionary now contains the sum of Totals for each ID
于 2020-10-23T16:41:05.343 回答