Getting Cell Values from Excel API C#

后端 未结 2 1010
小鲜肉
小鲜肉 2020-12-22 04:44

I have a ribbon that i made for Excel along with a cs File to perform as the core of the add-in. When a button is clicked on the CustomRibbon I want to parse the data values

相关标签:
2条回答
  • 2020-12-22 04:53

    The "lowest" applicable index for referring to a cell in an Excel sheet is [1,1], which corresponds to Column A, Cell 1. I see you're trying to refer to 0,0 which is out of the bounds of the table.

    Though C# typically utilizes zero based table indexing, it appears the programmers of Excel Interop adhered to a different methodology. That or they wanted to keep their conventions uniform, since the first row in an Excel table starts with 1, and not 0. I'm not an Excel buff, but that's my best guess.

    Edit: Per Siddharth's request, here's an example that copies the contents of a DataGridView control to an Excel sheet. Note that this just demonstrates basic functionality, and isn't a complete example or necessarily best practice:

    #using Microsoft.Office.Interop;
    
    Excel.Application xlApp;
    Excel.Workbook xlWorkBook;
    Excel.Worksheet xlWorkSheet;
    
    xlApp = new Excel.ApplicationClass();
    xlWorkBook = xlApp.Workbooks.Add(1);
    xlWorkSheet = Excel.Worksheet xlWorkBook.ActiveSheet;
    
    // Notice the index starting at [1,1] (row,column)
    for (int i=1; i<DataGridView.Columns.Count+1; i++)
        xlWorkSheet.Cells[1, i] = DataGridView.Columns[i - 1].HeaderText;
    
    for each(DataGridViewRow row in DataGridView.Rows)
    {
        for each (DataGridViewColumn column in DataGridView.Columns)
        {
            xlWorkSheet.Cells[row.Index+2,column.Index+1] = DataGridView.Rows[row.Index].Cells[column.Index].Value;
        }
    }
    

    Notice the disparities between the indexing. This example first copies the headers from the DataGridView, then offsets the position in the Excel sheet to copy the rest of the data since the column headers don't count as index-able cells in the DataGrid. This would probably also work for DataTables.

    0 讨论(0)
  • 2020-12-22 05:13

    Try using the Value2 field of the cell.

    sheet.Cells[1,1].Value2 = "hello";
    

    Also in this line

    Console.WriteLine(Globals.ThisAddIn.Application.Cells[1, 1]);
    

    The "Cells" field is a property of a worksheet. You can't use it on the Excel application; you need to first create or open a Workbook and then create or use an existing Worksheet.

    EDIT: Forgot that Excel ranges are 1-index and not 0-index.

    0 讨论(0)
提交回复
热议问题