简体   繁体   中英

How to save HeadColumn in DataGridView to Excel?

I make datagridview export to excel

but Headcolumn don't show in excel files.

Sample

result (in Excel)

1 | mani | 213/435 | 0-892-342234-09
2 | ware | 1/67    | 053-36-49

But I need result (in Excel)

ID | Name | Address | Tel. >>> **Headcolumn**
1  | mani | 213/435 | 0-892-342234-09
2  | ware | 1/67    | 053-36-49

Code C# Windows Form

        private void btExport_Click(object sender, EventArgs e)
        {
            string sql = @"SELECT id,fullname,address,tele FROM tablePeople";
            SqlCommand cmd = new SqlCommand(sql, Conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds, "data");
            DataTable dt = ds.Tables["data"];

            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 r = 0;
            int c = 0;

            // DGV To EXCLE But HeadColumn don't show in excel
            for (r = 0; r <= dataGridView1.RowCount - 1; r++)
            {
                for (c = 0; c <= dataGridView1.ColumnCount - 1; c++)
                {
                    DataGridViewCell cell = dataGridView1[c, r];
                    xlWorkSheet.Cells[r + 1, c + 1] = cell.Value;
                }
            }

            xlWorkBook.SaveAs(@"c:\details.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);

            MessageBox.Show("Excel file created");
        }

Thanks you very much for your time :)

There is a Columns collection in both DataGridView and DataTable You can get your column name by iterating over them.

Before you do this:

for (r = 0; r <= dataGridView1.RowCount - 1; r++)
{
    for (c = 0; c <= dataGridView1.ColumnCount - 1; c++)
    {
        DataGridViewCell cell = dataGridView1[c, r];
        xlWorkSheet.Cells[r + 1, c + 1] = cell.Value;
    }
}

Add this code:

c = 0;
foreach(DataGridViewColumn dataGridViewColumn in dataGridView1.Columns)
{
    xlWorkSheet.Cells[0, c++] = dataGridViewColumn.Name;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM