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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/472959/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 04:48:23  来源:igfitidea点击:

C#: How to access an Excel cell?

c#excel

提问by tksy

I am trying to open an Excel file and populate its cells with data? I have done the following coding so far.

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

Currently I am at this stage with the following code but still I am getting errors:

目前我处于这个阶段,使用以下代码,但仍然出现错误:

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";

These are the top 2 errors I am getting:

这些是我遇到的前 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

回答by Rob Prouse

If you are trying to automate Excel, you probably shouldn't be opening a Word document and using the Word automation ;)

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

Check this out, it should get you started,

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

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

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

And here is some code. It is taken from some of my code and has a lot of stuff deleted, so it doesn't do anything and may not compile or work exactly, but it should get you going. It is oriented toward reading, but should point you in the right direction.

这是一些代码。它取自我的一些代码并删除了很多内容,因此它不会做任何事情并且可能无法编译或完全工作,但它应该可以帮助您前进。它面向阅读,但应该为您指明正确的方向。

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;
        }
    }
 }

You can also do

你也可以这样做

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

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

And if you need to insert rows/columns

如果您需要插入行/列

// 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 );

回答by cordellcp3

I think, that you have to declare the associated sheet!

我认为,您必须声明相关的工作表!

Try something like this

尝试这样的事情

objsheet(1).Cells[i,j].Value;

回答by GvS

How I work to automate Office / Excel:

我如何使 Office / Excel 自动化:

  1. Record a macro, this will generate a VBA template
  2. Edit the VBA template so it will match my needs
  3. Convert to VB.Net (A small step for men)
  4. Leave it in VB.Net, Much more easy as doing it using C#
  1. 录制一个宏,这将生成一个 VBA 模板
  2. 编辑 VBA 模板,使其符合我的需求
  3. 转换为 VB.Net(男人的一小步)
  4. 将它留在 VB.Net 中,比使用 C# 更容易

回答by Jimbo

Try:

尝试:

Excel.Application oXL;
Excel._Workbook oWB;
Excel._Worksheet oSheet;
Excel.Range oRng;

oXL = new Excel.Application();
oXL.Visible = true;
oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));

oSheet = (Excel._Worksheet)oWB.Worksheets;
oSheet.Activate();

oSheet.Cells[3, 9] = "Some Text"

回答by Anonymous Type

Simple.

简单的。

To open a workbook. Use xlapp.workbooks.Open()

打开工作簿。使用 xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

您之前已经声明并实例化 xlapp 的地方。 Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

参数正确。

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

接下来确保在使用单元格属性或范围对象为单元格分配值时使用属性 Value2。

回答by Andy

This works fine for me

这对我来说很好用

       Excel.Application oXL = null;
        Excel._Workbook oWB = null;
        Excel._Worksheet oSheet = null;

        try
        {
            oXL = new Excel.Application();
            string path = @"C:\Templates\NCRepTemplate.xlt";
            oWB = oXL.Workbooks.Open(path, 0, false, 5, "", "",
                false, Excel.XlPlatform.xlWindows, "", true, false,
                0, true, false, false);

            oSheet = (Excel._Worksheet)oWB.ActiveSheet;
            oSheet.Cells[2, 2] = "Text";

回答by Reddy

You can use the below code; it's working fine for me:

您可以使用以下代码;它对我来说很好用:

newWorkbook = appExcel.Workbooks.Add();