我正在尝试逐行遍历和 excel 文件。首先检查行的第一列是否在列表中有名称如果是,则将该行的第七列更新为 0。
下面的代码不会崩溃,并且似乎正在做我要求它做的事情。
有2个问题...
- 代码运行后,不会将任何更改保存到 Excel 文件中。我已经尝试了几种 .Save() 的方法,但没有任何效果。可能是因为我使用的是免费版的 VS 吗?
我在 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();