Description
Hi There,
I am trying to import Microsoft.Office.Interop.Excel for one of the requirement - Combine 2 excel files and save in another file. Below is the code. However i am facing the issue with importing the Microsoft.Office.Interop.Excel .
1.I added from import
2.I added from the manage packages
3.I added directly from the respective xaml file
All the above options not worked.
Imports Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Public Class ExcelCombiner
’ Method to combine two Excel files
Public Sub CombineExcelFiles(file1Path As String, file2Path As String, outputFilePath As String)
’ Declare Excel Interop objects
Dim excelApp As Application = New Application()
Dim workbook1 As Workbook
Dim workbook2 As Workbook
Dim outputWorkbook As Workbook
Dim worksheet1 As Worksheet
Dim worksheet2 As Worksheet
Dim outputWorksheet As Worksheet
Dim lastRow As Integer
' Start Excel Application
excelApp.Visible = False ' Set to True if you want to see Excel working
Try
' Open the first workbook
workbook1 = excelApp.Workbooks.Open(file1Path)
worksheet1 = workbook1.Sheets(1) ' Assuming you're working with the first sheet
' Open the second workbook
workbook2 = excelApp.Workbooks.Open(file2Path)
worksheet2 = workbook2.Sheets(1) ' Assuming you're working with the first sheet
' Create a new workbook for the output
outputWorkbook = excelApp.Workbooks.Add()
outputWorksheet = outputWorkbook.Sheets(1)
outputWorksheet.Name = "CombinedData"
' Copy data from the first worksheet to the output
worksheet1.UsedRange.Copy(outputWorksheet.Cells(1, 1))
' Find the last row in the output worksheet
lastRow = outputWorksheet.Cells(outputWorksheet.Rows.Count, 1).End(XlDirection.xlUp).Row
' Copy data from the second worksheet and append it after the last row in the output
worksheet2.UsedRange.Copy(outputWorksheet.Cells(lastRow + 1, 1))
' Save the combined workbook
outputWorkbook.SaveAs(outputFilePath)
outputWorkbook.Close(False)
Console.WriteLine("Files combined successfully!")
Catch ex As Exception
Console.WriteLine("An error occurred: " & ex.Message)
Finally
' Close all open workbooks and quit Excel
workbook1.Close(False)
workbook2.Close(False)
excelApp.Quit()
' Release COM objects to free up memory
Marshal.ReleaseComObject(workbook1)
Marshal.ReleaseComObject(workbook2)
Marshal.ReleaseComObject(outputWorkbook)
Marshal.ReleaseComObject(excelApp)
End Try
End Sub
End Class
’ The entry point for the program
Public Class Program
Public Shared Sub Main()
’ Define paths for the Excel files
Dim file1Path As String = “C:\path\to\file1.xlsx”
Dim file2Path As String = “C:\path\to\file2.xlsx”
Dim outputFilePath As String = “C:\path\to\combined_output.xlsx”
' Create an instance of the ExcelCombiner class and combine the files
Dim combiner As New ExcelCombiner()
combiner.CombineExcelFiles(file1Path, file2Path, outputFilePath)
End Sub
End Class
Link
Date
2024-12-07
Related UiPath products
Studio