将数据网格视图数据导出到excel
本文关键字:数据 excel 视图 数据网 网格 | 更新日期: 2023-09-27 18:19:57
我使用此代码将数据从datagridview导出到excel工作表,但问题是列标题没有导出
private void copyAlltoClipboard()
{
dataGridView1.SelectAll();
DataObject dataObj = dataGridView1.GetClipboardContent();
if (dataObj != null)
Clipboard.SetDataObject(dataObj);
}
{
for (int j = 0; j <= this.dataGridView1.ColumnCount - 1; j++)
{
string colName = dataGridView1.Columns[j].HeaderText;
}
copyAlltoClipboard();
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
xlexcel.Visible = true;
xlWorkBook = xlexcel.Workbooks.Add(misValue);
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);
}
尝试将DataGridViewClipboardCopyMode
属性设置为EnableAlwaysIncludeHeaderText
。