c# Winforms datagridview列标题文本
本文关键字:标题 文本 datagridview Winforms | 更新日期: 2023-09-27 18:08:35
我构建了这段代码,将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);
它工作得很好,但问题是我无法导出datagridviewheadertext。有人能帮我吗?
在主循环之前做一个循环,像这样:
for (int j = 0; j <= this.dataGridView1.ColumnCount - 1; j++)
{
string colName = dataGridView1.Columns[j].HeaderText;
}
并设置标题为excel工作表行(0)或(1),列j为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);