封闭式 XML - Excel - VB,Net

问题描述 投票:0回答:1

我对该领域还很陌生,我一直在尝试使用 ClosedXML 自动创建和修改 excel 文件。 但这似乎不起作用。 我基本上是想通过这段代码将数据从两个文件复制到第三个文件(一个新文件):

Imports System
Imports System.Collections.Specialized
Imports System.Runtime.InteropServices
Imports System.Security.Cryptography
Imports System.Windows.Forms.VisualStyles.VisualStyleElement
Imports ClosedXML
Imports ClosedXML.Excel
Imports DocumentFormat.OpenXml.Spreadsheet

Public Class Form1
    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click

        Dim wb1 As IXLWorkbook = New XLWorkbook("C:\Users\oxy\Downloads\Test\Test.xlsx")
        Dim ws As IXLWorksheet = wb1.AddWorksheet
        wb1.SaveAs("C:\Users\oxy\Downloads\Test\Test2.xlsx")



        Dim wb2 As IXLWorkbook = New XLWorkbook(TextBox1.Text)
        Dim ws2 As IXLWorksheet = wb2.AddWorksheet
        ws.Cell(1, 1).InsertData(ws2.Columns("A:G"))


        wb1.SaveAs("C:\Users\oxy\Downloads\Test\Test2.xlsx")


        Dim wb3 As IXLWorkbook = New XLWorkbook(TextBox2.Text)
        Dim ws3 As IXLWorksheet = wb3.AddWorksheet
        ws.Cell(1, 6).InsertData(ws3.Columns("A:N"))
        wb1.SaveAs("C:\Users\oxy\Downloads\Test\Test2.xlsx")



    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        OpenFileDialog1.Filter = "Excel | *.xls; *.xlsx"
        OpenFileDialog1.ShowDialog()
        TextBox1.Text = OpenFileDialog1.FileName

    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        OpenFileDialog2.Filter = "Excel | *.xls; *.xlsx"
        OpenFileDialog2.ShowDialog()
        TextBox2.Text = OpenFileDialog2.FileName

    End Sub
End Class

我认为,我尝试将列从一个文件复制到另一个文件的方式可能会出现错误,或者选择一系列列的方式可能不正确。 我尝试了一些不同的方法,但这似乎不是问题 这是我在这个社区的第一篇文章,很抱歉有任何错误,提前谢谢您。

c# excel vb.net closedxml
1个回答
0
投票

由于您已将这个问题标记为 C#,这就是我要回答的问题,因此您必须自己将其转换为 VB。

在撰写本文时,您还有两个问题:

  1. 您正在尝试从新的(空)工作表复制
  2. InsertData() 无法获取 Columns 对象。看起来是因为它需要一个 Enumerable,并且 Columns 是 Enumerable,但枚举它不会返回单元格中的数据。因此,一旦解决了问题 1,您创建的文件中就会出现无意义的内容。

我认为这就是你想要做的,尽管我会警告你,我猜测,因为你实际上并没有告诉我们比“我想复制数据”更多的内容

private void Button4_Click( /* args */)
{
    var wb1 = new XLWorkbook(@"C:\Users\oxy\Downloads\Test\Test.xlsx");
    var ws = wb1.AddWorksheet();
    
    var wb2 = new XLWorkbook(TextBox1.Text);
    var ws2 = wb2.Worksheet(1);// assume you want the first
    ws2.Range("A:G").CopyTo(ws.Cell("A1"));

    // repeat for file 2
    
    wb1.SaveAs(@"C:\Users\oxy\Downloads\Test\Test2.xlsx");
}
© www.soinside.com 2019 - 2024. All rights reserved.