Replacement overwrites the existing content within a bookmark range, whereas insertion adds new content at the bookmark position and keeps the existing text. For contracts, reports, and notice templates, insertion is suited to appending supplementary notes, schedules, seals, or appendix body text at fixed placeholders without altering the content already filled in the template.

After locating a bookmark, the BookmarksNavigator of Spire.Doc for C++ can select InsertText(), InsertTable(), InsertParagraph(), or InsertTextBodyPart() according to the content type. The insertion position is determined by the parameters of MoveToBookmark() and can be before or after the start or end marker of the bookmark. All processing takes place in the local process, and the document does not need to be uploaded to any service.

This article covers four features:

The examples use the "Warehouse Scheduling System Implementation Service Agreement" template (ServiceAgreement.docx), the appendix document ScopeAddendum.docx, and the seal image seal.png. The template contains nine bookmarks, and the insertion examples use Budget, ServiceScope, SealAnchor, and AddendumAnchor:

Bookmark Inserted content Main call
Budget Amount in words for the contract value InsertText()
ServiceScope Implementation phase table InsertTable()
SealAnchor Company seal image InsertParagraph()
AddendumAnchor Body of the appendix "Supplementary Notes on Service Scope" InsertTextBodyPart()

The AddendumBody bookmark in the appendix document covers the entire body, which consists of 15 body objects.

Service agreement template containing nine bookmarks

Install Spire.Doc for C++

There are two ways to integrate Spire.Doc for C++ into your application. One way is to install it through NuGet; the other is to download the package from our website and copy the libraries into your program. Installing through NuGet is simpler and is the recommended approach.

  • In Visual Studio, open the NuGet Package Manager, search for Spire.Doc.Cpp, and install it.
  • Alternatively, run nuget install Spire.Doc.Cpp in the project directory, and then add the package's include and lib folders to the project.

An integrated project needs to reference the corresponding import library and to ensure that dependency files such as SpireDocCpp.dll and Spire.Doc.Base.dll are present in the run directory. For detailed configuration instructions, refer to How to Integrate Spire.Doc for C++ in a C++ Application.

Insert Text

BookmarksNavigator->InsertText(text) inserts plain text at the locator, and the original text within the bookmark range remains unchanged. The example inserts the amount in words after the end marker of the Budget bookmark, so the inserted text follows the amount directly.

Operation Method
Locate a bookmark BookmarksNavigator->MoveToBookmark(name, isStart, isAfter)
Insert plain text BookmarksNavigator->InsertText(text)
Insert a paragraph BookmarksNavigator->InsertParagraph(paragraph)
Insert body content BookmarksNavigator->InsertTextBodyPart(part)

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object and call MoveToBookmark("Budget", false, true) to locate the position after the end marker.
  • Call InsertText() to insert the amount in words.
  • Save the result document with Document->SaveToFile().

