0

我正在尝试逐行遍历和 excel 文件。首先检查行的第一列是否在列表中有名称如果是,则将该行的第七列更新为 0。

下面的代码不会崩溃,并且似乎正在做我要求它做的事情。

有2个问题...

  1. 代码运行后,不会将任何更改保存到 Excel 文件中。我已经尝试了几种 .Save() 的方法,但没有任何效果。可能是因为我使用的是免费版的 VS 吗?
  2. 我在 PersonsToExcludeMAIN 中有大约 150 个名称和大约 250 行要比较,代码大约需要 8 分钟才能运行。为什么?

    DB_PATH = @"C:\Users\n\Downloads\Nick1.xlsx";
    File.SetAttributes(DB_PATH, FileAttributes.Normal);
    MyApp = new Excel.Application();
    MyApp.Visible = false;
    MyBook = MyApp.Workbooks.Open(DB_PATH);
    MySheet = (Excel.Worksheet)MyBook.Sheets[1]; // Explicit cast is not required here
    lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
    
    //Get the used Range
    Excel.Range usedRange = MySheet.UsedRange;
    
    //Iterate the rows in the used range
    foreach (Excel.Range row in usedRange.Rows)
    {
           //PersonsToExcludeMAIN has the Names Of all the People (in the "Name" property) in the DB_PATH (the excel file I am trying to edit) I want to set their Column "7" to "0"
           List<Person> tempList = PersonsToExcludeMAIN.Where(item => item.Name == (row.Columns[1].Value2.ToString())).ToList();
    
            if (tempList.Count > 0)
            {
             //This gets reached and seems to be executing properly
             row.Columns[7].Value2 = "0";
            }
    
    }
    
    //This Save() doesn't do anything
    MyBook.Save();
    MyBook.Close(true);
    MyApp.Quit();
    
4

1 回答 1

-1
  1. 查看文档(here)的Workbook.Save()方法,它有一句话说

第一次保存工作簿时,使用 SaveAs 方法指定文件的名称。

也许是这样?

  1. 我在您的代码中看到您正在foreach循环内创建名称列表。我相信这就是为什么它需要太长时间。如果您在循环之外创建它,它可能会更快。
于 2018-12-29T20:06:22.717 回答