我正在编写一个程序来将数据写入现有的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);
}
答案 0 :(得分:5)
添加参考Microsoft.CSharp。 Solution explorer窗口:引用,添加引用,.NET选项卡,添加Microsoft.CSharp。
答案 1 :(得分:0)
不确定您收到了什么错误,但我已通过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();
我认为问题在于您使用Sheets而不是Worksheets。在不知道具体错误的情况下,很难确定。