Excel工作表错误
本文关键字:错误 工作 Excel | 更新日期: 2023-09-27 18:02:23
我正在编写一个程序,将数据写入现有的Excel文件。计划将新数据附加到旧数据,但现在我被困在试图访问一个特定的工作表。我在网上做了很多搜索,但别人做的事情对我的根本不起作用。我还是会出错。希望有人能帮我弄清楚我做错了什么。我有一个函数写到Excel。我一直被困在线创建工作表对象。这一行总是出错。我试过不同的方法,比如:
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代码的函数: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
。解决方案资源管理器窗口:参考资料->添加引用->. net选项卡,添加Microsoft.CSharp
不知道你得到什么错误,但我已经做了以下工作,通过COM互操作访问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();
我认为问题是你使用工作表而不是工作表。如果不知道具体的错误,就很难确定。