当前位置: 动力学知识库 > 问答 > 编程问答 >

excel - 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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: