2015-06-22 55 views
0

我有一個DataGridView我windowsforms項目,我可以將其導出到Excel文件中像爲:如何發送datagridview的數據到Excel文件兩次以上

private void btnExcel_Click(object sender, EventArgs e) 
    { 
     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.Open("C:\\file.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
     xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); 
     Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range)xlWorkSheet.Cells[12, 3]; 
     CR.Select(); 

     xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true); 
    } 

private void copyAlltoClipboard() 
    { 
     dataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; 
     dataGridView1.MultiSelect = true; 
     dataGridView1.SelectAll(); 
     DataObject dataObj = dataGridView1.GetClipboardContent(); 
     if (dataObj != null) 
      Clipboard.SetDataObject(dataObj); 
    } 

我通過點擊一個按鈕更新datagridview的數據。我想複製這些所有datagridview數據並將它們粘貼到同一個excel文件表中。當然細胞範圍應該改變。我能怎麼做?

回答

0

我不使用C# - 這裏是一個VB.Net版本:

使用進口Microsoft.Office.Interop的C#版本,以節省一些打字。

在OP的昏暗CR ...設定的目的地範圍內。我添加了另一個不同範圍的粘貼。

代碼在範圍操作以使用當前選擇的,而不是直接。當您錄製宏生成的代碼運行在選擇,但你的代碼可以定義範圍,就可以直接操作。

Imports Microsoft.Office.Interop 

Private Sub Button8_Click(sender As Object, e As EventArgs) Handles Button8.Click 
    copyAlltoClipboard(dgv) 
    Dim xlexcel As Excel.Application 
    Dim xlWorkBook As Excel.Workbook 
    Dim xlWorkSheet As Excel.Worksheet 
    xlexcel = New Excel.Application 
    xlexcel.Visible = True 
    xlWorkBook = xlexcel.Workbooks.Open("C:\temp\file.xlsx") 
    xlWorkSheet = xlWorkBook.Worksheets(1) 

    Dim CR As Excel.Range = xlWorkSheet.Cells(12, 3) 
    CR.PasteSpecial() 

    ' change range and paste again 
    CR = xlWorkSheet.Cells(1, 3) 
    CR.PasteSpecial() 
End Sub