将数据(包括标题)从DataGridView导出到.xls文件

时间:2016-02-22 16:19:50

标签: c# excel-interop

所以我试图为记录数据添加“Export to .XLS”选项。我有以下代码段来处理从DataGridView导出数据,但是当它打开Excel文件而不是存在的数据时,单元格A1只包含字符串“System.Drawing。”

有人能指出我做错了什么吗?感谢。

    private void copyGridToClipboard(DataGridView dg)
    {
        dg.SelectAll();
        dg.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText;
        DataObject dataObj = dg.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }
    private void myButton_Click(object sender, EventArgs e)
    {
        copyGridToClipboard(myDataGridView);
        Excel.Application xlexcel;
        Excel.Workbook xlWorkbook;
        Excel.Worksheet xlWorksheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkbook = xlexcel.Workbooks.Add(misValue);
        xlWorksheet = (Excel.Worksheet)xlWorkbook.Worksheets.get_Item(1);
        Microsoft.Office.Interop.Excel.Range CR = (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)

我一直在使用DevExpress GridView,所以我不太确定它与DataGridView有多么不同,但我通常从数据源获取数据表然后将其转换为数组并直接设置范围的值。 这是一些可能有效的VB.Net。

Dim dt As DataTable = (DirectCast(DataGridView1.DataSource, DataTable))

'convert to array
Dim columnCount As Integer = dt.Columns.Count - 1
Dim dataArray(dt.Rows.Count, columnCount) As Object
For columnIndex As Integer = 0 To columnCount
    dataArray(0, columnIndex) = dt.Columns(columnIndex).Caption
Next columnIndex
For rowIndex As Integer = 0 To dt.Rows.Count - 1
    For columnIndex As Integer = 0 To columnCount
        dataArray(dt.Rows.Count, columnIndex) = dt.Rows(rowIndex)(columnIndex)
    Next columnIndex
Next


'import to excel sheet
Dim lastRow As Integer = dataArray.GetLength(0) + 1
Dim lastColumn As Integer = dataArray.GetLength(1) + 1
Dim cellRange As Excel.Range = xlWorksheet .Range(xlWorksheet .Cells(1, 1), xlWorksheet .Cells(lastRow, lastColumn))
cellRange.Value = dataArray

您可以从DataGridView直接获取数据,但我不熟悉它。 这段代码应该能够通过VB - > C#转换器。