I have the code to parse data to a Datagridview and then export that into an excel spreadsheet. How can I export the headers of the datagridview?

var bs3 = new BindingSource { DataSource = query }; 
 
            dataGridView1.AutoGenerateColumns = true; 
            dataGridView1.AutoSize = true; 
 
            dataGridView1.DataSource = bs3; 
        } 
    } 
 
 
    private void RunExcel() 
    {  
        Excel.Application xlApp ; 
        Excel.Workbook xlWorkBook ; 
        Excel.Worksheet xlWorkSheet ; 
        object misValue = System.Reflection.Missing.Value; 
 
        xlApp = new Excel.Application(); 
        xlWorkBook = xlApp.Workbooks.Add(misValue); 
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
 
 
        int i = 0; 
        int j = 0; 
 
 
        for (i = 0; i <= dataGridView1.RowCount  - 1; i++) 
        { 
            for (j = 0; j <= dataGridView1.ColumnCount  - 1; j++) 
            { 
                DataGridViewCell cell = dataGridView1[j, i]; 
                xlWorkSheet.Cells[i + 1, j + 1] = cell.Value; 
            } 
 
 
        }

Recommended Answers

All 4 Replies

Check this code:

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

//get columns:
for (int i = 0; i <= this.dataGridView1.ColumnCount - 1; i++)
{
   string colName = dataGridView1.Columns[i].HeaderText;
   xlWorkSheet.Cells[1, i] = colName;
}

//get data:
//you can erase this if you dont need data from rows:
for (int i = 0; i <= dataGridView1.RowCount - 1; i++)
{
    for (int j = 0; j <= dataGridView1.ColumnCount - 1; j++)
    {
        DataGridViewCell cell = dataGridView1[j, i];
        xlWorkSheet.Cells[i + 2, j + 1] = cell.Value;
    }
}

xlWorkBook.SaveAs(
    "D:\\exp.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue,
    misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue,
    misValue, misValue, misValue, misValue
);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();

releaseObject(xlWorkSheet);
releaseObject(xlWorkBook);
releaseObject(xlApp);

No, that didn't work I tried that earlier I get the error: local variable 'i' cannot be defined in this scope because it would be given a different mening to 'i' since it is used in a parent to define something else.

Ups, sorry, there was a typo. Check the code ones again (I changes the 1st for loop - there was a "j" instead of an "i" inside).

Same error.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.