C#: How to access an Excel cell?

后端 未结 7 1115
忘掉有多难
忘掉有多难 2020-12-05 18:25

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

Currently I am at this stage with the following code but

相关标签:
7条回答
  • 2020-12-05 19:27

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

    Check this out, it should get you started,

    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 );
    
    0 讨论(0)
提交回复
热议问题