Not able to write to cell using this export-to-excel code
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
精彩评论