C#Winforms datagridview列标题文本

时间:2011-09-12 18:37:27

标签: c# excel datagridview

我构建了这个将datagridview行导出到Excel文件中的代码

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

它运作良好,但问题是我无法导出datagridview headertext。有谁可以帮助我?

2 个答案:

答案 0 :(得分:3)

在主循环之前做一个循环,如下所示:

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

并将标题设置为excel工作表行(0)或(1),将列j设置为colName的值。

答案 1 :(得分:0)

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