我在使用 set_value 方法时发现了一个问题。我写了最简单的代码来排除我的错误。
当我读取一些单元格然后使用 set_value 将它们写回工作表时:
任何过滤器在 xlsx 文件中都处于活动状态,
获取/设置 2 列或更多列,
一些单元格已损坏(它们是空的或包含像#N/D 一样的垃圾!)。当我在使用 set_value 之前在工作表或程序中禁用过滤时,一切正常。我在谷歌中找不到关于这个特定问题的任何信息,我做的事情真的很愚蠢吗?
Excel.Workbooks workbooks;
Excel.Workbook workbook = null;
Excel.Worksheet sheet = null;
Excel.Application excelApplication;
excelApplication = new Excel.Application();
excelApplication.Visible = false;
workbooks = excelApplication.Workbooks;
workbook = workbooks.OpenXML(file);
sheet = workbook.Sheets[1];
Excel.Range excelRangeR = sheet.UsedRange;
object[,] valueArrayR = (object[,])excelRangeR.get_Value(Excel.XlRangeValueDataType.xlRangeValueDefault);
//if uncomment line below (or manualy disable filters in XLSX file), set_value works fine
//sheet.AutoFilterMode = false;
excelRangeR.set_Value(Excel.XlRangeValueDataType.xlRangeValueDefault, valueArrayR);
workbook.Save();
workbook.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelRangeR);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbooks);
excelApplication.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);