Replacing Excel Interop in VB.NET — Faster, Without Depending on Excel or Other Apps

· unvell team
Replacing Excel Interop in VB.NET — Faster, Without Depending on Excel or Other Apps

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 projectUsePackage
.NET 10ReoGrid V5unvell.ReoGrid.One
.NET Framework 4.8, or .NET 8 (Windows)ReoGrid V4unvell.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
The sales list written by ReoGrid, open in Excel: a bold Sales title in row 1, a light-blue header in row 3 (Date, Customer, Item, Qty, Amount), six sales and a Total of 101,430 in the last row, with borders around every cell
The .xlsx written by ReoGrid, open in Excel — the same table the Interop version made. Dates are dates, amounts are numbers, and the total cell holds the formula =SUM(E4:E9).

Compared with the Interop version:

  • Clean-up is left to .NET. A Workbook is an ordinary .NET object, so you write no Quit, ReleaseComObject or Finally. 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 .xlsx and the PDF itself.
  • It builds with Option Strict On. Interop’s Cells(r, c).Value relies 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 thisInteropReoGrid V5
Start and stop ExcelNew Excel.Application() / Quit() / ReleaseComObjectNot needed
New workbookxlApp.Workbooks.Add()New Workbook() and book.AddWorksheet("Sheet1")
Open a filexlApp.Workbooks.Open(path)XlsxReader.Read(path)
Sheet by namebook.Worksheets("Sales")book("Sales")
Add a sheetbook.Worksheets.Add()book.AddWorksheet("Summary")
Write a value (address)sheet.Range("B2").Value = 100ws.Cell("B2").SetNumber(100)
Write a value (row, column)sheet.Cells(2, 3).Value = xws.SetObjectValue(1, 2, x)
Write a blockRange("A2:E100").Value = arrSetObjectValue per cell
Read a value.Valuews.GetObjectValue(r, c)
Read the displayed text.Textws.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.ColorBold / FontSize / Color on a StyleRecord
Fill color.Interior.Color = RGB(221, 235, 247)BackgroundColor = &HFFDDEBF7UI on a StyleRecord
Borders.Borders.LineStyle = xlContinuousws.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).Rowused.EndRow from ws.TryGetUsedRange(used)
Savebook.SaveAs(path)XlsxWriter.Write(book, path)
Save as PDFbook.ExportAsFixedFormat(xlTypePDF, path)PdfExporter.Export(book, path)
Printsheet.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 wroteWhat happensWhat to write
Copied Cells(4, 1) as (4, 1)The value lands one row down and one column rightSubtract 1 from both. Address strings such as "A4" carry over unchanged
Passed "=SUM(…)" to V5’s SetFormula#NAME? on screen and in the PDFDrop the leading =
Ported .Value = "=SUM(…)" to SetObjectValue in V5The text goes in as a string, not a formulaUse SetFormula
Wrote a date without a number formatExcel shows a serial number such as 46355Add a format such as yyyy-mm-dd with SetNumberFormat (Interop added a date format for you)
Passed DBNull straight to SetObjectValueThe cell gets an empty string, which COUNTA countsPass Nothing instead
Passed CUInt(RGB(221, 235, 247)) as a colorRed and blue swap places, and the light blue comes out light orange: RGB() packs blue, green, redWrite &HFF followed by red, green, blue (&HFFDDEBF7UI)
Copied the number from ColumnWidth = 12A very narrow columnReoGrid widths are pixels. Roughly 7–8 times the character count
Treated a date read back with V5 as a DateGetObjectValue returns a Double, and the conversion throwsTurn it back with Date.FromOADate(CDbl(v))
Wrote IO.Path.CombineBC30456: '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 rows10,000 rows
Interop, one cell at a time (the code above as-is)10.9 s66.2 s
Interop, data copied into an array and written once1.8 s8.0 s
ReoGrid V50.16 s0.57 s
ReoGrid V4 (.xlsx only)0.25 s0.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 .xls template as .xlsx first. 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.Start and it appears in the user’s own Excel (on .NET 10, set UseShellExecute to True on the ProcessStartInfo). To show the table inside your own form, place a ReoGridControl on 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 thisReoGrid V4
Start and stop ExcelNot needed
New workbookReoGridControl.CreateMemoryWorkbook()
Open a filebook.Load(path, FileFormat.Excel2007)
Sheet by namebook.Worksheets("Sales")
Add a sheetbook.Worksheets.Add(book.CreateWorksheet("Summary"))
Write a value (address)ws("B2") = 100
Write a value (row, column)ws(1, 2) = x
Write a blockws.SetRangeData(range, arr) (a DataTable works too)
Read a valuews.GetCellData(r, c)
Read the displayed textws.GetCellText(r, c)
Formulaws(r, c) = "=SUM(A1:A3)"
Number formatws.SetRangeDataFormat(range, CellDataFormatFlag.Number, …)
Bold, font size, text colorBold / FontSize / TextColor on a WorksheetRangeStyle
Fill colorBackColor on a WorksheetRangeStyle
Bordersws.SetRangeBorders(range, BorderPositions.All, RangeBorderStyle.BlackSolid)
Merge cellsws.MergeRange(range)
Column widthws.SetColumnsWidth(c, 1, 90) (pixels)
Insert a rowws.InsertRows(4, 1)
Find the last rowws.MaxContentRow
Savebook.Save(path, FileFormat.Excel2007)
Save as PDFUse printing (CreatePrintSession)
Printws.CreatePrintSession().Print() (WinForms)

Current limitations on V4

  • On a workbook with no screen (CreateMemoryWorkbook), AutoFitColumnsWidth throws. Set column widths as numbers, as above.
  • Exporting straight to PDF is a V5 feature. On V4, use WinForms printing (CreatePrintSession).

Summary

  • EXCEL.EXE outlives 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 DBNull into Nothing, colors into &HFF plus 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

Try ReoGrid in your own project

The Excel-compatible spreadsheet component for .NET WinForms, WPF and Avalonia. 30-day free trial — no credit card required.

Newsletter

New releases, straight to your inbox

Occasional updates on ReoGrid releases, features, and technical articles. Unsubscribe anytime.

Related articles

Import an Excel File into a DataGridView in VB.NET — Without Office or OLEDB

The usual OLEDB route stops on any PC without the Access Database Engine, and it guesses each column's type from the first few rows, so values that don't fit arrive empty. This VB.NET module reads an .xlsx file into a typed DataTable and shows it in a DataGridView: title rows above the header, dates, merged cells, leading zeros and the total row underneath are all handled. Code for ReoGrid V5 on .NET 10 and V4 on .NET Framework 4.8.

Export a DataGridView to Excel (.xlsx) in VB.NET — Without Office Interop

The usual Interop loop stops working on the first PC without Office, and it quietly turns a ZIP code like 02134 into 2134. This VB.NET module writes a DataGridView to a real .xlsx file instead: visible columns in screen order, numbers as numbers, dates as dates, leading zeros intact. Complete code for ReoGrid V5 on .NET 10 and V4 on .NET Framework 4.8.

Excel Tables in C# — What "Format as Table" Actually Saves, and How to Create One

Excel's "Format as Table" looks like formatting — a coloured header, striped rows — yet not one cell in the saved file carries a fill. What Excel stores is an object: a range, a header row and a style name. This guide opens up the table part of an .xlsx, explains what the 60 built-in styles really contain, and names the three details that decide whether Excel will open the file at all — then builds a table with filter buttons and a totals row in C# with ReoGrid V5.1.