Table of Contents

A sheet as CSV, JSON or Markdown

A sheet goes out as delimited text, as JSON or as a Markdown table, and delimited text or a Markdown table comes in as a new workbook. The CSV is what Excel's own save writes, byte for byte.

dotnet add package DocWright.Spreadsheet

A sheet as CSV

using DocWright.Spreadsheet;

XlsxDocument book = XlsxDocument.Create();
XlsxDocumentSheet sheet = book.Sheets[0];
sheet.SetValue("A1", XlsxCellValue.Text("Item"));
sheet.SetValue("B1", XlsxCellValue.Text("Price"));
sheet.SetValue("C1", XlsxCellValue.Text("Ordered"));
sheet.SetValue("A2", XlsxCellValue.Text("Pear, green"));
sheet.SetValue("B2", XlsxCellValue.Number(1234.5m));
sheet.SetValue("C2", XlsxCellValue.Date(new DateTime(2026, 11, 17)));
sheet.SetValue("A3", XlsxCellValue.Text("=HYPERLINK(\"http://example.test\")"));
sheet.SetValue("B3", XlsxCellValue.Number(-5m));
sheet.SetStyle("B2", book.DefaultStyle.With(numberFormat: "#,##0.00"));
sheet.SetStyle("C2", book.DefaultStyle.With(numberFormat: "d mmm yyyy"));

using (FileStream file = File.Create("sheet-export.csv"))
{
    sheet.ToCsv(file);                       // UTF-8 with the byte order mark, as Excel's "CSV UTF-8"
}

var shown = new StringWriter();
sheet.ToCsv(shown);                          // or to any TextWriter
Console.Write(shown.ToString());

It prints the first three lines below; the rest come from the samples further down this page.

Item,Price,Ordered
"Pear, green","1,234.50",17 Nov 2026
"=HYPERLINK(""http://example.test"")",-5,
-- typed values, a semicolon, line feeds
Item;Price;Ordered
Pear, green;1234.5;2026-11-17
"=HYPERLINK(""http://example.test"")";-5;
-- the formula guard
"'=HYPERLINK(""http://example.test"")",-5
-- JSON
[
  {"Item":"Pear, green","Price":1234.5,"Ordered":"2026-11-17"},
  {"Item":"=HYPERLINK(\"http://example.test\")","Price":-5,"Ordered":null}
]
[["Item","Price","Ordered"],["Pear, green","1,234.50","17 Nov 2026"]]
-- Markdown
| Item | Price | Ordered |
| --- | --- | --- |
| Pear, green | 1,234.50 | 17 Nov 2026 |
-- CSV in
A2: Text '007' | inferred: Text '007'
B2: Text '12' | inferred: Number '12'
C2: Text '2026-12-01' | inferred: Date (a date) '2026-12-01'
C3: Text '1 Dec 2026' | inferred: Text '1 Dec 2026'
D3: Text '=SUM(A1)' | inferred: Text '=SUM(A1)'
The quoted field that opens at row 1, field 2 is never closed.
MaxCells: The text fills more than MaxCells=4 cells.
-- a Markdown table in
3 rows, 3 columns
B2 is Text '12', C2 is 'a | b'
-- numbers are searched by what they show
1,234 is found in A2
1234 is found in A1
2026 is found in A3
text only: 0 matches
A2 is a Number shown as '1,299.50'
replaced 0; skipped A4: The cell holds a number, and '1.5' reads as a number that the cell's format would show differently, so there is no telling which value was meant. Set the cell's value instead.
A1 is Text 'n/a'

Download the file it wrote: sheet-export.csv.

With no options, ToCsv writes what Excel's own CSV save writes, and ToCsv(Stream) gives the bytes of its "CSV UTF-8" save:

Excel does this, and so does ToCsv
The range is the sheet's used range It starts at the first cell that holds anything, not at A1.
Every row is as wide as the range A row with nothing is a row of commas; a sheet with nothing is one empty row.
A cell is the text it shows 1,234.50, 17 Nov 2026, 12.5%. A formula cell is its stored result; an error is its text.
A field is quoted only when it must be When it holds a comma, a quote or a line break. A quote inside is doubled. Leading and trailing spaces are kept.
A row ends in CR LF A line break inside a cell stays a line feed, inside the quotes.
A column's width changes nothing A number the column shows as #### is written in full.
Hidden rows are written Of a merged range, only the first cell holds anything.
Note

Checked against Excel, byte for byte. Excel saved eleven workbooks as "CSV UTF-8" and ToCsv gives the same bytes for each one; the tests run every one.

To write a sheet chosen by name, call the workbook: book.ToCsv("Summary", writer).

Options

using DocWright.Spreadsheet;

