如何将数据网格视图数据发送到Excel文件两次或更多次
本文关键字:数据 文件 两次 数据网 网格 视图 Excel | 更新日期: 2023-09-27 17:57:24
我的windowsforms项目中有一个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);
}
我通过单击按钮更新数据网格视图数据。我想复制所有这些数据网格视图数据并将它们粘贴到同一个 excel 文件表中。当然,单元格范围应该改变。我该怎么办?
我不使用 C# - 这是一个 VB.Net 版本:
使用 C# 版本的导入 Microsoft.Office.Interop 来节省一些键入。
在 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