gpt4 book ai didi

C#:如何访问 Excel 单元格?

转载 作者:IT王子 更新时间:2023-10-29 04:38:36 26 4
gpt4 key购买 nike

我正在尝试打开一个 Excel 文件并用数据填充它的单元格?到目前为止,我已经完成了以下编码。

目前我正处于使用以下代码的阶段,但我仍然遇到错误:

Microsoft.Office.Interop.Excel.ApplicationClass appExcel =
new Microsoft.Office.Interop.Excel.ApplicationClass();
try
{
// is there already such a file ?
if (System.IO.File.Exists("C:\\csharp\\errorreport1.xls"))
{
// then go and load this into excel
Microsoft.Office.Interop.Excel.Workbooks.Open(
"C:\\csharp\\errorreport1.xls", true, false,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
}
else
{
// if not go and create a workbook:
newWorkbook = appExcel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
Microsoft.Office.Interop.Excel._Worksheet excelWorksheet =
(Microsoft.Office.Interop.Excel._Worksheet)
newWorkBook.Worksheets.get_Item(1);
}
i++;
j = 1;

j++;
objsheet.Cells(i, j).Value = "Tabelle: " + rs.Fields["Table_Name"];
j++;
objsheet.Cells(i, j).Value = "kombinationsschluessel:FALL "
+ rs3.Fields[1].Value;
j++;
objsheet.Cells(i, j).Value = "Null Value: ";
j++;
objsheet.Cells(i, j).Value = "Updated with 888";

这些是我遇到的前 2 个错误:

Error 1 An object reference is required for the nonstatic field, method, or
property 'Microsoft.Office.Interop.Excel.Workbooks.Open(string, object,
object, object, object, object, object, object, object, object, object,
object, object, object, object)'

Error 2 The name 'newWorkbook' does not exist in the current context

最佳答案

如果您正在尝试自动化 Excel,您可能不应该打开 Word 文档并使用 Word 自动化 ;)

看看这个,它应该让你开始,

http://www.codeproject.com/KB/office/package.aspx

这是一些代码。它取 self 的一些代码并删除了很多东西,所以它什么都不做,可能无法编译或正常工作,但它应该能让你继续。它以阅读为导向,但应该为您指明正确的方向。

Microsoft.Office.Interop.Excel.Worksheet sheet = newWorkbook.ActiveSheet;

if ( sheet != null )
{
Microsoft.Office.Interop.Excel.Range range = sheet.UsedRange;
if ( range != null )
{
int nRows = usedRange.Rows.Count;
int nCols = usedRange.Columns.Count;
foreach ( Microsoft.Office.Interop.Excel.Range row in usedRange.Rows )
{
string value = row.Cells[0].FormattedValue as string;
}
}
}

你也可以这样做

Microsoft.Office.Interop.Excel.Sheets sheets = newWorkbook.ExcelSheets;

if ( sheets != null )
{
foreach ( Microsoft.Office.Interop.Excel.Worksheet sheet in sheets )
{
// Do Stuff
}
}

如果需要插入行/列

// Inserts a new row at the beginning of the sheet
Microsoft.Office.Interop.Excel.Range a1 = sheet.get_Range( "A1", Type.Missing );
a1.EntireRow.Insert( Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, Type.Missing );

关于C#:如何访问 Excel 单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/472959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com