The code for inserting text is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Documents;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");

    //Insert the amount in words after the end marker of the Budget bookmark
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("Budget", false, true);
    navigator->InsertText(" (in words: four hundred and eighty thousand yuan only)");

    //Save the document as docx
    document->SaveToFile("Output/InsertText.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

After insertion, the amount paragraph in Section 4 reads "The total amount of this Agreement is RMB ¥ 480,000 (in words: four hundred and eighty thousand yuan only) (tax inclusive), ...", and both the original amount and the following text are retained:

Agreement paragraph after inserting the amount in words at the Budget bookmark

The Positioning Parameters Determine the Insertion Base

The two Boolean parameters of MoveToBookmark(name, isStart, isAfter) specify whether the start marker or the end marker serves as the reference and whether the insertion point lies after or before that marker. The example uses false, true, which inserts after the end marker, so the amount in words is placed after the Budget bookmark range and before the original phrase "(tax inclusive)". When a bookmark covers an entire passage, choosing a different base changes whether the new content lands before or after the text.

Inserted Text Inherits the Character Formatting at the Locator

Text inserted with InsertText() inherits the character formatting at the locator. In the example, the Budget bookmark covers the bold red amount, so the inserted amount in words is also displayed in bold red. When the inserted text needs independent formatting, use InsertParagraph() to build a paragraph with its own character formatting, or adjust the formatting of the text outside the bookmark range.

Insertion Versus Replacement

InsertText() adds text at the bookmark position, and both the content within the bookmark range and the bookmark markers are retained. ReplaceBookmarkContent() replaces the content within the bookmark range. Use insertion when supplementary notes need to be appended at a placeholder, and use replacement when the placeholder text needs to be replaced entirely with a new value.

Insert a Table

BookmarksNavigator->InsertTable(table) inserts a table at the locator. The example inserts a four-row, three-column implementation phase table at the ServiceScope bookmark; the table is placed at the start of Section 2 as an overview of the service scope, and the three paragraphs covered by the bookmark remain as they are.

Operation Method
Create a table new Table(document, true)
Build the row and column structure Table->ResetCells(rows, columns)
Obtain a cell Table->GetRows()->GetItem(r)->GetCells()->GetItem(c)
Insert the table BookmarksNavigator->InsertTable(table)

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a Table object and call ResetCells() to build a four-row, three-column structure.
  • Call AddParagraph() for the header cells to add paragraphs, and set bold text, white text, and dark blue shading.
  • Fill the data rows with the implementation phase, planned duration, and key deliverables.
  • Create a BookmarksNavigator object, locate ServiceScope, and call InsertTable() to insert the table.
  • Save the result document with Document->SaveToFile().

The code for inserting a table is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Documents/HorizontalAlignment.h"
#include "Spire/Doc/Formatting/ParagraphFormat.h"
#include "Spire/Doc/Table.h"
#include "Spire/Doc/TableRow.h"
#include "Spire/Doc/TableCell.h"
#include "Spire/Doc/Collections/RowCollection.h"
#include "Spire/Doc/Collections/CellCollection.h"
#include "Spire/Doc/Fields/TextRange.h"
#include "Spire/Doc/Formatting/CharacterFormat.h"
#include "Spire/Doc/Formatting/CellFormat.h"
#include "Spire/Doc/Fields/Shapes/Shading.h"
#include "Spire/Doc/common/h/Color.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Common;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;
using namespace Spire::Doc::Formatting;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");

    //Build the implementation phase table
    intrusive_ptr<Table> table = new Table(document, true);
    table->ResetCells(4, 3);
    const char* headers[3] = {"Implementation Phase", "Planned Duration", "Key Deliverables"};
    for (int c = 0; c < 3; c++)
    {
        intrusive_ptr<TableCell> cell = table->GetRows()->GetItem(0)->GetCells()->GetItem(c);
        intrusive_ptr<Paragraph> paragraph = cell->AddParagraph();
        paragraph->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Center);
        intrusive_ptr<TextRange> range = paragraph->AppendText(headers[c]);
        range->GetCharacterFormat()->SetBold(true);
        range->GetCharacterFormat()->SetTextColor(Color::GetWhite());
        cell->GetCellFormat()->GetShading()->SetBackgroundPatternColor(
            Color::FromArgbRGB(31, 56, 100));
    }

    const char* rows[3][3] = {
        {"Project Kickoff", "4 weeks", "Requirements Specification"},
        {"System Deployment", "8 weeks", "Deployment and interface integration report"},
        {"Trial Run and Acceptance", "6 weeks", "Trial run records and acceptance confirmation"}};
    for (int r = 0; r < 3; r++)
    {
        for (int c = 0; c < 3; c++)
        {
            intrusive_ptr<TableCell> cell = table->GetRows()->GetItem(r + 1)->GetCells()->GetItem(c);
            intrusive_ptr<Paragraph> paragraph = cell->AddParagraph();
            paragraph->GetFormat()->SetHorizontalAlignment(HorizontalAlignment::Left);
            paragraph->AppendText(rows[r][c]);
        }
    }

    //Insert the table at the ServiceScope bookmark, which places it at the start of Section 2
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("ServiceScope");
    navigator->InsertTable(table);

    //Save the document as docx
    document->SaveToFile("Output/InsertTable.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

After insertion, Section 2 contains, in order, the heading, the implementation phase table, the service scope description, and the appendix line:

Implementation phase table inserted at the ServiceScope bookmark

The Table Position Is Relative to the Bookmark

MoveToBookmark("ServiceScope") moves the locator to the start of the bookmark range, and InsertTable() inserts the table from that position. For a bookmark that covers several paragraphs, the table lands at the start of the range, and the paragraphs within the bookmark shift down in order. When the table needs to follow the bookmark range, use the empty paragraph after the bookmark or the next bookmark as the locator, and then adjust the isStart and isAfter parameters.

Cells Have No Default Paragraph After ResetCells

Table->ResetCells(rows, columns) creates only the row and column structure, and the cells contain no ready-made paragraph. Before filling content, call TableCell->AddParagraph() to add a paragraph and then call Paragraph->AppendText() to write the text. The bold text, white text, and dark blue shading of the header need to be set cell by cell, and the inserted table does not automatically inherit the style of other tables in the template.

Inserting a Table Versus Replacing Bookmark Content

InsertTable() inserts a table at the bookmark position, and the bookmark range and the original body text remain unchanged. ReplaceBookmarkContent(TextBodyPart) replaces the content within the bookmark range with a table. Use insertion when a schedule needs to be appended after a placeholder paragraph, and use replacement when the placeholder paragraph needs to be replaced entirely with a table.

Insert an Image

InsertParagraph() accepts a paragraph object, not a picture object. The example first creates a paragraph in a temporary section, calls Paragraph->AppendPicture() to load the seal image and set its width and height, then inserts the whole paragraph at the SealAnchor bookmark, and finally removes the temporary section.

Operation Method
Locate a bookmark BookmarksNavigator->MoveToBookmark(name, isStart, isAfter)
Create a paragraph that contains the picture Paragraph->AppendPicture(fileName)
Set the picture size DocPicture->SetWidth() / SetHeight()
Insert the paragraph BookmarksNavigator->InsertParagraph(paragraph)
Remove the temporary section SectionCollection->Remove(section)

The detailed steps are as follows.

  • Create a Document object and call LoadFromFile() to load the sample document.
  • Create a BookmarksNavigator object and call MoveToBookmark("SealAnchor", true, true) to locate the position after the start marker.
  • Call Document->AddSection() to create a temporary section, add a paragraph to it, and call AppendPicture() to load the seal image.
  • Call DocPicture->SetWidth() and SetHeight() to set the picture size to 72 points.
  • Call InsertParagraph() to insert the picture paragraph at the bookmark position.
  • Call SectionCollection->Remove() to remove the temporary section.
  • Save the result document with Document->SaveToFile().

The code for inserting an image is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#ifdef LoadImage
#undef LoadImage
#endif
#define LoadImage LoadImageA
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Section.h"
#include "Spire/Doc/Collections/SectionCollection.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/Paragraph.h"
#include "Spire/Doc/Fields/DocPicture.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;
using namespace Spire::Doc::Fields;

int main() {

    //Load the agreement template that contains bookmarks
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");

    //Insert the seal image after the start marker of the SealAnchor bookmark
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("SealAnchor", true, true);

    //Build a paragraph that contains the picture in a temporary section
    intrusive_ptr<Section> temp = document->AddSection();
    intrusive_ptr<Paragraph> paragraph = temp->AddParagraph();
    intrusive_ptr<DocPicture> picture = paragraph->AppendPicture("seal.png");
    picture->SetWidth(72.0f);
    picture->SetHeight(72.0f);
    navigator->InsertParagraph(paragraph);

    //Remove the temporary section used only to build the picture paragraph
    document->GetSections()->Remove(temp);

    //Save the document as docx
    document->SaveToFile("Output/InsertPicture.docx", FileFormat::Docx);
    document->Close();
    return 0;
}

The seal image is inserted at the SealAnchor bookmark of the signature table, below the Party A name:

Seal image inserted at the SealAnchor bookmark

The Picture Must Be Placed in a Paragraph First

InsertParagraph() accepts a paragraph object, not a picture object. The example first creates a paragraph in a temporary section, calls AppendPicture() to load the seal image, sets the width and height to 72 points, and then inserts the whole paragraph at the bookmark position. Calling an insertion method on a picture directly has no corresponding overload.

The Temporary Section Should Be Removed After Insertion

The temporary section in the example is used only to build the paragraph that contains the picture and does not take part in the final layout. After the paragraph is inserted into the target document, call SectionCollection->Remove() to remove the temporary section; otherwise, a blank page is added at the end of the result document. The inserted paragraph belongs to the target document, and removing the temporary section does not affect content that has already been inserted.

Image Size and Position Need to Be Adjusted for the Cell

The example sets the picture width and height to 72 points, which suits the size of the signature table cell. When the picture is too large, the cell grows taller automatically and may push the table onto the next page. When the bookmark is located in a table cell, confirm the cell width and row height before setting the picture size. The example uses true, true for positioning, so the picture is placed after the start marker of SealAnchor; changing the parameters to false, true places the picture after the end marker of the bookmark.

Insert Content from Another Document

BookmarksNavigator->InsertTextBodyPart(part) inserts the paragraphs and tables carried by a TextBodyPart at the bookmark position. The example obtains the entire body from the AddendumBody bookmark of the appendix document ScopeAddendum.docx and inserts it at the AddendumAnchor bookmark of the agreement template.

Operation Method
Locate a bookmark in the source document BookmarksNavigator->MoveToBookmark(name)
Obtain the source bookmark content BookmarksNavigator->GetBookmarkContent()
Locate a bookmark in the target document BookmarksNavigator->MoveToBookmark(name)
Insert body content BookmarksNavigator->InsertTextBodyPart(part)

The detailed steps are as follows.

  • Create two Document objects and load the agreement template and the appendix document respectively.
  • Create a BookmarksNavigator object in the appendix document, and call MoveToBookmark("AddendumBody") and GetBookmarkContent() to obtain the appendix body.
  • Create a BookmarksNavigator object in the agreement template, and call MoveToBookmark("AddendumAnchor") to locate the appendix line.
  • Call InsertTextBodyPart() to insert the appendix body at the bookmark position.
  • Save the result document with Document->SaveToFile().

The code for inserting content from another document is shown below.

#include <iostream>
#include <string>
#include "Spire/Doc/pch.h"
#ifdef DocumentProperties
#undef DocumentProperties
#endif
#define DocumentProperties DocumentPropertiesA
#include "Spire/Doc/Document.h"
#include "Spire/Doc/Documents/BookmarksNavigator.h"
#include "Spire/Doc/Documents/TextBodyPart.h"
#include "Spire/Doc/Collections/BodyRegionCollection.h"
#include "Spire/Doc/FileFormat.h"
using namespace std;
using namespace Spire::Doc;
using namespace Spire::Doc::Collections;
using namespace Spire::Doc::Documents;

int main() {

    //Load the agreement template and the addendum document
    intrusive_ptr<Document> document = new Document();
    document->LoadFromFile("ServiceAgreement.docx");
    intrusive_ptr<Document> addendum = new Document();
    addendum->LoadFromFile("ScopeAddendum.docx");

    //Obtain the body content of the addendum
    intrusive_ptr<BookmarksNavigator> addendumNav = new BookmarksNavigator(addendum);
    addendumNav->MoveToBookmark("AddendumBody");
    intrusive_ptr<TextBodyPart> part = addendumNav->GetBookmarkContent();
    cout << "Addendum body item count: " << part->GetBodyItems()->GetCount() << endl;

    //Insert the addendum content at the AddendumAnchor bookmark
    intrusive_ptr<BookmarksNavigator> navigator = new BookmarksNavigator(document);
    navigator->MoveToBookmark("AddendumAnchor");
    navigator->InsertTextBodyPart(part);

    //Save the document as docx
    document->SaveToFile("Output/InsertDocument.docx", FileFormat::Docx);
    document->Close();
    addendum->Close();
    return 0;
}

The bookmark in the appendix document covers the title, information strip, note box, two body paragraphs, and a four-row, three-column table, for a total of 15 body objects. The console output is as follows:

Addendum body item count: 15

Content inserted at the AddendumAnchor bookmark retains the title area, information strip, and note box of the appendix document, and the original appendix line remains before the inserted content:

Addendum body inserted at the AddendumAnchor bookmark

The Source Document Needs a Bookmark That Covers the Whole Block

GetBookmarkContent() returns only the body objects within the bookmark range. The example creates the AddendumBody bookmark in the appendix document in advance to cover the entire body, so the title, information strip, note box, body paragraphs, and table are obtained in one call. When the source document has no ready-made bookmark, call AppendBookmarkStart() and AppendBookmarkEnd() to enclose the target content first, or extract paragraphs and tables one by one and insert them separately.

Cross-Document Insertion Retains Source Formatting

InsertTextBodyPart() writes the objects in the TextBodyPart into the target document, and paragraph formatting and character formatting are inserted along with the content. In the example, the appendix title, the shading of the information strip, and the table column widths match the source document. When the page width of the target document differs from that of the source document, the table may need its column widths adjusted, and the indentation of the title and the note box may need to be set again.

Relationship Between Inserted Content and the Bookmark Position

InsertTextBodyPart() inserts content at the bookmark locator, and the bookmark range and the original text remain unchanged. The example inserts the appendix body at the start of the AddendumAnchor bookmark, so the appendix content follows the sentence "Appendix: Supplementary Notes on Service Scope (attached separately)." When the appendix content needs to start on a new page after the bookmark, set a page break in the inserted content, or adjust the page break property of the paragraphs after insertion.

Get a Free License

If you want to remove the evaluation message from the generated documents, or to get rid of the function limitations, please apply for a 30-day temporary license.

Export data to Excel in C# with Spire.XLS: source data, workbook, formatted XLSX

An export starts from one of five places: a DataTable built in code, a SQL query, a List<T>, a DataSet, or the grid a user is looking at. All five end at the same method — Worksheet.InsertDataTable — and the real work is getting each source into that shape without losing its types along the way.

This guide covers the full distance with Spire.XLS for .NET, a library that writes XLSX files without Microsoft Excel or Office Interop installed. The examples follow one logistics ledger: a shipment table, the SQL Server query behind it, a carrier list, a returns table, and a grid bound to the same rows. The layout is deliberate — sections 4 through 8 build the workbook, section 9 polishes it, section 10 keeps it standing under large result sets, and section 11 hands it to the user.

Quick Navigation

  1. Which Export Path Fits Your Data
  2. Why Not Excel Interop
  3. Set Up the Project
  4. Export a DataTable to Excel in C#
  5. Export Database Data to Excel in C#
  6. Export a List to Excel in C#
  7. Export a DataSet to Multiple Worksheets
  8. Export DataGridView and GridView Data
  9. Format the Exported Worksheet
  10. Keep Data Types and Handle Large Exports
  11. Serve the Export from ASP.NET Core
  12. Frequently Asked Questions
  13. Summary

1. Which Export Path Fits Your Data

The source object decides how much conversion happens before the insert. InsertDataTable accepts a DataTable, so every other source is a small transformation into that shape:

Source Convert to Main call Output
DataTable Nothing Worksheet.InsertDataTable() One worksheet
SQL query / DbDataReader DataTable DataAdapter.Fill(), then InsertDataTable() One worksheet
List<T> DataTable InsertDataTable() after property mapping One worksheet
DataSet Nothing per table InsertDataTable() inside a table loop One worksheet per table
DataGridView / GridView The bound DataTable, or a copy of the rows InsertDataTable() One worksheet
Any of the above, for a download MemoryStream Workbook.SaveToStream() Browser download

Two facts about InsertDataTable carry through every section below. Header text comes from DataColumn.ColumnName or the property name. Cell types come from the column's DataType: a column typed as string stays text in Excel even when every value looks like a number. That is exactly what you want for product codes and postal codes, and it is also the usual reason dates and amounts arrive as text — the column type was wrong at the source.


2. Why Not Excel Interop

Search for this topic and one of the top results is a Microsoft article from 2005 that automates Excel through COM Interop. It answered the question twenty years ago. Today the same approach breaks in the environments where C# code actually runs: web servers, Windows services, build agents, Linux containers.

Interop drives the Excel application itself. The code starts Excel, opens a workbook, writes cells one COM call at a time, then quits the application. Every step assumes a machine with Office installed and an interactive desktop session a user could log into. Microsoft's own guidance, "Considerations for server-side automation of Office", states that Office was never designed for unattended server use. Application pools recycle, desktop sessions disappear, and the EXCEL.EXE processes your code started keep running with nobody left to close them. On a Linux container there is no Excel to start, so the code fails before it writes a single cell.

A library that writes the XLSX file format directly takes the application out of the picture. Spire.XLS builds the package itself, so nothing needs Excel installed, there are no COM references to release, and the same code runs on Windows, Linux, and macOS:

Excel Interop Spire.XLS
Excel installed on the machine Required Not required
Interactive desktop session Required Not required
Windows service / IIS app pool Unsupported by Microsoft Supported
Linux / macOS containers Not available Supported
Cleanup Release every COM object, or EXCEL.EXE processes leak Dispose the Workbook
Writing rows One COM call per cell One bulk insert per block

The rest of this guide uses Spire.XLS for those reasons. If you maintain existing Interop code, the migration is mechanical: the per-cell write loops become single InsertDataTable calls, and the application lifecycle code goes away entirely.


3. Set Up the Project

Install the package:

Install-Package Spire.XLS

Add the namespace to the file that builds the workbook:

using Spire.Xls;

The library targets .NET Framework 4.6.2 and later, .NET Core, and .NET 5 through .NET 10, and runs on Windows, Linux, and macOS servers. Nothing in this guide references Microsoft.Office.Interop.Excel or asks for an Office installation.


4. Export a DataTable to Excel in C#

A DataTable is already the shape InsertDataTable expects, which makes it the baseline every other section builds on. The method takes the table, a flag for column headers, the starting row and column, and a flag that converts column types to Excel cell types.

using System;
using System.Data;
using Spire.Xls;

class Program
{
    static void Main()
    {
        DataTable shipments = BuildShipments();

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");

        // Headers on, start at A1, convert DataTable types to Excel types
        sheet.InsertDataTable(shipments, true, 1, 1, true);

        sheet.AllocatedRange.AutoFitColumns();
        workbook.SaveToFile("shipments.xlsx", FileFormat.Version2016);
    }

    static DataTable BuildShipments()
    {
        DataTable table = new DataTable("Shipments");
        table.Columns.Add("Shipment ID", typeof(int));
        table.Columns.Add("Destination", typeof(string));
        table.Columns.Add("Shipped On", typeof(DateTime));
        table.Columns.Add("Weight (kg)", typeof(double));
        table.Columns.Add("Freight Cost", typeof(decimal));
        table.Columns.Add("Delivered", typeof(bool));

        table.Rows.Add(4812, "Rotterdam", new DateTime(2026, 9, 3), 1240.5, 3180.00m, true);
        table.Rows.Add(4813, "Hamburg", new DateTime(2026, 9, 4), 860.0, 2145.50m, true);
        table.Rows.Add(4814, "Lyon", new DateTime(2026, 9, 7), 2750.25, 5960.75m, false);
        table.Rows.Add(4815, "Gdańsk", new DateTime(2026, 9, 8), 415.75, 980.00m, false);

        return table;
    }
}

The saved workbook holds one sheet named Shipments, with the six headers in row 1 and eight data rows below them. Numeric columns arrive as numbers, the DateTime column as dates, and Delivered as TRUE/FALSE. AutoFitColumns() sizes each column to its widest value.

A new Workbook opens with three blank worksheets. Worksheets.Clear() removes them before the named sheet is added; without it, the file ships with Sheet2 and Sheet3 sitting next to your data. Clearing first is shorter than deleting the extras afterward, and it keeps the sheet order predictable.

Exported DataTable opened in Excel: headers in row 1, typed columns, fitted widths

InsertDataTable returns the number of rows it wrote. When the source table comes from a query you do not control — the database path in the next section, for instance — that return value is the cheapest way to notice an empty result before your users do.

For the DataTable-only version of this task, see export a DataTable to Excel.


5. Export Database Data to Excel in C#

A database export is a DataTable export with one step in front of it: run the query, fill a DataTable with the result, then reuse the same InsertDataTable call from the previous section. DataAdapter.Fill does the filling. The example below uses Microsoft.Data.SqlClient (Install-Package Microsoft.Data.SqlClient); the same pattern applies to every ADO.NET provider.

using System.Data;
using Microsoft.Data.SqlClient;
using Spire.Xls;

class Program
{
    static void Main()
    {
        DataTable shipments = QueryShipments(
            "Server=.;Database=FreightLedger;Trusted_Connection=True;TrustServerCertificate=True");

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");
        sheet.InsertDataTable(shipments, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        workbook.SaveToFile("shipments.xlsx", FileFormat.Version2016);
    }

    static DataTable QueryShipments(string connectionString)
    {
        using SqlDataAdapter adapter = new SqlDataAdapter(
            "SELECT ShipmentID   AS [Shipment ID], " +
            "       Destination, " +
            "       ShippedOn    AS [Shipped On], " +
            "       WeightKg     AS [Weight (kg)], " +
            "       FreightCost  AS [Freight Cost], " +
            "       Delivered " +
            "FROM dbo.Shipments",
            connectionString);

        DataTable table = new DataTable("Shipments");
        adapter.Fill(table);
        return table;
    }
}

Fill opens the connection when it is closed and closes it again when the query finishes, so the connection string is the only thing the method needs. The using on the adapter disposes what Fill creates along the way.

The SQL Server result and the exported workbook: adapter.Fill feeds InsertDataTable

The column types come from the query result, not from anything you declare: INT arrives as Int32, DECIMAL as Decimal, DATETIME2 as DateTime, BIT as Boolean. With transTypes: true those map straight onto Excel cell types, so dates and amounts behave in the spreadsheet. The aliases in the SELECT list (AS [Shipped On]) control the header text. A computed column keeps whatever type SQL gives it — cast CONCAT results if you want them treated as text.

The pattern is identical for other databases. Swap in NpgsqlDataAdapter for PostgreSQL or MySqlDataAdapter from MySqlConnector; both fill a DataTable the same way, and the export code does not change.

Two cautions scale with the data. First, when a result set can run past a million rows, page on the query side — OFFSET/FETCH or keyset pagination — and write one workbook per page, instead of materializing the whole table in memory. Section 10 covers the sheet limits you are paging against. Second, if you are working in EF Core, await context.Shipments.ToListAsync() hands you a List<Shipment>, and the ToDataTable helper in the next section turns it into the DataTable this path expects.

The reverse direction — loading an existing workbook into a DataTable — is covered in import Excel data into a DataTable.


6. Export a List to Excel in C#

InsertDataTable has no List<T> overload, so the list is projected into a DataTable first. A small generic helper carries over the property names and the property types, and those types are what make the exported dates and amounts behave correctly in Excel.

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using Spire.Xls;

public class Carrier
{
    public int CarrierId { get; set; }
    public string CarrierName { get; set; }
    public string DispatchEmail { get; set; }
    public int FleetSize { get; set; }
    public double OnTimeRate { get; set; }
    public bool Active { get; set; }
}

static class ListExport
{
    public static DataTable ToDataTable<T>(IEnumerable<T> items)
    {
        PropertyInfo[] properties = typeof(T)
            .GetProperties(BindingFlags.Public | BindingFlags.Instance);

        DataTable table = new DataTable(typeof(T).Name);

        foreach (PropertyInfo property in properties)
        {
            Type columnType = Nullable.GetUnderlyingType(property.PropertyType)
                              ?? property.PropertyType;
            table.Columns.Add(property.Name, columnType);
        }

        foreach (T item in items)
        {
            table.Rows.Add(properties
                .Select(property => property.GetValue(item) ?? DBNull.Value)
                .ToArray());
        }

        return table;
    }

    public static void Export(IEnumerable<Carrier> carriers, string path)
    {
        DataTable table = ToDataTable(carriers);

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Carriers");
        sheet.InsertDataTable(table, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        workbook.SaveToFile(path, FileFormat.Version2016);
    }
}

Call ListExport.Export(...) with the list you already have. A row looks like 201 | Nordic Freight Line | [email protected] | 42 | 0.962 | TRUE, with the property names used as headers.

Exported List<Carrier>: property names as headers, a numeric on-time-rate column

The helper handles nullable value types by exporting the underlying type, so decimal? becomes a numeric column instead of an object column. To leave a property out of the file, filter it from the properties array before the loop, or project the list into a separate export type.

For a list you build by hand rather than project, InsertArray writes a two-dimensional array in one call:

object[,] rows =
{
    { 4812, "Rotterdam", new DateTime(2026, 9, 3), 3180.00m },
    { 4813, "Hamburg",   new DateTime(2026, 9, 4), 2145.50m }
};

workbook.Worksheets.Clear();
Worksheet sheet = workbook.Worksheets.Add("Manual Rows");
sheet.InsertArray(rows, 2, 1);
sheet.Range[1, 1].Text = "Shipment ID";
sheet.Range[1, 2].Text = "Destination";
sheet.Range[1, 3].Text = "Shipped On";
sheet.Range[1, 4].Text = "Freight Cost";

InsertArray(rows, 2, 1) starts at row 2 so the header line stays free. This path suits fixed reports where the columns are known at compile time.

For more on this single source, see export a List to Excel in C#.


7. Export a DataSet to Multiple Worksheets

A DataSet is a collection of DataTable objects, so one worksheet per table is a loop. A DataSet often arrives straight from a database — one adapter can fill several tables in a single Fill call, as in section 5 — and the loop below handles it the same way regardless of where the tables came from.

using System.Data;
using Spire.Xls;

static void ExportDataSet(DataSet ledger, string path)
{
    Workbook workbook = new Workbook();
    workbook.Worksheets.Clear();

    foreach (DataTable table in ledger.Tables)
    {
        Worksheet sheet = workbook.Worksheets.Add(table.TableName);
        sheet.InsertDataTable(table, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();
    }

    workbook.SaveToFile(path, FileFormat.Version2016);
}

With a DataSet named FreightLedger that holds Shipments and Returns, the result is a two-sheet workbook: Shipments and Returns. Each sheet repeats its own header row, and the two tables keep independent column sets.

DataSet export: one worksheet per DataTable, sheet tabs named after TableName

Excel restricts sheet names to 31 characters and rejects the characters : \ / ? * [ ]. TableName often comes from a query or a user, so normalize it before Worksheets.Add:

static string SafeSheetName(string name)
{
    foreach (char c in new[] { ':', '\\', '/', '?', '*', '[', ']' })
        name = name.Replace(c, '_');

    return name.Length > 31 ? name.Substring(0, 31) : name;
}

Duplicate names also fail. If two tables share a name, append an index before adding the sheet.


8. Export DataGridView and GridView Data

A grid is a view over data you already have. When it is bound to a DataTable, export that table and let the grid stay a display concern:

using System;
using System.Data;
using System.Windows.Forms;
using Spire.Xls;

static void ExportBoundGrid(DataGridView grid, string path)
{
    DataTable table = grid.DataSource as DataTable;
    if (table == null)
        throw new InvalidOperationException("Bind the grid to a DataTable before exporting.");

    Workbook workbook = new Workbook();
    workbook.Worksheets.Clear();
    Worksheet sheet = workbook.Worksheets.Add("Grid Export");
    sheet.InsertDataTable(table, true, 1, 1, true);
    workbook.SaveToFile(path, FileFormat.Version2016);
}

The same idea applies to an ASP.NET Web Forms GridView backed by a DataSet or DataTable: export the source table rather than scraping rendered HTML. A grid bound to a list of objects goes through the ToDataTable helper from section 6.

An unbound DataGridView has no table behind it, so the cells have to be copied into a DataTable first. That path, including column types and the new-row check, is covered in export DataGridView to Excel in C#.


9. Format the Exported Worksheet

A raw export is fine for a machine reader. Before the file goes to a person, it needs a header style, number formats, and a frozen header row. Apply all three after the data is inserted, so the ranges cover the real last row.

using System.Drawing;
using Spire.Xls;

static void FormatSheet(Workbook workbook, Worksheet sheet, int columnCount)
{
    CellStyle headerStyle = workbook.Styles.Add("ShipmentHeader");
    headerStyle.Font.IsBold = true;
    headerStyle.Font.Size = 12;
    headerStyle.Font.Color = Color.White;
    headerStyle.Color = Color.FromArgb(31, 78, 121);
    headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
    headerStyle.VerticalAlignment = VerticalAlignType.Center;

    sheet.Range[1, 1, 1, columnCount].Style = headerStyle;
    sheet.Rows[0].RowHeight = 22;

    int lastRow = sheet.LastRow;
    sheet.Range[2, 3, lastRow, 3].NumberFormat = "yyyy-mm-dd";
    sheet.Range[2, 4, lastRow, 4].NumberFormat = "#,##0.0";
    sheet.Range[2, 5, lastRow, 5].NumberFormat = "#,##0.00";

    sheet.FreezePanes(2, 1);
    sheet.AllocatedRange.AutoFitColumns();
}

The style is registered once through workbook.Styles.Add and assigned to the header range in a single call. FreezePanes(2, 1) keeps row 1 visible while the reader scrolls, and the three NumberFormat assignments give the date and money columns a display format without changing their stored values.

Formatted shipment sheet: styled header, date and currency formats, frozen header row

Number formats are display rules, not type conversions. A decimal column written with #,##0.00 still holds the full value, and Excel can sum it. Text that was stored as a string stays left-aligned no matter which format you apply.

Fonts, colors, borders, and conditional styles are covered in Format Excel Files in C#.


10. Keep Data Types and Handle Large Exports

Three details decide whether a large export arrives usable: the type conversion flag, the sheet limit, and the way rows are written.

Pass transTypes: true. The fifth argument of InsertDataTable converts DataTable column types to Excel cell types. With false, numeric and date columns can land as text. The overload is InsertDataTable(dataTable, columnHeaders, firstRow, firstColumn, transTypes).

Respect the sheet limit. An XLSX worksheet holds 1,048,576 rows and 16,384 columns. A query that returns more rows needs splitting:

const int RowsPerSheet = 1_000_000;

int sheetIndex = 0;
for (int offset = 0; offset < table.Rows.Count; offset += RowsPerSheet)
{
    DataTable slice = table.Clone();
    for (int i = offset; i < Math.Min(offset + RowsPerSheet, table.Rows.Count); i++)
        slice.ImportRow(table.Rows[i]);

    Worksheet sheet = workbook.Worksheets.Add($"Part {++sheetIndex}");
    sheet.InsertDataTable(slice, true, 1, 1, true);
}

Clone() copies the schema without the rows, and ImportRow keeps the column types. The header row repeats on each sheet, which keeps every part readable on its own.

When the source is a database, do this splitting at the query — OFFSET/FETCH per page, as shown in section 5 — rather than materializing the full result set and slicing it in memory. The loop above is for tables you already have in hand.

Write rows in bulk. InsertDataTable and InsertArray cross into the worksheet once per block; assigning each cell through Range crosses once per cell. In a local test with Spire.XLS 16.10.3 on .NET 10, building and saving a 100,000-row, six-column workbook took about 2.5 seconds through InsertDataTable and about 4 seconds through per-cell assignments, which also stored every value as text. For sheets that large, prefer fixed widths (sheet.Columns[i].ColumnWidth = 18) over AutoFitColumns(); autofit has to inspect every cell in the used range to size each column.


11. Serve the Export from ASP.NET Core

Everything so far produced a file on disk. In a web application the export usually ends as a browser download, and the workbook should never touch disk on the way. This section turns the export into a service: one interface, a DI registration, an authorized controller endpoint, and a Minimal API variant that reuses the same service.

The service owns the query and the workbook build. The data source is the database query from section 5, so the web path and the console path share one shape:

using System.Data;
using Microsoft.Data.SqlClient;
using Spire.Xls;

public interface IShipmentExportService
{
    Workbook Build();
}

public class ShipmentExportService : IShipmentExportService
{
    private const string ShipmentsSql =
        "SELECT ShipmentID  AS [Shipment ID], " +
        "       Destination, " +
        "       ShippedOn   AS [Shipped On], " +
        "       WeightKg    AS [Weight (kg)], " +
        "       FreightCost AS [Freight Cost], " +
        "       Delivered " +
        "FROM dbo.Shipments";

    private readonly string _connectionString;
    private readonly ILogger<ShipmentExportService> _logger;

    public ShipmentExportService(IConfiguration configuration,
        ILogger<ShipmentExportService> logger)
    {
        _connectionString = configuration.GetConnectionString("FreightLedger")
            ?? throw new InvalidOperationException(
                "Connection string 'FreightLedger' is not configured.");
        _logger = logger;
    }

    public Workbook Build()
    {
        using SqlConnection connection = new SqlConnection(_connectionString);
        using SqlDataAdapter adapter = new SqlDataAdapter(ShipmentsSql, connection);

        DataTable shipments = new DataTable("Shipments");
        adapter.Fill(shipments);

        Workbook workbook = new Workbook();
        workbook.Worksheets.Clear();
        Worksheet sheet = workbook.Worksheets.Add("Shipments");

        int rows = sheet.InsertDataTable(shipments, true, 1, 1, true);
        sheet.AllocatedRange.AutoFitColumns();

        _logger.LogInformation("Shipment export wrote {RowCount} rows.", rows);
        return workbook;
    }
}

The query runs synchronously because DataAdapter.Fill has no async overload. If a large result set should not block the request thread, read it with await command.ExecuteReaderAsync() into a DataTable instead — the workbook part stays the same.

Register it as scoped:

builder.Services.AddScoped<IShipmentExportService, ShipmentExportService>();

The controller stays thin — build, save to a MemoryStream, return the bytes:

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Spire.Xls;

[ApiController]
[Route("api/shipments")]
public class ShipmentExportController : ControllerBase
{
    private readonly IShipmentExportService _exportService;

    public ShipmentExportController(IShipmentExportService exportService)
    {
        _exportService = exportService;
    }

    [HttpGet("export")]
    [Authorize]
    public IActionResult Export()
    {
        Workbook workbook = _exportService.Build();

        using MemoryStream stream = new MemoryStream();
        workbook.SaveToStream(stream, FileFormat.Version2016);

        return File(
            stream.ToArray(),
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            "shipments.xlsx");
    }
}

A Minimal API route reuses the same service without the controller class:

app.MapGet("/api/shipments/export", (IShipmentExportService exportService) =>
{
    Workbook workbook = exportService.Build();

    MemoryStream stream = new MemoryStream();
    workbook.SaveToStream(stream, FileFormat.Version2016);
    stream.Position = 0;

    return Results.File(
        stream,
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
        "shipments.xlsx");
})
.RequireAuthorization();

Four decisions in this code are worth spelling out.

One Workbook per request, never a singleton. A Workbook is one document held in memory, and it is not thread-safe. A singleton service that kept a Workbook would serialize every request through a single file and leak rows between users. The service above creates the Workbook inside Build, so each request builds its own; the scoped registration matches that lifetime. The FAQ at the end of this guide has a dedicated entry on this, because it is the most common way these exports go wrong.

[Authorize] on the endpoint. An export endpoint returns a full table in one request, which makes it exactly the kind of URL that gets shared around or crawled if it responds anonymously. Require authentication, and if some roles should see fewer columns, shape that in the query or a DTO — the workbook code does not need to know about permissions.

ToArray() versus returning the stream. ToArray() copies the bytes once, which is fine for reports up to a few megabytes and lets the using block dispose the stream early. For large workbooks, skip the copy: save to the stream, set stream.Position = 0, and return File(stream, contentType, fileName) — ASP.NET Core writes it to the response and disposes the stream afterward. The Minimal API variant above shows that form.

Log the row count. InsertDataTable returns the rows it wrote, and the service logs it. When the query returns nothing — a filtered date range with no matches, a connection that fell back to an empty schema — the log tells you before a user opens an empty file and files a report of their own.

The response headers are the part users notice when something is wrong. The file name in the third argument of File() sets Content-Disposition, and the MIME type above is the one Excel and browsers expect for .xlsx. A text/csv type with an .xlsx extension produces a download that opens with a warning.

When the deliverable is a PDF report rather than a workbook, the same worksheet saves straight to PDF — see Convert Worksheet to PDF in C#.


12. Frequently Asked Questions

How do I export a DataTable to Excel in C#?

Create a Workbook, clear its default sheets, add one with Worksheets.Add("Shipments"), and call InsertDataTable(table, true, 1, 1, true). Save with SaveToFile(path, FileFormat.Version2016). The four positional arguments after the table mean headers on, start at row 1, start at column 1, and convert column types.

How do I export SQL query results to Excel in C#?

Fill a DataTable from the query with a DataAdapter — adapter.Fill(table) — then pass the table to InsertDataTable. Section 5 shows the full path, including where the column types come from, how the connection gets released, and how to page large result sets at the query level.

How do I export to Excel without Excel installed?

Use a library that writes the XLSX package directly. Section 2 covers why Interop needs Excel and a desktop session; Spire.XLS uses neither, so the same code runs in a console app, a Windows service, an ASP.NET Core request, a build agent, a Linux container, and Azure App Service.

Why are my dates and numbers stored as text?

The DataTable column type is usually string, because the values came from a CSV import or a SELECT that returned text. Excel stores what the column type says. Declare the column as typeof(DateTime) or typeof(decimal), or cast the values before adding the row. After insertion, a NumberFormat changes only the display, not the stored type.

Why does my exported workbook contain blank Sheet2 and Sheet3?

A new Workbook starts with three worksheets. You renamed or wrote into the first one and left the other two in place. Call workbook.Worksheets.Clear() before adding your own sheet, or remove the extras with workbook.Worksheets[1].Remove() while the count is greater than one.

Can I export to Excel in C# on Linux?

Yes. The code in this guide uses no COM and no Windows-only API. Spire.XLS for .NET writes the XLSX package itself, so the same code runs in a Linux container, on a build agent, and in Azure App Service.

How do I export multiple tables to one workbook?

Loop over the tables, add a worksheet for each one, and call InsertDataTable on that sheet. workbook.Worksheets.Clear() removes the default sheet first. Use TableName for the sheet name after replacing the characters Excel rejects.

How do I export only selected columns?

Build a DataView with the columns you want and export view.ToTable():

DataTable subset = new DataView(shipments).ToTable(false, "Shipment ID", "Destination", "Freight Cost");
sheet.InsertDataTable(subset, true, 1, 1, true);

The false argument means distinct rows are not required. The column list keeps the original order.

How do I keep leading zeros in codes?

Make the column type string, so 00731 stays 00731. A numeric column cannot keep the leading zero: the value is parsed as 731, and a NumberFormat only changes how that number is displayed. String columns are the reliable option for postal codes, SKUs, and account numbers.

Can I register the Workbook as a singleton in ASP.NET Core?

No. A Workbook holds one document in memory and is not thread-safe, so a shared instance would mix rows from concurrent requests. Register the export service as scoped and create a new Workbook per request, as section 11 does.

Can I export to XLS instead of XLSX?

Yes. Pass FileFormat.Version97to2003 to SaveToFile. The legacy XLS format caps a worksheet at 65,536 rows and offers fewer style options, so keep XLSX unless a downstream system requires the older format.


13. Summary

Every path in this guide converges on one method. A DataTable goes into InsertDataTable as it is. A database query fills a DataTable first, with the column types supplied by the query itself. A List<T> is projected through property mapping. A DataSet becomes one worksheet per table. A grid exports the table it is bound to.

Delivery has two exits. SaveToFile writes a file to disk; SaveToStream feeds everything else — an ASP.NET Core download, an email attachment, a blob upload. Wrapping the build in a scoped service keeps the controller thin and gives the same code to a Minimal API route or a background job, with authentication and a row-count log line as the standard trimmings.

The production details hold regardless of source: pass transTypes: true, keep each sheet under 1,048,576 rows, write blocks of rows instead of individual cells, and apply formatting after the data so the ranges match what was actually written.

For commercial use of the advanced capabilities, you can request a free temporary license to evaluate the full build; the evaluation build adds a warning worksheet to saved workbooks.

Page 3 of 387
page 3