我对该领域还很陌生,我一直在尝试使用 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#,这就是我要回答的问题,因此您必须自己将其转换为 VB。
在撰写本文时,您还有两个问题:
我认为这就是你想要做的,尽管我会警告你,我猜测,因为你实际上并没有告诉我们比“我想复制数据”更多的内容
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");
}