To write Excel by each row while preserving the format of the template Excel file, you can follow the steps below in VB.NET:
-
Create a template Excel file with the desired formatting. Save it in a specific location (e.g., "C:\path\to\template.xlsx").
-
Use the File.Copy() method to create a new file with a different name for writing the data, so that the template file remains intact. For example:
Dim templateFilePath As String = "C:\path\to\template.xlsx"
Dim outputFilePath As String = "C:\path\to\output.xlsx"
File.Copy(templateFilePath, outputFilePath, True)
- Modify the code provided in the previous answer to write the data to the newly created output file:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub btnWriteExcel_Click(sender As Object, e As EventArgs) Handles btnWriteExcel.Click
Dim outputFilePath As String = "C:\path\to\output.xlsx"
'Create a new instance of Excel and open the output file
Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook = xlApp.Workbooks.Open(outputFilePath)
Dim xlWorkSheet As Excel.Worksheet = CType(xlWorkBook.Sheets(1), Excel.Worksheet)
'Data to be written to Excel
Dim data As New List(Of String())()
data.Add(New String() {"John", "Doe", "john.doe@example.com"})
data.Add(New String() {"Jane", "Smith", "jane.smith@example.com"})
data.Add(New String() {"Bob", "Johnson", "bob.johnson@example.com"})
'Loop through each row and write the data
For rowIndex As Integer = 1 To data.Count
Dim rowData As String() = data(rowIndex - 1) 'Get the data for current row
Dim range As Excel.Range = xlWorkSheet.Range("A" & rowIndex.ToString(), "C" & rowIndex.ToString()) 'Specify the range for the row
'Write the data to the range
range.Value = rowData
Next
'Save the workbook and clean up Excel
xlWorkBook.Save()
xlWorkBook.Close()
xlApp.Quit()
'Cleanup
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkSheet)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWorkBook)
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
MessageBox.Show("Excel file created successfully.")
End Sub
End Class
In this modified code, we open the output file (previously created by copying the template file) using xlWorkBook = xlApp.Workbooks.Open(outputFilePath). Now, the code writes the data to the output file while preserving the formatting since it is based on the template file.
After writing the data, we save and close the workbook, and release the Excel objects from memory.
Remember to import the Microsoft.Office.Interop.Excel namespace and add a reference to the "Microsoft Excel Object Library" in your project.