var typed = new StringWriter();
sheet.ToCsv(typed, new XlsxCsvOptions
{
    ValuesAs = XlsxExportValues.Typed,       // 1234.5 and 2026-11-17, whatever the cells' formats
    Delimiter = ';',
    NewLine = "\n",
});
Console.Write(typed.ToString());
XlsxCsvOptions Default Meaning
ValuesAs DisplayedText Typed writes a number plainly whatever its format (1234.5), a date as ISO 8601 (2026-11-17, 2026-11-17T08:30:00) and a boolean as TRUE or FALSE.
Delimiter , Any character but a quote or a line break.
NewLine "\r\n" Or "\n", or "\r".
ByteOrderMark true For ToCsv(Stream). A TextWriter has its own encoding.
GuardFormulas false See below.
Range the used range Any XlsxCellRange, for example from A1.
MaxCells 10,000,000 The most cells the range may cover. Past it: ResourceLimitExceededException, before a row is read. null for no limit.

Formula injection

A CSV is plain text, but the application that opens it decides what a field is. A field that begins with =, +, - or @ is run as a formula by Excel and by other spreadsheets, and a sheet can hold such text because somebody typed it into a form.

using DocWright.Spreadsheet;

var guarded = new StringWriter();
sheet.ToCsv(guarded, new XlsxCsvOptions { GuardFormulas = true, Range = new XlsxCellRange(3, 1, 3, 2) });
Console.Write(guarded.ToString());

GuardFormulas writes such a field with an apostrophe in front, which makes it text when a spreadsheet opens it. A number that only carries a sign, like -5, is left alone.

Warning

The guard is off by default. The apostrophe is part of the field for every other reader: a database import or a script gets '=.... Turn it on when the sheet holds text from people you do not trust and the file is meant to be opened in a spreadsheet.

A sheet as JSON

using System.Text;
using DocWright.Spreadsheet;

using (var json = new MemoryStream())
{
    sheet.ToJson(json, new XlsxJsonOptions { Indented = true });
    File.WriteAllBytes("sheet-export.json", json.ToArray());
    Console.WriteLine(Encoding.UTF8.GetString(json.ToArray()));
}

using (var rows = new MemoryStream())
{
    book.ToJson("Sheet1", rows, new XlsxJsonOptions
    {
        FirstRowIsHeader = false,                       // an array of arrays
        ValuesAs = XlsxExportValues.DisplayedText,      // every cell as the string Excel shows
        Range = new XlsxCellRange(1, 1, 2, 3),
    });
    Console.WriteLine(Encoding.UTF8.GetString(rows.ToArray()));
}

Download: sheet-export.json.

XlsxJsonOptions Default Meaning
FirstRowIsHeader true The first row names the properties and each row below is an object. false gives an array of arrays.
ValuesAs Typed A number is a JSON number, a boolean true or false, a date an ISO 8601 string, an error its text, an empty cell null. DisplayedText makes every cell the string Excel shows.
Indented false One row on each line.
Range, MaxCells as for CSV

A blank heading becomes Column3 and a repeated one gets _2. An empty sheet is []. The output is UTF-8 with no byte order mark, and DocWright writes it itself: the package has no dependency on a JSON library. Reading JSON into a workbook is not offered; deserialize it and use ImportData.

A sheet as a Markdown table

using DocWright.Spreadsheet;

var markdown = new StringWriter();
sheet.ToMarkdown(markdown, new XlsxMarkdownOptions { Range = new XlsxCellRange(1, 1, 2, 3) });
Console.Write(markdown.ToString());

The table is a pipe table (GitHub Flavored Markdown) of the text each cell shows. The first row is the heading; with FirstRowIsHeader = false the heading is the column letters, because a Markdown table has to have one. A vertical bar and a backslash in a cell get a backslash in front, and a line break in a cell becomes <br>, since a table row is one line. Other Markdown in a cell is left as it is.

A workbook from CSV

using DocWright.Spreadsheet;

const string Csv = "Code,Qty,Due,Note\r\n007,12,2026-12-01,\"two\nlines\"\r\nA-1,1.5,1 Dec 2026,=SUM(A1)\r\n";

XlsxDocument plain = XlsxDocument.FromCsv(new StringReader(Csv));
XlsxDocument inferred = XlsxDocument.FromCsv(
    new StringReader(Csv),
    new XlsxCsvReadOptions { InferTypes = true, SheetName = "Orders" });

foreach (string reference in new[] { "A2", "B2", "C2", "C3", "D3" })
{
    XlsxDocumentCell a = plain.Sheets[0].GetCell(reference);
    XlsxDocumentCell b = inferred.Sheets[0].GetCell(reference);
    Console.WriteLine($"{reference}: {a.Value.Kind} '{a.DisplayText}' | inferred: {b.Value.Kind}{(b.IsDate ? " (a date)" : string.Empty)} '{b.DisplayText}'");
}

using (FileStream output = File.Create("from-csv.xlsx"))
{
    inferred.Save(output);
}

Download the workbook: from-csv.xlsx.

The workbook is the one XlsxDocument.Create() starts, with the fields from A1. Every field is text unless you ask otherwise, so nothing is lost or guessed: 007 stays 007, and a field that begins with = is text, never a formula. Quoted fields, doubled quotes, line breaks inside quotes, any of the three line ends, a byte order mark and rows of different lengths are all read.

