Plenty of VB.NET business apps still write their Excel output through Microsoft.Office.Interop.Excel. It works until it doesn’t, and the maintenance tickets all sound alike: EXCEL.EXE is still sitting in Task Manager. It fails on a PC without Office, or with a different Office version. The export is slow. It hangs when run from Task Scheduler.
This article takes a typical Interop routine, one that builds a sales list and saves it as .xlsx and PDF, and replaces it with ReoGrid. We ran the Interop version too, to watch EXCEL.EXE outlive it and to time it. Further down are a mapping table from Interop calls to ReoGrid and the porting mistakes that are easy to make. All of the ReoGrid code was compiled with Option Strict On, and every file it wrote was opened in Excel to check it.
Which ReoGrid for your project
| Your project | Use | Package |
|---|---|---|
| .NET 10 | ReoGrid V5 | unvell.ReoGrid.One |
| .NET Framework 4.8, or .NET 8 (Windows) | ReoGrid V4 | unvell.ReoGrid4 |
Most VB.NET apps that use Interop are on .NET Framework, and those want V4: skip to the V4 code. Both versions install from UNVELL’s package feed (V5 setup, V4 setup), and a 30-day trial key covers either one.
Before: the Interop code you usually find
This routine turns a DataTable of sales into a table and saves it as .xlsx and PDF, written the way it usually is in code that has been maintained for years: Option Strict Off, one Cells(row, col) assignment per value.
Option Strict Off
Imports System.Data
Imports System.IO
Imports System.Runtime.InteropServices
Imports Excel = Microsoft.Office.Interop.Excel
Public Module SalesReport
Public Sub ExportSales(table As DataTable, xlsxPath As String)
Dim xlApp As New Excel.Application()
xlApp.DisplayAlerts = False
Dim books As Excel.Workbooks = xlApp.Workbooks
Dim book As Excel.Workbook = books.Add()
Dim sheet As Excel.Worksheet = book.Worksheets(1)
Try
sheet.Range("A1").Value = "Sales"
sheet.Range("A1").Font.Bold = True
sheet.Range("A1").Font.Size = 14
' Header (row 3)
For c = 0 To table.Columns.Count - 1
sheet.Cells(3, c + 1).Value = table.Columns(c).ColumnName
Next
sheet.Range("A3:E3").Font.Bold = True
sheet.Range("A3:E3").Interior.Color = RGB(221, 235, 247)
' Data (from row 4)
For r = 0 To table.Rows.Count - 1
For c = 0 To table.Columns.Count - 1
sheet.Cells(r + 4, c + 1).Value = table.Rows(r)(c)
Next
Next
Dim last = table.Rows.Count + 3
sheet.Range($"A4:A{last}").NumberFormat = "yyyy-mm-dd"
sheet.Range($"D4:E{last}").NumberFormat = "#,##0"
' Total
sheet.Cells(last + 1, 4).Value = "Total"
sheet.Cells(last + 1, 5).Formula = $"=SUM(E4:E{last})"
sheet.Cells(last + 1, 5).NumberFormat = "#,##0"
sheet.Range($"A3:E{last + 1}").Borders.LineStyle = Excel.XlLineStyle.xlContinuous
sheet.Columns("A:E").AutoFit()
book.SaveAs(xlsxPath)
book.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, Path.ChangeExtension(xlsxPath, ".pdf"))
Finally
book.Close(False)
xlApp.Quit()
Marshal.ReleaseComObject(sheet)
Marshal.ReleaseComObject(book)
Marshal.ReleaseComObject(books)
Marshal.ReleaseComObject(xlApp)
End Try
End Sub
End Module
The output itself is fine: open it in Excel and the table is what you expect. The trouble is everything around it.
EXCEL.EXE survives Quit
The code calls Quit and releases all four COM objects it holds in variables with ReleaseComObject. Even so, EXCEL.EXE was still running ten seconds after ExportSales returned.
The culprits are the intermediate objects that never went into a variable. sheet.Range("A1").Font.Bold quietly creates two COM objects, a Range and a Font, and sheet.Cells(r + 4, c + 1) creates another one on every pass through the loop. Nothing releases them, so Excel cannot exit until the .NET garbage collector gets round to them. Sure enough, EXCEL.EXE exited as soon as we called GC.Collect() and GC.WaitForPendingFinalizers().
You can put every intermediate object in a variable and release each one (the “two dots” rule), but the code nearly doubles in size. And when the save failed and the app ended on an unhandled exception, EXCEL.EXE kept running after the app had exited, Quit notwithstanding, until we ended it by hand.
Cell-by-cell writes are slow
Each Cells(r, c).Value = … is a round trip to Excel, which runs in a separate process. For a five-column table, 1,000 rows took 10.9 s and 10,000 rows took 66.2 s. ReoGrid V5 produced the same output in 0.16 s and 0.57 s (test setup, plus the array-write variant, below).
It needs Excel installed
Interop starts a real copy of Excel in the background and drives it. Every PC that runs your code needs Office, and every Office update or reinstall reaches your code. Running it from a service or a scheduled task is not supported by Microsoft.
After: the same output with ReoGrid V5
Add the package to your .vbproj project.
dotnet add package unvell.ReoGrid.One
Apply your license key once when the application starts. Without a key, saving throws ReoGridLicenseException.
Imports unvell.ReoGrid.Core.License
ReoGridLicense.SetLicense(myLicenseKey)
Then replace ExportSales with the module below. The parameters and the way you call it stay the same.
Imports System.Data
Imports System.IO
Imports unvell.ReoGrid.Core
Imports unvell.ReoGrid.Core.Style
Imports unvell.ReoGrid.IO.Excel
Imports unvell.ReoGrid.IO.Pdf
Public Module SalesReport
Public Sub ExportSales(table As DataTable, xlsxPath As String)
Dim book As New Workbook()
Dim ws = book.AddWorksheet("Sheet1")
ws.SetText(0, 0, "Sales")
ws.SetCellStyle(0, 0, New StyleRecord With {.Bold = True, .FontSize = 14})
' Header (row 3, which is index 2: indexes count from 0)
For c = 0 To table.Columns.Count - 1
ws.SetText(2, c, table.Columns(c).ColumnName)
Next
ws.SetRangeStyle("A3:E3", New StyleRecord With {.Bold = True, .BackgroundColor = &HFFDDEBF7UI})
' Data (from row 4)
For r = 0 To table.Rows.Count - 1
For c = 0 To table.Columns.Count - 1
Dim value = table.Rows(r)(c)
ws.SetObjectValue(r + 3, c, If(value Is DBNull.Value, Nothing, value))
Next
Next
Dim last = table.Rows.Count + 3 ' last data row, as Excel numbers it
ws.SetNumberFormat(ws.ResolveRange($"A4:A{last}"), "yyyy-mm-dd")
ws.SetNumberFormat(ws.ResolveRange($"D4:E{last + 1}"), "#,##0")
' Total. No leading = on the formula
ws.Cell($"D{last + 1}").SetText("Total")
ws.Cell($"E{last + 1}").SetFormula($"SUM(E4:E{last})")
' Borders: a full grid over the table
Dim edge As New BorderEdge(BorderLineStyle.Solid, &HFF000000UI, 1.0F)
Dim area = ws.ResolveRange($"A3:E{last + 1}")
For r = area.Row To area.EndRow
For c = area.Col To area.EndCol
ws.Borders.Set(r, c, New CellBorders(edge, edge, edge, edge))
Next
Next
' Column widths (pixels)
Dim widths = {90, 150, 150, 60, 90}
For c = 0 To widths.Length - 1
ws.Columns.SetSize(c, widths(c))
Next
' Like Excel's default: no gridlines when printed or exported to PDF
ws.PrintSettings.ShowGridLines = False
XlsxWriter.Write(book, xlsxPath)
PdfExporter.Export(book, Path.ChangeExtension(xlsxPath, ".pdf"))
End Sub
End Module
=SUM(E4:E9).Compared with the Interop version:
- Clean-up is left to .NET. A
Workbookis an ordinary .NET object, so you write noQuit,ReleaseComObjectorFinally. Everything happens inside your own process, so an exception halfway through leaves nothing running behind it. - It runs as-is on PCs without Office installed. ReoGrid writes both the
.xlsxand the PDF itself. - It builds with
Option Strict On. Interop’sCells(r, c).Valuerelies on late binding; every ReoGrid method here is strongly typed. - Column widths are in pixels. On a workbook with no screen you set them as numbers, as above. When the sheet is on screen,
ReoGridControl.AutoFitSelectedColumns()fits the selected columns to their content.
Interop calls and their ReoGrid equivalents
Common Interop calls and how to write them with ReoGrid V5. Interop counts rows and columns from 1; ReoGrid counts them from 0. The V4 equivalents are in the V4 section.
| To do this | Interop | ReoGrid V5 |
|---|---|---|
| Start and stop Excel | New Excel.Application() / Quit() / ReleaseComObject | Not needed |
| New workbook | xlApp.Workbooks.Add() | New Workbook() and book.AddWorksheet("Sheet1") |
| Open a file | xlApp.Workbooks.Open(path) | XlsxReader.Read(path) |
| Sheet by name | book.Worksheets("Sales") | book("Sales") |
| Add a sheet | book.Worksheets.Add() | book.AddWorksheet("Summary") |
| Write a value (address) | sheet.Range("B2").Value = 100 | ws.Cell("B2").SetNumber(100) |
| Write a value (row, column) | sheet.Cells(2, 3).Value = x | ws.SetObjectValue(1, 2, x) |
| Write a block | Range("A2:E100").Value = arr | SetObjectValue per cell |
| Read a value | .Value | ws.GetObjectValue(r, c) |
| Read the displayed text | .Text | ws.GetDisplayText(r, c) |
| Formula | .Formula = "=SUM(A1:A3)" | ws.SetFormula(r, c, "SUM(A1:A3)") |
| Number format | .NumberFormat = "#,##0" | ws.SetNumberFormat(range, "#,##0") |
| Bold, font size, text color | .Font.Bold / .Font.Size / .Font.Color | Bold / FontSize / Color on a StyleRecord |
| Fill color | .Interior.Color = RGB(221, 235, 247) | BackgroundColor = &HFFDDEBF7UI on a StyleRecord |
| Borders | .Borders.LineStyle = xlContinuous | ws.Borders.SetOutline / ws.Borders.Set |
| Merge cells | .Merge() | ws.MergeRange(range) |
| Column width | .ColumnWidth = 12 (characters) | ws.Columns.SetSize(c, 90) (pixels) |
| Insert a row | .Rows(5).Insert() | ws.InsertRows(4, 1) |
| Find the last row | .Cells(.Rows.Count, 1).End(xlUp).Row | used.EndRow from ws.TryGetUsedRange(used) |
| Save | book.SaveAs(path) | XlsxWriter.Write(book, path) |
| Save as PDF | book.ExportAsFixedFormat(xlTypePDF, path) | PdfExporter.Export(book, path) |
sheet.PrintOut() | New GridPrintDocument(book, Nothing).Print() (WinForms) |
For printing and PDF see Printing and Page Setup and PDF Export; for borders, Borders.
Porting mistakes that are easy to make
Even with the table in hand, a few things behave differently from Interop. We ran into every one of these while writing the code for this article.
| What you wrote | What happens | What to write |
|---|---|---|
Copied Cells(4, 1) as (4, 1) | The value lands one row down and one column right | Subtract 1 from both. Address strings such as "A4" carry over unchanged |
Passed "=SUM(…)" to V5’s SetFormula | #NAME? on screen and in the PDF | Drop the leading = |
Ported .Value = "=SUM(…)" to SetObjectValue in V5 | The text goes in as a string, not a formula | Use SetFormula |
| Wrote a date without a number format | Excel shows a serial number such as 46355 | Add a format such as yyyy-mm-dd with SetNumberFormat (Interop added a date format for you) |
Passed DBNull straight to SetObjectValue | The cell gets an empty string, which COUNTA counts | Pass Nothing instead |
Passed CUInt(RGB(221, 235, 247)) as a color | Red and blue swap places, and the light blue comes out light orange: RGB() packs blue, green, red | Write &HFF followed by red, green, blue (&HFFDDEBF7UI) |
Copied the number from ColumnWidth = 12 | A very narrow column | ReoGrid widths are pixels. Roughly 7–8 times the character count |
Treated a date read back with V5 as a Date | GetObjectValue returns a Double, and the conversion throws | Turn it back with Date.FromOADate(CDbl(v)) |
Wrote IO.Path.Combine | BC30456: 'Path' is not a member of 'unvell.ReoGrid.Core.IO' | Add Imports System.IO and write Path.Combine. The same goes for Text.Encoding |
The last one is peculiar to VB.NET. In a file that has Imports unvell.ReoGrid.Core, a name starting with IO or Text resolves to ReoGrid’s namespace of that name. Write the full name, as in System.IO.Path, or add Imports System.IO.
Gridlines differ when printing, too. Excel does not print gridlines by default; ReoGrid draws them when printing and in PDFs, and a saved .xlsx prints them from Excel as well. Setting ws.PrintSettings.ShowGridLines = False, as the code above does, gives you the same look as the Interop version.
How fast
The same five-column sales data, timed until both the .xlsx and the PDF were saved. Each figure is the median of three runs.
| 1,000 rows | 10,000 rows | |
|---|---|---|
| Interop, one cell at a time (the code above as-is) | 10.9 s | 66.2 s |
| Interop, data copied into an array and written once | 1.8 s | 8.0 s |
| ReoGrid V5 | 0.16 s | 0.57 s |
ReoGrid V4 (.xlsx only) | 0.25 s | 0.42 s |
Most of Interop’s time goes on the cell-by-cell writes. Copying the data into an array and writing it in one call brings 10,000 rows down to 8.0 s. ReoGrid V5 still finished the same output in 0.57 s.
Test setup: Ryzen 9 9900X, Windows 11 Pro, Excel 2021 (64-bit, 16.0.20326). Interop ran on .NET Framework 4.8, ReoGrid V5 on .NET 10 and V4 on .NET Framework 4.8; the Interop times include starting Excel.
Opening a template and filling it in
Code that opens a workbook designed in Excel and only fills in values ports the same way.
' Interop
' Dim book = xlApp.Workbooks.Open(templatePath)
' book.Worksheets(1).Range("B3").Value = customerName
' book.SaveAs(outputPath)
' ReoGrid V5
Dim book = XlsxReader.Read(templatePath)
book(0).Cell("B3").SetText(customerName)
XlsxWriter.Write(book, outputPath)
Borders, fonts, number formats, formulas and page setup are saved as the template had them. Filling an Excel Template walks through it.
Two things to check about the template:
- Save an
.xlstemplate as.xlsxfirst. ReoGrid reads and writes.xlsx. Open it in Excel, choose Save As and pick.xlsx, and it is ready to use. - Charts and shapes are dropped when the template is saved again. Values, formatting and images are kept. For a report that needs a chart, keep Interop for that part, or paste the chart into the template as an image.
When to keep Interop
ReoGrid is a component that reads and writes Excel files; it does not drive Excel itself. For the jobs below, keeping Interop for that part is the practical choice.
- Running VBA macros (
xlApp.Run("MacroName")). ReoGrid does not run the macros in an.xlsm. - Opening a workbook with charts or pivot tables and saving it back.
- Showing the user Excel itself. Open the saved file with
Process.Startand it appears in the user’s own Excel (on .NET 10, setUseShellExecutetoTrueon theProcessStartInfo). To show the table inside your own form, place aReoGridControlon it.
If Interop only writes your output, the module above removes the Office dependency entirely.
The same export on V4 (.NET Framework 4.8)
V4’s package is unvell.ReoGrid4, which runs on .NET Framework 4.8 and .NET 8 (Windows). The license call is the same, with Imports unvell.ReoGrid.License.
Imports System.Data
Imports unvell.ReoGrid
Imports unvell.ReoGrid.DataFormat
Imports unvell.ReoGrid.Graphics
Imports unvell.ReoGrid.IO
Public Module SalesReport
Public Sub ExportSales(table As DataTable, xlsxPath As String)
Dim book = ReoGridControl.CreateMemoryWorkbook()
Dim ws = book.Worksheets(0)
Dim last = table.Rows.Count + 3 ' last data row, as Excel numbers it
ws.Resize(last + 1, table.Columns.Count)
ws("A1") = "Sales"
ws.SetRangeStyles("A1", New WorksheetRangeStyle With {
.Flag = PlainStyleFlag.FontStyleBold Or PlainStyleFlag.FontSize,
.Bold = True, .FontSize = 14})
' Header
For c = 0 To table.Columns.Count - 1
ws(2, c) = table.Columns(c).ColumnName
Next
ws.SetRangeStyles("A3:E3", New WorksheetRangeStyle With {
.Flag = PlainStyleFlag.FontStyleBold Or PlainStyleFlag.BackColor,
.Bold = True, .BackColor = SolidColor.FromArgb(255, 221, 235, 247)})
' Data: the whole DataTable in one call
ws.SetRangeData(New RangePosition(3, 0, table.Rows.Count, table.Columns.Count), table)
ws.SetRangeDataFormat($"A4:A{last}", CellDataFormatFlag.DateTime,
New DateTimeDataFormatter.DateTimeFormatArgs With {.Format = "yyyy-MM-dd"})
ws.SetRangeDataFormat($"D4:E{last + 1}", CellDataFormatFlag.Number,
New NumberDataFormatter.NumberFormatArgs With {.DecimalPlaces = 0, .UseSeparator = True})
' Total. V4 treats a string starting with = as a formula
ws(last, 3) = "Total"
ws(last, 4) = $"=SUM(E4:E{last})"
ws.SetRangeBorders($"A3:E{last + 1}", BorderPositions.All, RangeBorderStyle.BlackSolid)
' Column widths (pixels)
Dim widths As UShort() = {90, 150, 150, 60, 90}
For c = 0 To widths.Length - 1
ws.SetColumnsWidth(c, 1, widths(c))
Next
book.Save(xlsxPath, FileFormat.Excel2007)
End Sub
End Module
V4 has SetRangeData, the closest thing to Interop’s array write, and it takes a DataTable directly. Formulas work as in Interop: assign a string that starts with =.
Each entry of the mapping table looks like this on V4:
| To do this | ReoGrid V4 |
|---|---|
| Start and stop Excel | Not needed |
| New workbook | ReoGridControl.CreateMemoryWorkbook() |
| Open a file | book.Load(path, FileFormat.Excel2007) |
| Sheet by name | book.Worksheets("Sales") |
| Add a sheet | book.Worksheets.Add(book.CreateWorksheet("Summary")) |
| Write a value (address) | ws("B2") = 100 |
| Write a value (row, column) | ws(1, 2) = x |
| Write a block | ws.SetRangeData(range, arr) (a DataTable works too) |
| Read a value | ws.GetCellData(r, c) |
| Read the displayed text | ws.GetCellText(r, c) |
| Formula | ws(r, c) = "=SUM(A1:A3)" |
| Number format | ws.SetRangeDataFormat(range, CellDataFormatFlag.Number, …) |
| Bold, font size, text color | Bold / FontSize / TextColor on a WorksheetRangeStyle |
| Fill color | BackColor on a WorksheetRangeStyle |
| Borders | ws.SetRangeBorders(range, BorderPositions.All, RangeBorderStyle.BlackSolid) |
| Merge cells | ws.MergeRange(range) |
| Column width | ws.SetColumnsWidth(c, 1, 90) (pixels) |
| Insert a row | ws.InsertRows(4, 1) |
| Find the last row | ws.MaxContentRow |
| Save | book.Save(path, FileFormat.Excel2007) |
| Save as PDF | Use printing (CreatePrintSession) |
ws.CreatePrintSession().Print() (WinForms) |
Current limitations on V4
- On a workbook with no screen (
CreateMemoryWorkbook),AutoFitColumnsWidththrows. Set column widths as numbers, as above. - Exporting straight to PDF is a V5 feature. On V4, use WinForms printing (
CreatePrintSession).
Summary
EXCEL.EXEoutlives Interop code because intermediate COM objects are never released. A ReoGrid workbook is an ordinary .NET object and needs no clean-up- Cell-by-cell writes are where Interop is slowest. The 10,000-row export that took 66 s through Interop took 0.57 s with ReoGrid V5
- When porting, count rows and columns from 0, drop the leading
=from formulas, and give dates a number format - Turn
DBNullintoNothing, colors into&HFFplus red, green, blue, and column widths into pixels - Keep Interop for running VBA macros and for saving back workbooks with charts
- V5 on .NET 10, V4 on .NET Framework 4.8
See what’s new in V5 / Start a 30-day trial
Further reading
- Using ReoGrid from VB.NET — project setup and reading C# samples as VB
- Filling an Excel Template
- XLSX Import and Export — what is saved and read back
- Export a DataGridView to Excel (.xlsx) in VB.NET
- Import an Excel File into a DataGridView in VB.NET
- Reading, Writing, and Displaying Excel Files in VB.NET
- Spreadsheet to PDF in C#