使用VB.Net将文本文件导入excel工作簿



我正在尝试使用vb.net将一些文本文件添加到Excel工作簿中。我想在我的资源文件夹中添加6个文本文件,作为我要创建的6张工作表的模板。我可以为每个文本文件创建单独的工作簿,但在编写将所有文本文件添加到单个工作本中的代码时遇到了困难。我正在复制我现在拥有的代码。我该怎么做?

Dim xlApp As Excel.Application = New Excel.Application With {.Visible =True}
Dim XlDesTemplateBook As Excel.Workbook
Dim xlDesTemplateSheet As Excel.Worksheet
Dim xlDesTemplateSheet1 As Excel.Worksheet
XlDesTemplateBook = xlApp.Workbooks.Add()
xlDesTemplateSheet1 = XlDesTemplateBook.Worksheets.Add("File Path1")
xlDesTemplateSheet1 = XlDesTemplateBook.Worksheets.Add("File Path2")

当我尝试运行代码时,会出现此错误。

System.Runtime.InteropServices.COMException:"HRESULT:0x800A03EC中的异常">

这对我来说很好。

Imports System.IO
Imports System.Text
Imports Microsoft.Office.Interop
Public Class Form1
Dim objexcel As New Excel.Application
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim Paths() As String = Directory.GetFiles("C:your_path_here", "*.txt")
For Each Path As String In Paths
File.AppendAllText("C:your_path_hereTextFileToWriteTo.txt", File.ReadAllText(Path), Encoding.Default) 'The text file will be created if it does not already exist  
Next
Dim objexcel As New Excel.Application
objexcel = CreateObject("Excel.Application")
objexcel.Visible = True
objexcel.Workbooks.Open("C:your_path_hereTextFileToWriteTo.txt",,,,,,,,,,,,,,)
End Sub
End Class

最新更新