XlsxCsvReadOptions Default Meaning
Delimiter , Not the quote and not a line break.
Quote "
DetectDelimiter false The first record decides: of the comma, the semicolon, the tab and the vertical bar, the one that occurs most outside quotes. The quote is never guessed.
InferTypes false An unquoted field that is a number in the invariant form (-1234.5, 1E+3) becomes a number, and an ISO 8601 date (2026-12-01, optionally with a time) becomes a date, in a column made wide enough to show it. 007, 12%, TRUE and 1 Dec 2026 stay text.
SheetName Sheet1
MaxCells 2,000,000 The workbook is built in memory. null for no limit beyond the grid.

The text is somebody else's, so it is bounded:

using DocWright.Core;
using DocWright.Spreadsheet;

try
{
    XlsxDocument.FromCsv(new StringReader("a,\"never closed"));
}
catch (InvalidDocumentException refused)
{
    Console.WriteLine(refused.Message);
}

try
{
    XlsxDocument.FromCsv(new StringReader("a,b,c\nd,e,f"), new XlsxCsvReadOptions { MaxCells = 4 });
}
catch (ResourceLimitExceededException limit)
{
    Console.WriteLine($"{limit.LimitName}: {limit.Message}");
}

A field longer than the 32,767 characters a cell holds, a row past column 16,384 and a row past 1,048,576 are refused with InvalidDocumentException too.

A workbook from a Markdown table

using DocWright.Spreadsheet;

const string Page = "# Stock\n\nAs counted on Monday:\n\n| Item | Qty | Note |\n| :--- | ---: | --- |\n| Pear | 12 | a \\| b |\n| Fig | 3 | first<br>second |\n\nThat is all.\n";

XlsxDocumentSheet table = XlsxDocument.FromMarkdownTable(new StringReader(Page)).Sheets[0];
XlsxCellRange area = table.Dimension!.Value;
Console.WriteLine($"{area.LastRow} rows, {area.LastColumn} columns");
Console.WriteLine($"B2 is {table.GetCell("B2").Value.Kind} '{table.GetCell("B2").Value.TextValue}', C2 is '{table.GetCell("C2").Value.TextValue}'");

FromMarkdownTable reads the first pipe table in a text: a row of cells, a row of dashes of as many cells, then the rows until a blank line or a line with no vertical bar. What stands before the table is passed over. Every cell is text; \|, \\ and <br> are read back as ToMarkdown wrote them. A text with no table is InvalidDocumentException.

Numbers are searched by what they show

A search looks at every cell the way Excel's Find does: a number, a date, a boolean and an error are matched against the text the cell shows.

using DocWright.Spreadsheet;

XlsxDocument numbers = XlsxDocument.Create();
XlsxDocumentSheet s = numbers.Sheets[0];
s.SetValue("A1", XlsxCellValue.Number(1234.5m));
s.SetValue("A2", XlsxCellValue.Number(1234.5m));
s.SetValue("A3", XlsxCellValue.Date(new DateTime(2026, 11, 17)));
s.SetValue("A4", XlsxCellValue.Number(1.5m));
s.SetStyle("A2", numbers.DefaultStyle.With(numberFormat: "#,##0.00"));
s.SetStyle("A3", numbers.DefaultStyle.With(numberFormat: "yyyy-mm-dd"));
s.SetStyle("A4", numbers.DefaultStyle.With(numberFormat: "0.00"));

Console.WriteLine("1,234 is found in " + string.Join(" ", s.FindText("1,234").Select(m => m.Reference)));
Console.WriteLine("1234 is found in " + string.Join(" ", s.FindText("1234").Select(m => m.Reference)));
Console.WriteLine("2026 is found in " + string.Join(" ", s.FindText("2026").Select(m => m.Reference)));
Console.WriteLine("text only: " + s.FindText("1234", new XlsxFindOptions { SearchNumbers = false }).Count + " matches");

So 1,234 finds the number shown as 1,234.50 and not the same number shown as 1234.5, and a date's serial number finds nothing. Set SearchNumbers = false to search text only.

Important

This is a change from 1.12. A search there looked at text cells only. The same call now returns number cells too. See upgrading.

A replace in a number is made in the text it shows:

using DocWright.Spreadsheet;

XlsxReplaceResult result = s.ReplaceText("1,234", "1,299");
Console.WriteLine($"A2 is a {s.GetCell("A2").Value.Kind} shown as '{s.GetCell("A2").DisplayText}'");

result = s.ReplaceText("1.50", "1.5");
Console.WriteLine($"replaced {result.ReplacedCount}; skipped {result.Skipped[0].Reference}: {result.Skipped[0].Reason}");

result = s.ReplaceText("1234.5", "n/a");
Console.WriteLine($"A1 is {s.GetCell("A1").Value.Kind} '{s.GetCell("A1").Value.TextValue}'");
The new text The cell becomes
is what the cell's format shows for some value (1,299.50 under #,##0.00) that number, in the same format
is an ISO date, in a date cell whose format shows it that way that date
reads as a number the format would show differently (1.5 under 0.00, which shows 1.50) nothing: the cell is in Skipped with the reason
is no number at all (n/a) text

A number that a formula results in is found and never replaced.

Note

One difference from Excel: a number in a column too narrow for it shows as #### there, and Excel's Find then matches the hashes. Here the cell is searched by its full text.