Net中操作Excel文件合并
Imports XExcel = Microsoft.Office.Interop.Excel
Imports System.Collections.ObjectModel
Public Class Form1
Private Sub ButtonX1_Click(sender As System.Object, e As System.EventArgs) Handles ButtonX1.Click
Dim pSourcePath As String, pResultPath As String
Dim pSourceWB As XExcel.Workbook
pSourcePath = “T:\ExcelTest”
pResultPath = “T:\ExcelTest\Result”
‘先新建目标文件
Dim pExcelApp As New Microsoft.Office.Interop.Excel.Application
Dim pResultWB As XExcel.Workbook = pExcelApp.Workbooks.Add(XExcel.XlWBATemplate.xlWBATWorksheet)
Dim pFiles As ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(pSourcePath, FileIO.SearchOption.SearchTopLevelOnly, “*.xls”)
If (pFiles.Count <= 0) Then
Return
End If
For Each pFile As String In pFiles
pSourceWB = pExcelApp.Workbooks.Open(pFile)
Dim pResultSheet As XExcel.Worksheet = pResultWB.Sheets.Add()
Dim pSourceSheet As XExcel.Worksheet = pSourceWB.Sheets(1)
With pSourceSheet
.UsedRange.Copy(pResultSheet.Range(pResultSheet.Cells(1, 1), pResultSheet.Cells(100, 10))) ‘,
pResultSheet.Name = pSourceWB.Name
pSourceWB.Close(False)
End With
Next
pResultWB.SaveAs(pResultPath & “\” & “Result.xls”)
pResultWB.Close()
pExcelApp.Workbooks.Close()
pExcelApp.Quit()
For Each pFile As String In pFiles
My.Computer.FileSystem.DeleteFile(pFile)
Next
MsgBox(“合并完成”)
End Sub
End Class