Excel工作表错误

我正在编写一个程序来将数据写入现有的Excel文件。 计划追加新的数据到旧的,但现在我被困在试图访问特定的工作表。 我在网上做了很多search,但没有人做我的工作。 我仍然有错误。 希望有人能帮我弄清楚我做错了什么。 我有一个函数来写入Excel。 我一直卡在行来创build工作表对象。 总是得到这条线上的错误。 我尝试过不同的方式

Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorksheets.get_Item(1); 

要么

 Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorksheets.Worksheet[0]; 

要么

 Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorksheets.get_Item(1); 

要么

 Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorksheets.get_Item(currentSheet); 

我尝试了许多不同的方式,我发现在网上,但他们似乎没有为我工作。

这是我的Excel代码的function:

 using Microsoft.Office; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; public void write_to_file(string lux_excel, string serialnumber_excel) { Excel.Application excelapp = new Excel.Application(); excelapp.Visible = true; //make the object visible Excel.Workbooks excelWorkbooks; Excel.Workbook excelWorkbook; excelWorkbooks = excelapp.Workbooks; object misValue = System.Reflection.Missing.Value; string fileName = @"C:\Designs\C_sharp_learn\chapter2\test_data.xlsx"; excelWorkbook = excelWorkbooks.Open(fileName, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue, misValue); string currentSheet = "Sheet1"; Excel.Sheets excelWorksheets = (Excel.Sheets)excelWorkbook.Sheets; Excel.Worksheet excelWorksheet = (Excel.Worksheet)excelWorksheets.get_Item(1); } 

添加参考Microsoft.CSharp。 解决scheme资源pipe理器窗口:引用,添加引用,.NET选项卡,添加Microsoft.CSharp。

不知道你得到了什么错误,但我已经完成了以下操作来通过COM Interop访问Excel工作簿中的工作表:

 _xApp = new Excel.Application(); _xApp.DisplayAlerts = false; // don't display alerts _xApp.AskToUpdateLinks = false; // don't present the option to ask for link updating _xApp.ScreenUpdating = false; // turn off the redrawing the of the screen while we're working // open the book _xBook = _xApp.Workbooks.Open(Filename: _file.FullName, UpdateLinks: false, ReadOnly: true, CorruptLoad: true, Editable: false, Local: true); _xBook.CheckCompatibility = false; _xBook.UpdateLinks = Microsoft.Office.Interop.Excel.XlUpdateLinks.xlUpdateLinksNever; _xBook.Activate(); _sheets = _xBook.Worksheets; // get the sheet we want if (!string.IsNullOrEmpty(this.WorksheetName)) { for (int i = 1; i < _sheets.Count + 1; i++) { _xSheet = _sheets[i] as Excel.Worksheet; if (base.CheckFilter(this.WorksheetName, _xSheet.Name)) break; if (_xSheet.Name.IndexOf(this.WorksheetName, StringComparison.InvariantCultureIgnoreCase) > -1) break; } } else { _xSheet = _sheets[1] as Excel.Worksheet; } if (_xSheet == null) throw new ArgumentException("Worksheet not found in Excel Spreadsheet provided!", "this.WorksheetName"); _xSheet.Activate(); 

我认为问题在于使用表格而不是工作表。 不知道你的具体错误,很难确定。