Export a report to Word, Excel, CSV and text
The DocWright.Reporting.Export package writes a paginated report to four formats. All of them start from the same ReportPageModel that PDF and PNG are drawn from, so run and paginate once, then export as many times as you like.
<PackageReference Include="DocWright.Reporting.Export" Version="1.*" />
This guide continues from Paginate and render a report and uses the same sales.rdl.
All four formats
using DocWright.Reporting.Export;
// One page model, four formats.
using (FileStream docx = File.Create("sales.docx"))
{
ReportDocxExporter.Export(pages, fonts, docx);
}
using (FileStream xlsx = File.Create("sales.xlsx"))
{
ReportXlsxExporter.Export(pages, fonts, xlsx);
}
File.WriteAllText("sales.csv", ReportCsvExporter.ToCsv(pages));
File.WriteAllText("sales.txt", ReportTextExporter.ToText(pages));
Downloads: sales.docx, sales.xlsx.
Output (all output from this page's samples):
flow export: 2 section(s), 0 diagnostic(s)
CSV: 65 records from 2 pages
Region;Store;Amount
Central;20 stores;43,300
;Central store 01;500
;Central store 02;2,600
Text:
Sales: All regions
Region | Store | Amount
Central | 20 stores | 43,300
Central store 01 | 500
Central store 02 | 2,600
1 sheet "Report", 67 rows
level 0: Sales: All regions
level 0: Region | Store | Amount
level 0: Central | 20 stores | 43300 (number)
level 1: | Central store 01 | 500 (number)
level 1: | Central store 02 | 2600 (number)
per page: 2 sheets
Each exporter has an Export(pages, …, stream, options) method. CSV and text also have ToCsv and ToText, which return a string. Word and Excel also have ToDocument and ToWorkbook, which return the model so you can change it before saving.
Word

The default, ReportDocxLayout.Fixed, reproduces each printed page as a grid. Each report page becomes a Word section of the same size, holding a borderless table whose rows and columns come from the positions of the items on the page. This is the same approach as Reporting Services' own Word export, and it's how an absolutely positioned report survives in a format that has no absolute positioning.
- Each textbox is written as the lines the paginator laid out, one paragraph per line, so Word breaks lines where the PDF does.
- Charts, gauges and barcodes become pictures, drawn by the same renderer as a PNG of the page (
RasterDpi, 150 by default). - Row heights are "at least", not exact, so nothing is ever clipped.
- Page headers and footers are written as ordinary content on each page, not as Word headers, because a report's header can be different on every page ("Page 3 of 9").
- Borders keep their style, written as Reporting Services' own Word renderer writes them: dotted, dashed (
dashSmallGap) and double, at its widths. Word draws no border wider than 12 pt, so a wider one is held there and reported. - Lines are borders of the grid, as Reporting Services writes them: a horizontal line is the top edge of the cells it spans, a vertical one their left edge, and a diagonal one the diagonal of a cell its own size. A line that can't be placed exactly — inside a row of items, or across an item — is reported with
DXP9502.
ReportDocxLayout.Flow writes the text as ordinary flowing paragraphs, for a report someone will rewrite rather than print:
using DocWright;
using DocWright.Core.Diagnostics;
using DocWright.Dom;
using DocWright.Reporting.Export;
// Flow layout: plain paragraphs and tables for a document someone will edit,
// instead of the default fixed grid that reproduces the printed page.
var diagnostics = new CollectingConversionDiagnostics();
var flow = new ReportDocxExportOptions
{
Layout = ReportDocxLayout.Flow,
IncludePageHeadersAndFooters = false,
Diagnostics = diagnostics,
};
// ToDocument returns the WordDocument, so you can edit it before saving.
using WordDocument document = ReportDocxExporter.ToDocument(pages, fonts, flow);
document.Sections[0].Blocks.Insert(0, new Paragraph("Exported for the October board meeting."));
using (FileStream output = File.Create("sales-flow.docx"))
{
new DocWrightConverter().Save(document, output);
}
Console.WriteLine($"flow export: {document.Sections.Count} section(s), {diagnostics.Snapshot().Count} diagnostic(s)");
ReportDocxExportOptions |
Default | |
|---|---|---|
Layout |
Fixed |
Fixed reproduces the printed page. Flow gives editable paragraphs. |
RasterDpi |
150 | Resolution of charts, gauges and custom items, from 32 to 600. |
IncludePageHeadersAndFooters |
true |
|
IncludeImages |
true |
|
Diagnostics, StrictMode |
— | Report what couldn't be carried, or throw instead. A line in Flow layout, for example, is DXP9502: flow layout writes no lines. |
CSV
using DocWright.Reporting.Export;
// Every region, over several pages: each table row is one record, once.
string csv = ReportCsvExporter.ToCsv(pages, new ReportCsvExportOptions
{
FieldDelimiter = ";",
IncludeItemsOutsideDataRegions = false, // true adds titles and other free-standing text
});
string[] records = csv.Split((char)10).Select(r => r.TrimEnd((char)13)).Where(r => r.Length > 0).ToArray();
Console.WriteLine($"CSV: {records.Length} records from {pages.Pages.Count} pages");
foreach (string line in records.Take(4))
{
Console.WriteLine(" " + line);
}
CSV contains the data, not the page. Each table becomes a block of records whose columns are the table's columns. A row split by a page break, or a header repeated on a later page, is written only once, and rows from different pages are never merged into one record. Page headers and footers are never written. Quoting follows RFC 4180. A byte-order mark is written by default, because spreadsheet programs often misread UTF-8 without one.
ReportCsvExportOptions |
Default |
|---|---|
FieldDelimiter, RecordDelimiter, Qualifier |
, · \r\n · " |
IncludeItemsOutsideDataRegions |
false. Set it to true to include titles and other text outside tables. |
WriteByteOrderMark |
true |
Plain text
using DocWright.Reporting.Export;
string text = ReportTextExporter.ToText(pages, new ReportTextExportOptions
{
IncludePageHeadersAndFooters = false,
LineEnding = "\n",
ColumnSeparator = " | ",
PageSeparator = "\n----\n",
});
Console.WriteLine("Text:");
foreach (string line in text.Split('\n').Take(5))
{
Console.WriteLine(" " + line);
}
The text of every textbox in reading order, one block per page. Text in the same horizontal band, such as a table row, goes on one line, separated by ColumnSeparator. Line endings and separators are always the ones you set, never the machine's, so the same report gives the same bytes everywhere. Unlike CSV, page headers and footers are included by default.
Excel
using DocWright.Fonts;
using DocWright.Formats.Xlsx;
using DocWright.Reporting.Export;
// ToWorkbook returns the workbook model: inspect it, add to it, then write it.
XlsxWorkbook book = ReportXlsxExporter.ToWorkbook(pages, fonts);
XlsxWorksheet sheet = book.Worksheets[0];
Console.WriteLine($"{book.Worksheets.Count} sheet \"{sheet.Name}\", {sheet.Rows.Count} rows");
// Numbers stay numbers, so the column sums. Toggles become the row outline.
foreach (XlsxRow row in sheet.Rows.Take(5))
{
string cells = string.Join(" | ", row.Cells.Select(c =>
c.Value.Kind == XlsxCellValueKind.Number ? $"{c.Value.NumberValue} (number)" : c.Value.TextValue));
Console.WriteLine($" level {row.OutlineLevel}: {cells}");
}
var notes = new XlsxWorksheet("Notes");
var first = new XlsxRow(1);
first.Cells.Add(new XlsxCell(1, XlsxCellValue.Text("Exported from sales.rdl")));
notes.Rows.Add(first);
book.Worksheets.Add(notes);
using (FileStream output = File.Create("sales-with-notes.xlsx"))
{
XlsxWriter.Write(book, output);
}
// One sheet per page instead of one for the whole report.
XlsxWorkbook perPage = ReportXlsxExporter.ToWorkbook(pages, fonts, new ReportXlsxExportOptions
{
Sheets = ReportXlsxSheets.PerPage,
ShowGridLines = true,
});
Console.WriteLine($"per page: {perPage.Worksheets.Count} sheets");
- Numbers stay numbers. A textbox whose value is a number becomes a numeric cell, with the report's format converted to an Excel number format. It looks the same as in the report, and the column can be summed. A format with no Excel equivalent is dropped, leaving the plain number, and reported as
DXP9502. Showing a different number would be worse. - One sheet for the whole report by default, as Reporting Services does.
ReportXlsxSheets.PerPagegives one sheet per page instead, named from the page name if the report sets one. - The grid is rebuilt from positions. Rows are the horizontal bands that items fall into, and columns are the distinct left and right edges of the items, so no cell holds two items.
- Drill-down toggles become Excel's row outline (the level shown in the output), with summary rows above their details. Groups without a toggle don't add outline levels. Excel allows seven levels.
- Page headers and footers are left out by default, unlike Reporting Services, because a header repeated on every page would become a band of text through the middle of the data. Set
IncludePageHeadersAndFootersto include them. - Charts, gauges and barcodes are anchored pictures (
RasterDpi, 96 by default). Grid lines are hidden unlessShowGridLinesis set.
A collapsed toggle
A page model holds what a reader sees, so a group whose toggle is collapsed has no detail rows in it, and by default the workbook has none either. Reporting Services writes those rows into the sheet hidden, so Excel's outline buttons can bring them back. To do the same, paginate the workbook's page model with IncludeToggleHiddenRows:
using DocWright.Formats.Xlsx;
using DocWright.Reporting.Export;
using DocWright.Reporting.Pagination;
// Collapse Central by clicking its toggle, as a viewer would.
string centralKey = pages.Pages.SelectMany(p => p.Items).SelectMany(Flatten).OfType<ReportPageTextbox>()
.First(t => t.Toggle is not null && t.Value == "Central").Toggle!.Key;
// For the workbook, ask for the rows a collapsed toggle hides: they are written hidden,
// so Excel's outline buttons bring them back, as Reporting Services does.
var forExcel = new ReportPaginationOptions { IncludeToggleHiddenRows = true };
forExcel.ToggledItems.Add(centralKey);
XlsxWorksheet sheet = ReportXlsxExporter.ToWorkbook(ReportPaginator.Paginate(instance, fonts, forExcel), fonts).Worksheets[0];
foreach (XlsxRow row in sheet.Rows.Skip(2).Take(3))
{
string cells = string.Join(" | ", row.Cells.Select(c =>
c.Value.Kind == XlsxCellValueKind.Number ? $"{c.Value.NumberValue} (number)" : c.Value.TextValue));
Console.WriteLine($" level {row.OutlineLevel}{(row.Hidden ? ", hidden" : "")}: {cells}");
}
Console.WriteLine($"hidden rows: {sheet.Rows.Count(r => r.Hidden)} of {sheet.Rows.Count}");
level 0: Central | 20 stores | 43300 (number)
level 1, hidden: | Central store 01 | 500 (number)
level 1, hidden: | Central store 02 | 2600 (number)
hidden rows: 20 of 67
The hidden rows are laid out as if shown, each item in them has HiddenByToggle set, and the export writes them with hidden and collapsed at their outline level.
Important
Use that page model for Excel only. Every other output (PDF, images, the viewer, DOCX, CSV, text) draws the flagged rows as if they were shown. If you produce both pages and a workbook, paginate twice: pagination is stateless, and the same instance can be paginated as often as you need.
Only rows that a toggle could show are carried. A member that is hidden with no ToggleItem stays out, and so do columns that a collapsed toggle hides.
ToWorkbook returns an XlsxWorkbook, the model used by DocWright.Formats.Xlsx. Add sheets, change widths or freeze panes, then write it with XlsxWriter.Write.
Next steps
- Write Excel files for the workbook model.
- Run an SSRS report and export it: Microsoft's Regional Sales report from start to finish.