开发者

Not able to write to cell using this export-to-excel code

开发者 https://www.devze.com 2023-03-23 00:25 出处:网络
I am using this code to export DataGridView rows to an Excel sheet. Excel.Application xlApp; Excel.Workbook xlWorkBook;

I am using this code to export DataGridView rows to an Excel sheet.

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;


        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        int i = 0;
        int j = 0;

        for (i = 0; i <= dgv.RowCount - 1; i++)
        {
            for (j = 0; j <= dgv.ColumnCount - 1; j++)
            {
                DataGridViewCell cell = dgv[j, i];
                xlWorkSheet.Cells[i + 5, j 开发者_JAVA技巧+ 2] = cell.Value;
            }
        }

        string SavedFilePath = Application.StartupPath + "\\GeneratedExcelReports\\";
        xlWorkBook.SaveAs(SavedFilePath + ExcelFileNameToCreate + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

If I add this line of code:

xlWorkSheet.Cells[0,1].Value = "My Test Report";

it generates error, because it has nothing as Value in the list that Intelli-Sense opens. How to edit a particular cell at run-time?


The Cells property is a non-zero indexed array (or whatever this is called => indexes start at 1) due to the VB heritage. So to set the value of the cell situated on row 1 and column 1 use this:

xlWorkSheet.Cells[1, 1].Value = "My Test Report";
                  ^
           must not be zero
0

精彩评论

暂无评论...
验证码 换一张
取 消