简体   繁体   中英

C# Winforms datagridview column header text

I build this code which exports datagridview rows into Excel file

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 <= dgvInventory.RowCount - 1; i++)
{
    for (j = 0; j <= dgvInventory.ColumnCount - 1; j++)
    {
        DataGridViewCell cell = dgvInventory[j, i];
        xlWorkSheet.Cells[i + 1, 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);

it works good but problem is that im unable to export datagridview headertext. can anyone help me?

Do a loop before your main loop, something like this:

    for (int j = 0; j <= this.dataGridView1.ColumnCount - 1; j++)
    {
        string colName = dataGridView1.Columns[j].HeaderText;
    }

and set the header to excel worksheet row(0) or (1), column j to the value of colName.

    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;

    /*header text*/
    for (i = 0; i <= dgvInventory.Columns.Count - 1; i++)
    {
      xlWorkSheet.Cells[1, i+1] = dgvView.Columns[i].HeaderText; 
    }

    /*And the information of your data*/
    for (i = 0; i <= dgvInventory.RowCount - 1; i++)
    {
        for (j = 0; j <= dgvInventory.ColumnCount - 1; j++)
        {
            DataGridViewCell cell = dgvInventory[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);

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