将datagridview数据导出为ex​​cel

时间:2015-10-31 12:01:13

标签: c#

我正在使用此代码将数据从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);
            }

1 个答案:

答案 0 :(得分:0)

尝试将DataGridViewClipboardCopyMode属性设置为EnableAlwaysIncludeHeaderText