Put data into a sheet and read it back
ImportData writes a DataTable, a DataView, any IEnumerable<T> or a two-dimensional array into a sheet at a cell, as typed cells. ExportDataTable, FillDataTable, ExportObjects<T> and ExportArray read a range back. They work on a workbook you opened and on one you started from nothing.
dotnet add package DocWright.Spreadsheet
Import a list
The types used on this page:
using System.Data;
using DocWright.Core.Primitives;
using DocWright.Spreadsheet;
public sealed class SheetOrder
{
public int Id { get; set; }
public string Customer { get; set; } = string.Empty;
public decimal Total { get; set; }
public DateTime Placed { get; set; }
public bool Paid { get; set; }
}
// What a row is read back into: the property names are the headings of the sheet.
public sealed class SheetOrderRow
{
public int Order { get; set; }
public string? Customer { get; set; }
public decimal Total { get; set; }
public DateTime Placed { get; set; }
public bool Paid { get; set; }
}
using DocWright.Core.Primitives;
using DocWright.Spreadsheet;
var orders = new List<SheetOrder>
{
new SheetOrder { Id = 1001, Customer = "Mere Tane", Total = 129.5m, Placed = new DateTime(2026, 11, 17), Paid = true },
new SheetOrder { Id = 1002, Customer = "=cmd|' /C calc'!A0", Total = 48m, Placed = new DateTime(2026, 11, 18), Paid = false },
new SheetOrder { Id = 1003, Customer = "0012", Total = 1250.75m, Placed = new DateTime(2026, 11, 19), Paid = true },
};
XlsxDocument book = XlsxDocument.Create();
XlsxDocumentSheet sheet = book.Sheets[0];
var options = new XlsxImportOptions
{
HeaderStyle = book.DefaultStyle.With(bold: true, backgroundColor: ColorRgb.FromRgb(221, 235, 247)),
};
options.Columns.Add(new XlsxImportColumn("Id") { Header = "Order" });
options.Columns.Add(new XlsxImportColumn("Customer"));
options.Columns.Add(new XlsxImportColumn("Total") { NumberFormat = "#,##0.00" });
options.Columns.Add(new XlsxImportColumn("Placed"));
options.Columns.Add(new XlsxImportColumn("Paid"));
XlsxCellRange? written = sheet.ImportData(orders, 1, 1, options); // row 1, column 1
Console.WriteLine($"written: rows {written!.Value.FirstRow} to {written.Value.LastRow}, columns {written.Value.FirstColumn} to {written.Value.LastColumn}");
Console.WriteLine($"B3 is {sheet.GetCell("B3").Value.Kind}: {sheet.GetCell("B3").Value.TextValue} (formula: {sheet.GetCell("B3").Formula ?? "none"})");
Console.WriteLine($"B4 is {sheet.GetCell("B4").Value.Kind}: {sheet.GetCell("B4").Value.TextValue}");
Console.WriteLine($"D2 shows as {sheet.GetCell("D2").NumberFormat}, C2 as {sheet.GetCell("C2").NumberFormat}");
sheet.SetColumnWidth(2, 24m);
File.WriteAllBytes("orders-import.xlsx", book.ToArray());
It prints the first four lines below; the rest come from the samples further down this page.
written: rows 1 to 4, columns 1 to 5
B3 is Text: =cmd|' /C calc'!A0 (formula: none)
B4 is Text: 0012
D2 shows as yyyy-mm-dd, C2 as #,##0.00
table: Order:Decimal, Customer:String, Total:Decimal, Placed:DateTime, Paid:Boolean; 3 rows
objects: 3; first: 1001 Mere Tane 129.5 2026-11-17 True
array: 3 x 3; [2,2] = 1250.75 (Decimal)
issue at A3: the cell holds the text 'n/a', which is not a number (property Order is Int32)
the order of row 3 is left at 0; row 4's total is 4.5
strict: A3 on 'Sheet1' cannot be exported: the cell holds the text 'n/a', which is not a number (property Order is Int32).
filled 2 rows; Count is Int32: 12, DBNull
Download the result and open it in Excel: orders-import.xlsx.
ImportData returns the range it wrote, header included, or null when there was nothing to write.
Important
A string is always text. =cmd|' /C calc'!A0 goes into the sheet as those characters, not as a formula, and 0012 stays 0012. Excel does the opposite: given the same strings through automation it makes a formula, a number, a date or a boolean of them. An import that did so would run a formula somebody typed into a name field. To write a formula, call SetFormula.
What each value becomes
| .NET value | Cell |
|---|---|
string |
Text, whatever it looks like. More than 32,767 characters is refused. Excel cuts such a text short without saying so. |
null, DBNull |
Nothing. A cell that held a value or a formula is emptied; where nothing was, nothing is written. |
bool |
Boolean. |
sbyte to ulong, decimal |
Number, with every digit kept in the file. Excel itself shows 15 significant digits. |
double |
Number. NaN and the infinities become the error #NUM!. |
float |
The number it stands for: 0.1f is 0.1. |
DateTime, DateTimeOffset, DateOnly |
A date in the workbook's own date system. A DateTimeOffset gives the clock time it states. Shown through DateFormat unless the cell already shows dates. |
TimeSpan |
A number of days, shown as [h]:mm:ss. |
TimeOnly |
A fraction of a day, shown as h:mm:ss. |
Guid, char |
Text. |
| An enum | Its name, as text. |
| Anything else | Refused with an ArgumentException that names the row and the column. |
The four sources
| Source | Columns | Header |
|---|---|---|
DataTable |
Its columns, in order. | The column names. |
DataView |
The columns of its table; the rows the view shows, in the view's order. | The column names. |
IEnumerable<T> |
Each public readable property whose type a cell can hold, in declaration order. A property of another type (a list, a nested object) is left out. A sequence of plain values is one column. | The property names; Value for plain values. |
object?[,] |
The second dimension. | None. IncludeHeader is ignored and Columns must be empty. |
The properties of T are found once per type and kept. They are read through reflection and not through generated code, so the call works under trimming and Native AOT.
Import options
| Option | Default | Meaning |
|---|---|---|
IncludeHeader |
true |
Write the row of headings. |
HeaderStyle |
null |
The look of the header cells. Start it from book.DefaultStyle. |
DateFormat |
yyyy-mm-dd |
The number format a date gets where the cell does not already show dates. null gives none. |
Columns |
empty | Which columns, in what order, each with an optional Header and NumberFormat. A name the source lacks is an ArgumentException. |
MaxRows |
null |
The most data rows to write. A source with more is refused with a ResourceLimitExceededException. It is never cut short. |
Every cell goes through SetValue, so the cells an edit refuses are refused here too: a table's header row, and part of an array formula. Where the number of rows is known beforehand (a table, a view, an array, a collection), what does not fit the worksheet or passes MaxRows is refused before a cell is written. Otherwise the rows already written stay written.
Note
Size. An import is one edit for each cell, held in memory until the workbook is saved. Measured on .NET 10: 100,000 rows of 10 columns import in 0.7 s and hold 130 MB; 1,000,000 rows take 6.5 s and hold about 1.3 GB, and saving them peaks at about 5.2 GB. To write a very large workbook in one go, build an XlsxWorkbook and write it.
Read a range back
using System.Data;
using DocWright.Spreadsheet;
XlsxDocument reopened;
using (FileStream input = File.OpenRead("orders-import.xlsx"))
{
reopened = XlsxDocument.Open(input);
}
XlsxDocumentSheet data = reopened.Sheets[0];
DataTable table = data.ExportDataTable();
Console.WriteLine("table: " + string.Join(", ", table.Columns.Cast<DataColumn>().Select(c => $"{c.ColumnName}:{c.DataType.Name}")) + $"; {table.Rows.Count} rows");
IReadOnlyList<SheetOrderRow> rows = data.ExportObjects<SheetOrderRow>();
Console.WriteLine($"objects: {rows.Count}; first: {rows[0].Order} {rows[0].Customer} {rows[0].Total} {rows[0].Placed:yyyy-MM-dd} {rows[0].Paid}");
object?[,] array = data.ExportArray(new XlsxCellRange(2, 1, 4, 3)); // rows 2 to 4, columns 1 to 3
Console.WriteLine($"array: {array.GetLength(0)} x {array.GetLength(1)}; [2,2] = {array[2, 2]} ({array[2, 2]!.GetType().Name})");
| Method | Gives |
|---|---|
ExportDataTable(range, options) |
A new DataTable whose columns are typed by what they hold: all numbers decimal, all dates DateTime, all booleans bool, all text string, mixed object. An empty cell is DBNull. An empty heading becomes Column and its position; a repeated one gets _2, _3, and so on. |
FillDataTable(table, range, options) |
Rows added to your own table, each cell given as the type of the column its heading names. Returns the number of rows added. |
ExportObjects<T>(range, options) |
One T for each row, each heading's column going to the public settable property of that name, compared without regard to case. Columns may be in any order. |
ExportArray(range, options) |
object?[,], every row of the range included, each cell in its own type; null for an empty cell. |
The range is one-based and inclusive: first row, first column, last row, last column. null means every cell the sheet stores. A formula cell gives the result stored in the file, or the one Calculate gave it (Calculate formulas).
A cell that does not fit is reported, never guessed
using DocWright.Spreadsheet;
data.SetValue("A3", XlsxCellValue.Text("n/a")); // somebody typed text into the Order column
data.SetValue("C4", XlsxCellValue.Number(4.5m));
var export = new XlsxExportOptions();
IReadOnlyList<SheetOrderRow> checkedRows = data.ExportObjects<SheetOrderRow>(null, export);
foreach (XlsxExportIssue issue in export.Issues)
{
Console.WriteLine($"issue at {issue.Reference}: {issue.Message}");
}
Console.WriteLine($"the order of row 3 is left at {checkedRows[1].Order}; row 4's total is {checkedRows[2].Total}");
try
{
data.ExportObjects<SheetOrderRow>(null, new XlsxExportOptions { Strict = true });
}
catch (DocWright.Core.InvalidDocumentException refusal)
{
Console.WriteLine($"strict: {refusal.Message}");
}
Text is not parsed into a number, 4.5 is not rounded into an int, a number too large for the type is not wrapped, and an error value such as #DIV/0! is nothing. Each such cell is listed in Issues with its reference and what was wrong, and becomes null, DBNull or the property left as it was. Strict makes the first one an InvalidDocumentException that names the cell.
What is converted: a number or a boolean into string when text is asked for; a number into any numeric type it fits; a date cell or a number into DateTime, DateTimeOffset or DateOnly; a number of days into TimeSpan or TimeOnly; text into Guid, char or an enum by name; a number into an enum by a value it defines.
Export options
| Option | Default | Meaning |
|---|---|---|
FirstRowIsHeader |
true |
The first row of the range holds the headings. Without it a new table's columns are Column1, Column2, and ExportObjects throws, since a property is found by its heading. |
StopAtEmptyRow |
false |
End at the first row that holds no value. Otherwise an empty row is a row of nothing. |
Strict |
false |
Throw at the first cell that cannot be given. |
MaxCells |
10,000,000 | The most cells a range may cover. A larger one is refused with a ResourceLimitExceededException before a row is read. |
Issues |
The cells the last export could not give. Cleared when an export starts. |
Warning
MaxCells is on by default, and for a reason. A workbook somebody else made can store one cell in A1 and one a million rows below. With no range given, the export covers both, and would build a million rows from a file of a few hundred bytes. Give the range you mean, or set MaxCells = null for a file you trust.
A table keeps its own schema
using System.Data;
using DocWright.Spreadsheet;
var stock = new DataTable("Stock");
stock.Columns.Add("Sku", typeof(string));
stock.Columns.Add("Count", typeof(int));
stock.Columns.Add("Checked", typeof(DateTime));
stock.Rows.Add("A-1", 12, new DateTime(2026, 11, 1));
stock.Rows.Add("B-2", DBNull.Value, new DateTime(2026, 11, 2));
XlsxDocumentSheet stockSheet = book.AddSheet("Stock");
stockSheet.ImportData(stock, 1, 1);
// ExportDataTable would give Count as decimal: a cell holds a number, not an int.
// A table of your own keeps its schema.
DataTable copy = stock.Clone();
int added = stockSheet.FillDataTable(copy);
Console.WriteLine($"filled {added} rows; Count is {copy.Columns["Count"]!.DataType.Name}: {copy.Rows[0]["Count"]}, {(copy.Rows[1]["Count"] is DBNull ? "DBNull" : "a value")}");
Two things to know:
- A
TimeSpanis written under a time format, so read back without being asked for as aTimeSpanit is aDateTime. Fill a table or an object whose column or property isTimeSpanto have the length back. FillDataTableleaves out a row your table refuses (a null in a column that allows none, a key that repeats) and lists it inIssues.
DataTable and DataView come from System.Data, which is part of every framework the package targets. The package still depends on no other package but DocWright.Core.