Version 1.0.0. A short overview is in the README.md file and the release history is in the CHANGELOG.md file, both in the root folder of the package.
This manual ships in the Documentation~ folder of the package as index.md.
Overview
Sheet Maker writes and reads spreadsheets from C#: .xlsx workbooks and .csv files, at runtime and in the Editor.
- Writing .xlsx. Several sheets; text, numbers, booleans, dates and formula text; number formats; a small style set (bold, italic, underline, font colour, fill colour, borders, horizontal alignment, wrap); column widths; a frozen header row and first column; auto-filter; merged cells; hyperlinks. Rows are written one after the other and compressed as they go, so a sheet of 100,000 rows does not have to be held in memory.
- Reading .xlsx. Sheet names, and the rows of each sheet with typed cells: text, numbers, booleans, dates, errors and the results a file has cached for its formulas.
- CSV. A writer and a reader for the format RFC 4180 describes, with the delimiter you choose and an optional byte order mark. Culture-invariant.
- Typed mapping.
SheetMap<T>declares columns with delegates (a header, a getter and an optional setter) to export a list of your objects and to read rows back into objects. - Output to a file, a
Streamor abyte[]. A workbook or CSV can be written and read on any thread, one thread at a time per object.
The package is managed C# only. The ZIP container, the DEFLATE compressor and decompressor, the CRC-32 and the XML reading and writing are part of this package and based on the published specifications (RFC 1951, the ZIP application note, ECMA-376 and RFC 4180). The runtime assembly uses nothing beyond the .NET core types and UnityEngine.CoreModule: no System.IO.Compression, no System.Xml, no System.Linq, no regular expressions, no reflection on your types, no native plugin and no third-party library. The package contains no native code. It was run on Windows 11 (Editor, Mono and IL2CPP players), on Android x86-64 emulators and, before the corrections of 2026-10-09, as a WebGL build in a headless browser; other platforms were not run. The table under Platform support shows which configurations were run and when.
You do not have to set up a link.xml, a scripting define, a permission or a native library.
Sheet Maker does not turn sheets into ScriptableObjects, does not sync with Google Sheets or any online service, and does not calculate formulas. Limitations lists everything that is left out of this version.
Requirements
- Unity 6000.0.84f1 or newer. Tested with Unity 6000.0.84f1 and 6000.3.12f1 only.
- No other package and no other Unity module. The package declares no dependencies, and its runtime assembly uses
UnityEngine.CoreModuleonly for the two colour structsColorandColor32. - The package contains no native code and no platform-specific code. It was run only on Windows 11, on Android emulators and, in an earlier build, on WebGL; see Tested configurations. Read Platform support and Where files go for what differs on WebGL, Android and iOS.
- The demo scenes use uGUI, so they need the
com.unity.uguipackage. The package itself does not. A few samples in this manual use Unity APIs that every new project has (UnityWebRequest, IMGUI, the Editor API).
Installation
From the Asset Store
- Open the Package Manager: Window > Package Manager in Unity 6.0, Window > Package Management > Package Manager in Unity 6.3.
- Select My Assets and find Sheet Maker.
- Click Download, then Install.
Unity installs Sheet Maker as a package. It appears in the Project window under Packages > Sheet Maker, not under Assets/, and its files are read-only. Your own scripts, scenes and spreadsheets go under Assets/ as usual.
Folders of the package whose name ends in ~ are not shown in the Project window: Documentation~ (this manual) and Samples~ (the demo, imported as described below). To reach them, right-click Packages > Sheet Maker in the Project window and choose Show in Explorer (Reveal in Finder on macOS).
If your scripts live in an assembly definition, add a reference to Luanrobs.Sheets to it. Scripts outside assembly definitions need nothing.
Demo scenes
- In the Package Manager, select Sheet Maker.
- Open the Samples tab.
- Click Import next to Demo.
Unity copies the sample into your project under Assets/Samples, where you can open and change it. It has four small scenes in its Scenes folder. Open 01 Export Table, 02 Read Spreadsheet or 03 Stress Export and press Play. 00 Menu switches between them, and needs all four scenes in the Scene List first (see the notes under the table).
| Scene | What it shows |
|---|---|
00 Menu |
Launcher with one button per scene. Its footer link to the product page opens only when it is clicked. |
01 Export Table |
A high-score table on screen. Export .xlsx writes HighScores.xlsx: the sheet Scores through a SheetMap<T>, and a second sheet Summary written with the sheet API (a merged title, styles, a number format, a formula and a link). Export .csv writes HighScores.csv. The full path and the time taken are shown. |
02 Read Spreadsheet |
Reads the bundled Data/Inventory.bytes, an .xlsx file referenced as a TextAsset, with XlsxReader, and lists its sheets and rows with the kind of each cell. |
03 Stress Export |
Writes 100,000 rows of 8 columns to Stress.xlsx with a reused row buffer, on a background thread (in slices inside a coroutine on WebGL, which has no threads), and shows the rows written, the time taken and the file size. |
Things to know:
- The scenes use uGUI with Unity's built-in font, so they need the
com.unity.uguipackage. They do not need TextMeshPro, and the sample contains no font files. The package itself does not need uGUI. - The sample uses the luanrobs look: cream text and outlines on navy. The colours are stored in the scenes themselves.
- The EventSystem is created at runtime with the input module that matches your project (the Input System package or the legacy Input Manager).
- The menu loads the other scenes by name, so it works only when all four scenes are in the Scene List in File > Build Profiles, with
00 Menufirst. That holds in Play mode in the Editor as well as in a build: until then a button of the menu shows a message instead of loading its scene. Each of the other three scenes runs by itself without it. - Files are saved under
Application.persistentDataPathin aSheetMakerfolder, and the full path is shown on screen. The Open file and Show folder buttons exist only in the Editor and in desktop players, and act only when you click them. Nothing in the sample opens a file, a folder or a web page on its own. - The link in the footer of
00 Menuopenshttps://luanrobs.com/sheet-maker/only when it is clicked. Delete that object from the scene to remove it. Data/Inventory.bytesis a spreadsheet generated for the sample with invented data. A file with the extension.bytesis imported by Unity as aTextAsset, which is how02 Read Spreadsheetreaches it on every platform.- A
README.txtin the sample folder repeats these notes.
Quick start
Write a workbook with one sheet to the folder Unity keeps your game's files in. Save the script as QuickStartWrite.cs, add it to any GameObject and press Play. The package does not size columns, and a spreadsheet application shows ##### for a date in a column that is too narrow for its format, so the sample sets the width of column C before the first row.
using System;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class QuickStartWrite : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "scores.xlsx");
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Scores");
sheet.SetColumnWidth(2, 20); // column C holds dates: wide enough for "2026-10-08 00:00:00"
sheet.AddRow(new SheetStyle { Bold = true }, "Player", "Points", "Date");
sheet.AddRow("Ana", 1200, new DateTime(2026, 10, 8));
sheet.AddRow("Bruno", 950, new DateTime(2026, 10, 7));
}
Debug.Log("Saved " + path);
}
}
Read it back. Save this one as QuickStartRead.cs, and run the first script once before it: the reader throws FileNotFoundException when the file does not exist yet.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class QuickStartRead : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "scores.xlsx");
using (var workbook = new XlsxReader(path))
using (XlsxSheetReader sheet = workbook.OpenSheet("Scores"))
{
while (sheet.ReadRow())
{
if (sheet.RowIndex == 0)
{
continue; // the header row: "Points" is a text, not a number
}
string player = sheet[0].AsString();
int points = sheet[1].AsInt();
string date = sheet[2].AsString();
Debug.Log("Row " + (sheet.RowIndex + 1) + ": " + player + ", " + points + ", " + date);
}
}
}
}
Things to know:
- Dispose finishes the file.
usingcallsDispose, which callsClose. A file whose writer was never closed is incomplete. - Indexes are zero-based. Row 0, column 0 is the cell
A1. This applies to every row and column number in the package. - Values become cells by themselves.
"Ana",1200and aDateTimeare converted toSheetCellwhen they are passed toAddRow. See Cells and conversions. - The date comes back as a date. A number cell whose number format is a date format is read as a
DateTimecell.AsString()prints it asyyyy-MM-dd HH:mm:ss. - Where is the file? See Where files go.
Writing .xlsx files
Workbook, sheets and rows
XlsxWriter writes a workbook one sheet after the other and one row after the other, straight into its output.
- Create the writer.
- Call
AddSheet(name)and add rows to theXlsxSheetWriterit returns. - Add more sheets if you need them. Each
AddSheetfinishes the sheet before it. - Call
Close(), or leave theusingblock.
Only the sheet added last accepts calls. After the next AddSheet, or after Close(), an earlier sheet throws InvalidOperationException. Close() can be called more than once. A workbook with no sheet gets an empty sheet named Sheet1 when it is closed, because a workbook without sheets cannot be opened.
A sheet name has 1 to 31 characters, none of : \ / ? * [ ], no control character, does not start or end with an apostrophe ('), is different from every other sheet name in the workbook, ignoring case, and is not History (in any case), a name spreadsheet applications reserve for themselves. A name that breaks a rule throws ArgumentException.
The three outputs
The constructor you choose decides where the workbook goes.
| Constructor | Output | Notes |
|---|---|---|
new XlsxWriter(path, options) |
A file | The folder must exist. A file that already exists is replaced. If writing fails, an incomplete file is left behind. The writer owns the file and releases it on Dispose. |
new XlsxWriter(stream, options, leaveOpen) |
A Stream |
The stream must be writable; it does not have to seek, so a network stream is accepted. The workbook starts at the stream's current position. Close finishes the workbook and flushes, and never closes a stream you passed; Dispose closes it unless leaveOpen is true. When the stream can seek and holds more data after the end of the workbook (an older, longer file being written over), it is cut at the end of the workbook, because a workbook must be the last thing in its file. |
new XlsxWriter(options) |
Memory | Get the bytes with ToArray(). Each call returns a new array. The writer keeps its buffer, so ToArray() still returns the bytes after Dispose. |
All options arguments are optional; null means the defaults.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class ThreeOutputs : MonoBehaviour
{
private void Start()
{
// 1. A file. The folder must exist; a file that already exists is replaced.
string path = Path.Combine(Application.persistentDataPath, "report.xlsx");
using (var workbook = new XlsxWriter(path))
{
Fill(workbook);
}
// 2. A stream. leaveOpen keeps it open after the writer is disposed.
using (var memory = new MemoryStream())
{
using (var workbook = new XlsxWriter(memory, leaveOpen: true))
{
Fill(workbook);
}
Debug.Log("The stream holds " + memory.Length + " bytes.");
}
// 3. A byte array, built in memory.
using (var workbook = new XlsxWriter())
{
Fill(workbook);
byte[] bytes = workbook.ToArray();
Debug.Log("The array holds " + bytes.Length + " bytes.");
}
}
private static void Fill(XlsxWriter workbook)
{
XlsxSheetWriter sheet = workbook.AddSheet("Report");
sheet.AddRow("Hello", "World");
}
}
Rows
| Call | What it does |
|---|---|
AddRow(params SheetCell[] cells) |
Appends a row made from the values you pass. With no arguments it appends an empty row. |
AddRow(SheetStyle rowStyle, params SheetCell[] cells) |
The same, with a style for the cells of the row that have no style of their own. |
AddRow(SheetCell[] cells, int count) |
Appends the first count cells of an array. Use it with one array that you reuse for every row; see Large exports. |
AddRow(SheetCell[] cells, int count, SheetStyle rowStyle) |
The same, with a row style. |
SkipRows(int count) |
Leaves the next count rows empty. |
RowCount is the number of rows written or skipped so far, which is also the zero-based index the next row will get. Arrays passed to AddRow are not kept.
Rules for the values:
- An empty text is written like an empty cell. An empty cell is written only when it has a style, so the style shows.
- A number that is NaN or infinite is written as the error
#NUM!. - A text may have up to 32,767 characters. Characters that XML 1.0 cannot hold (the control characters other than tab and line feed, and every carriage return) are stored with the
_xHHHH_escape that spreadsheet applications use, and this package's reader undoes it. A text that already looks like_x000D_is stored so that it comes back unchanged. An unpaired surrogate is replaced by U+FFFD. - A sheet can have 1,048,576 rows and 16,384 columns. A row of more than 16,384 cells, a text, formula or link over its limit, or a date before 1900 throws instead of being written. The exact exceptions are in Error handling, which also says what an exception does to the writer.
What the file contains
The writer follows the transitional ECMA-376 format. The parts are written in this order: for each sheet its xl/worksheets/sheetN.xml (and a _rels part when the sheet has links), then xl/sharedStrings.xml (only when shared strings are on and a text was written), xl/styles.xml, xl/workbook.xml, xl/_rels/workbook.xml.rels, _rels/.rels and [Content_Types].xml. There is no docProps part, so the file carries no author, title or creation date. The same calls always produce the same bytes: no timestamps and no random identifiers are written. A workbook that has a formula is marked to be recalculated when it is opened.
Whether Microsoft Excel, LibreOffice and Google Sheets open these files without a message has not been tested; see Platform support.
Writer options
XlsxWriterOptions is copied when the writer is created. Changing it afterwards does not affect a writer that already exists.
| Field | Type | Default | Description |
|---|---|---|---|
Compression |
SheetCompression |
Fast |
Store writes no compression and gives a larger file. Fast compresses with a short match search. Compact searches longer for repeated data, aiming at a smaller file, and takes longer to write. A value that is not one of the three throws ArgumentException when the writer is created. |
UseSharedStrings |
bool |
true |
true stores each distinct text once in the shared string table, as spreadsheet applications do. The writer keeps the texts of that table in memory until it is closed, so the table is bounded: after 65,536 distinct texts or about 4 million characters (about 8 MB), a text that is not in it yet is written inside its own cell, and texts already in it keep being shared. false writes every text inside its own cell and keeps no text in memory. |
DateFormat |
string |
yyyy-mm-dd hh:mm:ss |
The number format code given to date cells whose style has no number format. This is a spreadsheet format code, not a .NET format string: literal text goes in double quotes (yyyy-mm-dd"T"hh:mm:ss). Setting null or empty throws ArgumentException; so does a control character in it or a code longer than 255 characters, when the writer is created. |
Cells and conversions
SheetCell is the one type used to write rows and to read them back. It is an immutable value, so it can be shared and used from any thread.
Writing: implicit conversions
These convert to a SheetCell by themselves, in AddRow, in an array initializer or in a SheetMap getter:
| Value | Cell |
|---|---|
string |
Text. A null string is an empty cell; "" is a text cell that is written like an empty cell. |
char |
Text of one character. |
double, float, int, uint, long, ulong, short, ushort, byte, sbyte, decimal |
Number. A float goes through its shortest round-trip decimal form, so 1.1f is stored as 1.1. A decimal is converted to a double. |
bool |
Boolean. |
DateTime |
Date. DateTime.Kind is ignored and the clock value is stored as it is. See Dates. |
char?, double?, float?, int?, long?, decimal?, bool?, DateTime? |
The value, or an empty cell for null. |
Other types do not convert. Convert them yourself, for example value.ToString() or (int)myEnum. The compiler tells you with Cannot implicitly convert type 'X' to 'Luanrobs.Sheets.SheetCell'; see Troubleshooting and FAQ.
There are also cells built by method: SheetCell.Empty, SheetCell.Formula(text), SheetCell.Link(text, url), and WithStyle(style) and WithLink(url) on any cell.
using System;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class CellKinds : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "cells.xlsx");
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Cells");
sheet.AddRow(
"text", // string: a text cell
42, // int, long, short, byte...: a number
3.14159, // double: a number
1.1f, // float: stored as 1.1
19.90m, // decimal: a number
true, // bool: a boolean
new DateTime(2026, 10, 8, 14, 30, 0), // DateTime: a date cell
'x', // char: a text of one character
(int?)null, // a null nullable: an empty cell
SheetCell.Empty, // an empty cell
SheetCell.Formula("SUM(B1:C1)")); // formula text, not calculated
var buffer = new SheetCell[] { "Ana", 1200, false };
sheet.AddRow(buffer, buffer.Length);
}
}
}
Reading: kind and conversions
A cell has a Kind: Empty, Text, Number, Boolean, DateTime or Error. The typed properties give the value of the matching kind and a default for every other kind: Text (also the code of an Error), Number, Boolean, DateTime. For any kind, the As methods convert and never throw; they return the fallback you pass when the conversion does not apply.
| Kind | AsString() |
AsDouble(f) |
AsBool(f) |
AsDateTime(f) |
|---|---|---|---|---|
| Empty | "" |
f | f | f |
| Text | the text | the text parsed as a number with the invariant culture (a decimal point, no thousands separators), else f | true, yes or 1 is true and false, no or 0 is false (spaces trimmed, case ignored), else f |
the text parsed with the invariant culture, else f |
| Number | the number in round-trip format, invariant culture | the number | true when not zero (NaN gives f) | the number read as a 1900-system serial, else f |
| Boolean | TRUE or FALSE |
1 or 0 | the value | f |
| DateTime | yyyy-MM-dd HH:mm:ss |
the 1900-system serial (a time on 1899-12-31 gives its fraction of a day; before 1899-12-31 gives f) | f | the value |
| Error | the code, for example #DIV/0! |
f | f | f |
AsInt and AsLong take AsDouble and round half away from zero. They return the fallback when there is no number or it does not fit. Spreadsheet numbers are doubles, so integers beyond 2^53 are not exact in a number cell. A text that is a whole number is converted exactly, with all its digits, so a 64-bit identifier kept as text (every CSV field is a text) survives.
AsDateTime on a text applies no time zone: it returns the clock value as it is written, with DateTimeKind.Unspecified, also when the text ends in Z or in an offset such as +02:00 (2026-10-08T14:30:00Z gives 14:30 on every machine). A text that is only a time (12:30) gives that time on 1899-12-31, the day a reader uses for a cell that holds only a time, so use DateTime.TimeOfDay.
Two cells are equal (==, Equals) when their kind, value and formula text are equal. Style and link are not compared. ToString() is the same as AsString().
Styles and number formats
A SheetStyle describes how a cell looks in an .xlsx file. It has no effect on .csv files.
| Property | Type | Default | Description |
|---|---|---|---|
Bold |
bool |
false |
Bold text. |
Italic |
bool |
false |
Italic text. |
Underline |
bool |
false |
A single underline. |
FontColor |
SheetColor? |
null |
The text colour. Null is the default colour. |
FillColor |
SheetColor? |
null |
A solid background colour. Null is no fill. |
Borders |
SheetBorders |
None |
The sides that have a line: Left, Right, Top, Bottom, combined as flags, or All. |
BorderLine |
SheetBorderLine |
Thin |
The thickness of those lines: Thin, Medium or Thick. |
Align |
SheetAlign |
General |
General lets the application decide (text to the left, numbers and dates to the right); or Left, Center, Right. |
Wrap |
bool |
false |
Wraps long text onto several lines inside the cell. |
NumberFormat |
string |
null |
A number format code. Null, empty and General mean none. |
Clone() returns a copy.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class StyledReport : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "styled.xlsx");
// One style per look, reused for as many cells as needed.
var header = new SheetStyle
{
Bold = true,
FontColor = Color.white,
FillColor = SheetColor.FromHex("#1F2A44"),
Align = SheetAlign.Center,
Borders = SheetBorders.Bottom,
BorderLine = SheetBorderLine.Medium
};
var money = new SheetStyle { NumberFormat = SheetNumberFormats.Thousands2 };
var percent = new SheetStyle { NumberFormat = SheetNumberFormats.Percent };
var warning = new SheetStyle { FillColor = new Color32(255, 235, 156, 255), Italic = true, Wrap = true };
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Stock");
// Layout calls come before the first row.
sheet.SetColumnWidth(0, 24);
sheet.SetColumnStyle(2, money);
sheet.AddRow(header, "Item", "Quantity", "Price", "Discount", "Note");
SheetCell discount = 0.15;
SheetCell note = "Low stock";
sheet.AddRow("Sword", 3, 1250.5, discount.WithStyle(percent));
sheet.AddRow("Shield", 0, 980, discount.WithStyle(percent), note.WithStyle(warning));
}
}
}
Which style a cell gets
For each cell, the first of these that exists is used:
- The cell's own style (
cell.WithStyle(style)). - The style of the row (
AddRow(rowStyle, ...)). - The style of the column (
SetColumnStyle(column, style), set before the first row). - No style.
Styles replace each other as a whole. They are not merged property by property: a cell with its own style does not also get the bold of the row style.
Two exceptions:
- A cell with a link and no style of its own gets a built-in link look (font colour
0563C1, underlined) instead of the row or column style. Give the cell a style of its own to change that. - A date cell whose style has no number format gets that style plus
XlsxWriterOptions.DateFormat. This is the only case where two sources are combined.
Create one style object per look and reuse it. A style is read at the moment a cell, row or column that uses it is written, so changing it afterwards affects only what is written later. Do not change a style while another thread is writing with it. A workbook can hold up to 64,000 different styles; going past that throws InvalidOperationException.
Colours
SheetColor is an opaque RGB colour. Make one with new SheetColor(r, g, b), with SheetColor.FromHex("#1F2A44") (RRGGBB, with or without #; anything else throws FormatException), or let Unity colours convert by themselves: style.FillColor = Color.yellow and style.FontColor = new Color32(255, 0, 0, 255) both compile. The alpha channel is ignored, so a transparent colour such as Color.clear becomes solid black: use null for no fill and for the default font colour.
Number formats
NumberFormat takes a code in spreadsheet syntax. SheetNumberFormats has the common ones:
| Constant | Code | Shows |
|---|---|---|
General |
General |
No number format. |
Integer |
0 |
Whole numbers. |
Decimal2 |
0.00 |
Two decimals. |
Thousands |
#,##0 |
Whole numbers with thousands separators. |
Thousands2 |
#,##0.00 |
Two decimals with thousands separators. |
Percent |
0% |
0.25 shows as 25%. |
Percent2 |
0.00% |
Two decimals. |
Date |
yyyy-mm-dd |
Date only. |
DateTime |
yyyy-mm-dd hh:mm:ss |
Date and time. |
Time |
hh:mm:ss |
Time only. |
Text |
@ |
Treat the cell as text. |
Any other code in spreadsheet syntax is accepted too. Codes always use the invariant notation: a point as the decimal separator and a comma as the thousands separator. The application shows the number with the user's own separators. A code must not contain characters below U+0020 (ArgumentException).
Not available in this version: font name and size, vertical alignment, row heights, automatic column width and conditional formatting.
Dates
A date cell is a number (the serial number of the day, with the time of day as the fraction) plus a date number format. The package handles both parts for you.
- Only the 1900 date system is written. Serial 1 is 1900-01-01, serial 59 is 1900-02-28, serial 61 is 1900-03-01, serial 46303 is 2026-10-08, and noon is
.5. Spreadsheet applications count a 29 February 1900 that never existed (serial 60), and the writer allows for it, so dates on both sides of it are stored correctly. - Dates before 1899-12-31 throw.
AddRowthrowsArgumentOutOfRangeExceptionfor a date cell before 1899-12-31, and the writer can then only be disposed (see Error handling). Check the date first and write such dates as text. A date on 1899-12-31 is accepted and written as a time without a date (a serial below 1): that is how a reader returns a cell that holds only a time, so such a cell can be written again. - A time just before midnight stays on its day. Fractions of a millisecond are dropped when a date is written, so
date.AddDays(1).AddTicks(-1)is stored as 23:59:59.999 of that day. - No time zone is applied.
DateTime.Kindis ignored and the clock value is stored as it is. Convert to the time you want to show (ToLocalTime(), for example) before you write it. - The number format. A date cell is shown with
XlsxWriterOptions.DateFormat(defaultyyyy-mm-dd hh:mm:ss) unless its style has a number format of its own, for exampleSheetNumberFormats.Date. - A time of day without a date is a number: the fraction of a day, with the format
SheetNumberFormats.Time. - The column may be too narrow. Widen it with
SetColumnWidth; the package does not size columns by itself.
using System;
using System.Globalization;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class DateExamples : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "dates.xlsx");
// Date cells without a number format of their own use this one.
var options = new XlsxWriterOptions { DateFormat = SheetNumberFormats.DateTime };
var dateOnly = new SheetStyle { NumberFormat = SheetNumberFormats.Date };
var timeOnly = new SheetStyle { NumberFormat = SheetNumberFormats.Time };
using (var workbook = new XlsxWriter(path, options))
{
XlsxSheetWriter sheet = workbook.AddSheet("Dates");
sheet.SetColumnWidth(0, 22);
sheet.SetColumnWidth(1, 14);
sheet.SetColumnWidth(2, 14);
// A date and time, shown with the writer's DateFormat.
SheetCell stamp = new DateTime(2026, 10, 8, 14, 30, 0);
// The same kind of cell shown as a date only.
SheetCell day = new DateTime(2026, 10, 8);
// A time of day with no date: the fraction of a day, shown as a time.
SheetCell noon = TimeSpan.FromHours(12).TotalDays;
sheet.AddRow(stamp, day.WithStyle(dateOnly), noon.WithStyle(timeOnly));
// Dates before 1900-01-01 cannot be stored in a date cell: write them as text.
DateTime born = new DateTime(1850, 3, 1);
SheetCell bornCell = born >= new DateTime(1900, 1, 1)
? (SheetCell)born
: born.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
sheet.AddRow(bornCell);
}
}
}
Reading: a number cell whose style has a date or time number format is returned as a DateTime cell, with DateTimeKind.Unspecified, rounded to the nearest millisecond. Both the built-in date formats (ids 14 to 22, 27 to 36, 45 to 47 and 50 to 58) and custom codes that contain the letters y, m, d, h or s outside quotes and brackets count, and so do the elapsed-time forms [h], [m] and [s]; General, 0.00E+00 and @ do not. A workbook that uses the 1904 date system is read in that system. A serial below 1, a cell that holds only a time, is returned on 1899-12-31, in both date systems, so use DateTime.TimeOfDay; AsDouble() gives its fraction of a day, and the cell can be written again as it is. In a 1904-system workbook this means a cell dated 1904-01-01 (serial 0) is returned on 1899-12-31 with its time. Serials 59 and 60 both give 1900-02-28. A number that is negative, NaN or 2958466 or more is not a date and stays a Number cell.
The CSV writer prints dates with CsvOptions.DateFormat, a .NET custom format (yyyy-MM-dd HH:mm:ss by default). In that format MM is the month and mm the minute; the spreadsheet format codes above use mm for both, depending on where it stands. A date before 1900 is accepted by the CSV writer.
Formulas
SheetCell.Formula("SUM(B2:B10)") writes a formula. A leading equals sign is removed. A null, empty or = argument throws ArgumentException. The formula can have up to 8,192 characters, and when it is written, a character that XML cannot store in it throws ArgumentException.
The formula is stored, not calculated. The package writes the formula text and no result, and marks the workbook to be recalculated when it is opened. A spreadsheet application therefore shows the result. A tool that does not calculate, such as a file preview or a library that reads cached values, sees no value in the cell. This package's reader returns such a cell as an empty cell with HasFormula true and FormulaText set. The package does not check the syntax of the text.
Formula text follows the file format, not the language of the application: English function names, a comma between arguments and a point as the decimal separator. The application translates it for display.
SheetAddress builds the references. It takes zero-based indexes:
| Call | Result |
|---|---|
SheetAddress.Cell(0, 0) |
A1 |
SheetAddress.Range(1, 1, 10, 1) |
B2:B11 |
SheetAddress.ColumnName(26) |
AA |
SheetAddress.TryParseCell("$B$2", out row, out column) |
true, row 1, column 1 |
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class FormulaExamples : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "formulas.xlsx");
int[] prices = { 120, 80, 45, 300 };
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Prices");
sheet.AddRow(new SheetStyle { Bold = true }, "Item", "Price");
for (int i = 0; i < prices.Length; i++)
{
sheet.AddRow("Item " + (i + 1), prices[i]);
}
// Column B (index 1), from row 2 (index 1) to the last price.
string range = SheetAddress.Range(1, 1, prices.Length, 1);
sheet.AddRow("Total", SheetCell.Formula("SUM(" + range + ")"));
}
// A formula cell has no value in this file: only the formula text is stored.
using (var workbook = new XlsxReader(path))
using (XlsxSheetReader sheet = workbook.OpenSheet(0))
{
while (sheet.ReadRow())
{
for (int column = 0; column < sheet.CellCount; column++)
{
SheetCell cell = sheet[column];
if (cell.HasFormula)
{
Debug.Log(SheetAddress.Cell(sheet.RowIndex, column) + " = " + cell.FormulaText);
}
}
}
}
}
}
When you read a workbook, a formula cell has the kind and value of the result the file had cached, and its formula in FormulaText. A spreadsheet application stores a formula that was filled down a column once, in the first cell, and marks the cells below as reusing it; the reader gives each of those cells the formula for its own position (A2*2 in row 2 is reported as A3*2 in row 3; references fixed with $ stay). An empty string as FormulaText means the file marks the cell as a formula without giving its text (a data table cell, or a shared formula whose first cell is missing). When a cell is written again, a non-empty formula is written with its value as the cached result, and an empty formula text is written as the value only.
A text that starts with = in an .xlsx file is a text, not a formula: use SheetCell.Formula for formulas. In a .csv file, a formula cell is written as = followed by the formula text, and a text that starts with = is written as it is.
Links
SheetCell.Link(text, url) makes a text cell that opens an address when it is clicked in a spreadsheet application. With a null text, the address is shown. cell.WithLink(url) adds a link to a cell you already have; a null or empty address removes it.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class LinkExamples : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "links.xlsx");
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Links");
sheet.SetColumnWidth(0, 24);
sheet.SetColumnWidth(1, 36);
// The text is shown in the cell; the address opens when it is clicked.
sheet.AddRow("Product page", SheetCell.Link("Open the page", "https://luanrobs.com/sheet-maker/"));
// With no text, the address itself is shown.
sheet.AddRow("Support", SheetCell.Link(null, "mailto:luanrobs@gmail.com"));
// Add a link to a cell you already have, and give it a style of its own.
var linkStyle = new SheetStyle { Bold = true, Underline = true, FontColor = SheetColor.FromHex("0563C1") };
SheetCell docs = "Manual";
sheet.AddRow("Documentation", docs.WithLink("https://luanrobs.com/sheet-maker/docs/").WithStyle(linkStyle));
}
}
}
- The address is any address the application can open, for example a web address or a
mailto:address. It can have up to 2,079 characters and no control character, and a sheet can have up to 65,530 links. An empty address throwsArgumentExceptionwhen the cell is made; a longer one, or one with a control character, throws it when the cell is written. - A link cell without a style of its own looks like a link: blue and underlined. A style of its own replaces that look.
- Links are not read back. A cell from the reader has
LinkUrlnull. - In a .csv file only the text is written.
Layout
Layout calls shape the sheet. The ones that go into the head of the file must come before the first row, because the file is written as a stream.
| Call | When | What it does |
|---|---|---|
SetColumnWidth(column, width) |
Before the first row | The width in characters of the default font, more than 0 and up to 255. |
SetColumnStyle(column, style) |
Before the first row | The style for cells of the column that have no style of their own and are not in a row with a row style. Null removes it. Typically a number format for a whole column. |
FreezePanes(rows, columns) |
Before the first row | FreezePanes(1, 0) freezes a header row, FreezePanes(1, 1) also the first column, FreezePanes(0, 0) removes the freeze. |
MergeCells(firstRow, firstColumn, lastRow, lastColumn) |
Any time while the sheet is current | Merges a rectangle of cells. The merged cell shows its top-left cell. The corners may be in any order. A rectangle of one cell is ignored. A rectangle that overlaps an earlier merge throws ArgumentException. |
SetAutoFilter() |
Any time while the sheet is current | Filter buttons on row 0, covering every column and every row the sheet has when it is finished. Nothing is added to a sheet that ends up without cells. |
SetAutoFilter(firstRow, firstColumn, lastRow, lastColumn) |
Any time while the sheet is current | Filter buttons on the first row of the rectangle. A sheet has one filter; a second call replaces the first. |
A layout call that must come first, made after the first row, throws InvalidOperationException. So does any call on a sheet that is no longer the current one. Column and row numbers outside the sheet throw ArgumentOutOfRangeException.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class LayoutExample : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "inventory.xlsx");
var bold = new SheetStyle { Bold = true };
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Inventory");
// Layout first, before any row. Indexes are zero-based.
sheet.SetColumnWidth(0, 28);
sheet.SetColumnWidth(1, 10);
sheet.SetColumnWidth(2, 12);
sheet.SetColumnWidth(3, 12);
sheet.FreezePanes(3, 1); // rows 0-2 and column 0 stay in place
// Row 0: a title, merged across the four columns.
sheet.AddRow(bold, "Inventory report");
sheet.MergeCells(0, 0, 0, 3);
// Row 1 stays empty. Row 2 is the header.
sheet.SkipRows(1);
sheet.AddRow(bold, "Item", "Quantity", "Price", "Value");
// Rows 3 and 4: the data.
sheet.AddRow("Sword", 3, 1250.5, SheetCell.Formula("B4*C4"));
sheet.AddRow("Shield", 8, 980, SheetCell.Formula("B5*C5"));
// Filter buttons on the header row (row 2) over the data rows.
sheet.SetAutoFilter(2, 0, sheet.RowCount - 1, 3);
}
}
}
To merge a range, write the value in its top-left cell and leave the others empty.
Large exports
A sheet is never held as a whole: each row is compressed and written as it is added. While it works the writer keeps only bounded state: the column settings, the merges, the links and the filter of the current sheet, the styles, and, when shared strings are on, a table of at most 65,536 distinct texts and about 4 million characters (texts beyond that are written inside their cells). All of it is released when the workbook is closed. Four habits keep a large export light:
- Reuse one buffer.
AddRow(buffer, count)takes an array that you refill for every row, so no array is allocated per row. Set every cell that the count covers: a cell you leave alone keeps the value of the previous row. - Turn shared strings off with
UseSharedStrings = falsewhen the texts are mostly different from each other. The writer then keeps no text at all. With shared strings on, a file whose texts repeat stores each one once, and the table costs at most about 8 MB of text plus its index while the workbook is open. - Write to a file or a
Stream, not to memory. A writer created with no output keeps the whole compressed file in memory until you take it. - Choose the compression.
SheetCompression.Fastis the default.Storewrites the data without compression: a larger file and no compression work.Compactsearches longer for repeated data: aimed at a smaller file, and it takes longer to write.
A sheet holds up to 1,048,576 rows, the header included. Write further rows to another sheet.
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class LargeExport : MonoBehaviour
{
private const int Rows = 100000;
// This runs on the main thread, so the game pauses until it returns.
// See BackgroundExport and SlicedExport for the alternatives.
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "large.xlsx");
var options = new XlsxWriterOptions
{
Compression = SheetCompression.Fast, // the default
UseSharedStrings = false // memory does not grow with the number of distinct texts
};
// One buffer for the whole export: no array is allocated per row.
var buffer = new SheetCell[4];
using (var workbook = new XlsxWriter(path, options))
{
XlsxSheetWriter sheet = workbook.AddSheet("Data");
sheet.FreezePanes(1, 0);
sheet.AddRow(new SheetStyle { Bold = true }, "Id", "Name", "Value", "Active");
for (int i = 1; i <= Rows; i++)
{
// Set every cell that the count covers: a cell you skip keeps the previous row's value.
buffer[0] = i;
buffer[1] = "Item " + i;
buffer[2] = i * 0.25;
buffer[3] = i % 2 == 0;
sheet.AddRow(buffer, buffer.Length);
}
}
}
}
That loop runs on the main thread, so the game stands still until it ends. There are two ways to avoid that.
A background thread (every platform except WebGL). Create the writer on the other thread and use it only there. Read Unity values, for example Application.persistentDataPath, on the main thread first and pass plain values to the thread. Unity objects are not for other threads.
using System;
using System.IO;
using System.Threading.Tasks;
using Luanrobs.Sheets;
using UnityEngine;
public class BackgroundExport : MonoBehaviour
{
private volatile int rowsWritten;
private string status = "Idle";
// Call this from a button. Not for WebGL, which has no threads.
public async void StartExport()
{
// Read Unity values on the main thread, then hand plain values to the other thread.
string path = Path.Combine(Application.persistentDataPath, "background.xlsx");
rowsWritten = 0;
status = "Writing...";
try
{
await Task.Run(() => Write(path, 100000));
status = "Saved " + path;
}
catch (Exception exception)
{
status = "Failed: " + exception.Message;
}
}
// Runs on a thread-pool thread: it touches no Unity object.
private void Write(string path, int rows)
{
var buffer = new SheetCell[3];
var options = new XlsxWriterOptions { UseSharedStrings = false };
using (var workbook = new XlsxWriter(path, options))
{
XlsxSheetWriter sheet = workbook.AddSheet("Data");
sheet.AddRow(new SheetStyle { Bold = true }, "Id", "Name", "Value");
for (int i = 1; i <= rows; i++)
{
buffer[0] = i;
buffer[1] = "Item " + i;
buffer[2] = i * 0.5;
sheet.AddRow(buffer, buffer.Length);
rowsWritten = i;
}
}
}
private void OnGUI()
{
GUILayout.Label(status + " (" + rowsWritten + " rows)");
if (GUILayout.Button("Export 100,000 rows"))
{
StartExport();
}
}
}
Slices over several frames (the way on WebGL, which has no threads). The writer can stay open between frames, so a coroutine can write some rows, wait one frame and continue. If the coroutine is stopped or its object is destroyed before the end, Unity does not run the rest of it, so a using block would never dispose the writer and the file would stay open until the garbage collector releases it. Keep the writer in a field and dispose it in OnDestroy, as the sample does. The file then holds only the rows written so far: delete it if a partial export is of no use.
using System.Collections;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class SlicedExport : MonoBehaviour
{
private const int TotalRows = 100000;
private const int RowsPerFrame = 2000;
private XlsxWriter workbook;
private IEnumerator Start()
{
string path = Path.Combine(Application.persistentDataPath, "sliced.xlsx");
var buffer = new SheetCell[3];
var options = new XlsxWriterOptions { UseSharedStrings = false };
// The writer stays open between frames, so it is kept in a field: OnDestroy disposes it
// if this object goes away before the export ends.
workbook = new XlsxWriter(path, options);
XlsxSheetWriter sheet = workbook.AddSheet("Data");
sheet.AddRow(new SheetStyle { Bold = true }, "Id", "Name", "Value");
for (int i = 1; i <= TotalRows; i++)
{
buffer[0] = i;
buffer[1] = "Item " + i;
buffer[2] = i * 0.5;
sheet.AddRow(buffer, buffer.Length);
if (i % RowsPerFrame == 0)
{
yield return null;
}
}
workbook.Dispose();
workbook = null;
Debug.Log("Saved " + path);
}
private void OnDestroy()
{
// Unity does not run the rest of a coroutine that is stopped. Disposing here closes the
// file, which then holds only the rows written so far.
if (workbook != null)
{
workbook.Dispose();
workbook = null;
}
}
}
Measured on one Windows 11 machine on 2026-10-08. These are a few measurements on a machine that was also busy with other work, not a benchmark, and other machines and builds will differ. In three runs, the test suite wrote 100,000 rows of 10 columns of mixed kinds through one reused row buffer in 4.5 to 5.6 s in the Unity 6000.3 Editor (Mono). The managed memory grew by 14 to 16 MB while it wrote, a figure that also counts garbage the test itself made and that was not yet collected. The file is 6,182,637 bytes, and reading it back row by row took 8.2 to 11.6 s. The demo exports 100,000 rows of 8 columns on a background thread: 1.18 to 1.28 s in a Mono player and 0.75 to 0.77 s in an IL2CPP player (more than one run each; the IL2CPP runs include the one with managed stripping High), a file of 4,491,352 bytes that the demo shows as 4.28 MB. In the WebGL build, run in a headless browser on a software renderer, the same export in slices on the main thread took 2.7 s (one run).
Reading .xlsx files
XlsxReader opens a workbook. The constructor reads the list of sheets, the shared texts and the number formats; the rows of a sheet are read as you ask for them, so a large sheet is not held in memory as a whole.
| Constructor | Input | Notes |
|---|---|---|
new XlsxReader(path) |
A file | The file stays open until the reader is disposed. |
new XlsxReader(bytes) |
A byte[] |
The array is wrapped, not copied. Do not change it while the reader is in use. |
new XlsxReader(stream, leaveOpen) |
A Stream |
A seekable stream is read in place, from its start to its end, whatever its position; the workbook must be the last thing in the stream and may have other bytes in front of it (a header of your own, for example). A stream that cannot seek is first copied into memory from its current position. If the constructor throws because of the data and leaveOpen is false, the stream is disposed; for an invalid argument it is left alone. |
Then:
SheetCountandSheetNameslist the worksheets in workbook order, hidden sheets included. Chart sheets are not counted.FindSheet(name)returns the zero-based index of a sheet, ignoring case, or -1. A null name throwsArgumentNullException.OpenSheet(index)andOpenSheet(name)return anXlsxSheetReader, positioned before the first row. Each call returns an independent reader, so several can be open at once. An index out of range throwsArgumentOutOfRangeException, and a name that does not exist throwsArgumentException.- On the sheet reader,
ReadRow()moves to the next row and returns false at the end.RowIndexis the zero-based position of the current row in the sheet.CellCountis the number of cells of the row, that is the index of its last cell that has a value or a formula, plus one.this[column]returns the cell, and an empty cell at or beyondCellCount. ReadAllRows()reads every remaining row into a list. The index of an entry is its row index in the sheet; rows the file skipped are empty arrays; if a file lists a row twice or out of order, the later row replaces the earlier one. It holds the whole sheet in memory, so useReadRow()for large sheets. A row costs about 48 bytes for every column up to its last used one, empty cells in between included, so a single value in column XFD costs as much as 16,384 values. For that reasonReadAllRows()throwsSheetFormatExceptiononce the rows hold more than 4,000,000 cells (XlsxSheetReader.DefaultMaxCells, about 200 MB);ReadAllRows(maxCells)takes a limit of your choice.- A sheet whose data is damaged throws
SheetFormatExceptionfromReadRow(), and the same exception again from every later call. - Dispose the sheet reader and the workbook reader. Disposing the workbook reader stops the sheet readers it opened: they throw
ObjectDisposedException.
using System.Globalization;
using System.Text;
using Luanrobs.Sheets;
using UnityEngine;
public class WorkbookDump : MonoBehaviour
{
[SerializeField] private TextAsset workbookAsset;
private void Start()
{
using (var workbook = new XlsxReader(workbookAsset.bytes))
{
for (int index = 0; index < workbook.SheetCount; index++)
{
using (XlsxSheetReader sheet = workbook.OpenSheet(index))
{
Debug.Log("Sheet " + sheet.Name);
var line = new StringBuilder();
// Only rows that have a value or a formula are returned.
// RowIndex says where the row is in the sheet and may skip numbers.
while (sheet.ReadRow())
{
line.Length = 0;
line.Append("Row ").Append(sheet.RowIndex + 1).Append(':');
for (int column = 0; column < sheet.CellCount; column++)
{
line.Append(' ').Append(Describe(sheet[column]));
}
Debug.Log(line.ToString());
}
}
}
}
}
private static string Describe(SheetCell cell)
{
switch (cell.Kind)
{
case SheetCellKind.Text:
return "\"" + cell.Text + "\"";
case SheetCellKind.Number:
return cell.Number.ToString(CultureInfo.InvariantCulture);
case SheetCellKind.Boolean:
return cell.Boolean ? "TRUE" : "FALSE";
case SheetCellKind.DateTime:
return cell.DateTime.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
case SheetCellKind.Error:
return cell.Text;
default:
return cell.HasFormula ? "=" + cell.FormulaText : "(empty)";
}
}
}
What a row contains
ReadRow()returns only rows that have at least one cell with a value or a formula. Rows that are empty, or have only formatting, are skipped, soRowIndexcan jump. Use it, not a counter, to know where you are.- A cell is one of the kinds in Cells and conversions: text (shared or inline), number, boolean, date, error, or empty. A date is a number whose style has a date number format; see Dates. An error cell has the kind
Errorand its code, such as#DIV/0!, inText. - A formula cell has the kind and value of the result the file cached for it, and its formula in
FormulaText. Files written by this package, and by some other tools, cache no result: the kind is thenEmptyandHasFormulais true. - A merged range is not interpreted. The value is in its top-left cell and the other cells are empty.
- Styles, links, column widths and comments are not read.
StyleandLinkUrlare null on every cell from a reader. - Texts made of several formatted pieces (rich text) are returned as one text with the pieces joined. Phonetic guides are ignored.
What the reader accepts
The reader is based on the ECMA-376 specification. It finds the workbook through the package relationships and reads the sheets, shared strings and styles that relationships point to, with these variants: element names with a namespace prefix (x:row), cells and rows without a position attribute, absolute relationship targets, the 1904 date system, shared and inline strings, t="str", t="b", t="e" and t="d" cells, and ZIP entries written with a data descriptor. It reads UTF-8 XML only.
Files made by Microsoft Excel, LibreOffice and Google Sheets were not available on the test machine and were not tested. See Platform support.
Data that is not a readable workbook throws SheetFormatException with a message that says what was found: not a ZIP archive, an old binary .xls or a password-protected workbook (both are OLE compound files), a ZIP64 archive, an encrypted ZIP entry, a damaged entry, a missing workbook or sheet part, XML that is malformed, in UTF-16 or has a DOCTYPE, or a shared string index that does not exist.
Reading from a TextAsset
Unity does not import .xlsx files as text assets. Rename the file to end in .bytes and Unity imports it as a TextAsset. Read bytes, never text: the file is binary.
using Luanrobs.Sheets;
using UnityEngine;
public class InventoryList : MonoBehaviour
{
// A workbook file renamed to end in .bytes becomes a TextAsset when it is in Assets.
[SerializeField] private TextAsset workbookAsset;
private void Start()
{
// Use .bytes, never .text: the file is binary.
using (var workbook = new XlsxReader(workbookAsset.bytes))
{
Debug.Log("Sheets: " + string.Join(", ", workbook.SheetNames));
using (XlsxSheetReader sheet = workbook.OpenSheet(0))
{
while (sheet.ReadRow())
{
Debug.Log(sheet[0].AsString() + " x " + sheet[1].AsInt());
}
}
}
}
}
Reading from StreamingAssets
On desktop platforms Application.streamingAssetsPath is a normal folder. On Android and WebGL the files are inside the app package or on a web server, so File.ReadAllBytes does not reach them: load them with UnityWebRequest. A TextAsset avoids the question.
using System.Collections;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
using UnityEngine.Networking;
public class StreamingAssetsReader : MonoBehaviour
{
// The file is Assets/StreamingAssets/Inventory.xlsx.
[SerializeField] private string fileName = "Inventory.xlsx";
private IEnumerator Start()
{
string path = Path.Combine(Application.streamingAssetsPath, fileName);
byte[] data;
if (path.Contains("://"))
{
// Android and WebGL: StreamingAssets are not plain files.
using (UnityWebRequest request = UnityWebRequest.Get(path))
{
yield return request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogWarning("Could not load " + path + ": " + request.error);
yield break;
}
data = request.downloadHandler.data;
}
}
else
{
data = File.ReadAllBytes(path);
}
using (var workbook = new XlsxReader(data))
using (XlsxSheetReader sheet = workbook.OpenSheet(0))
{
while (sheet.ReadRow())
{
Debug.Log(sheet[0].AsString());
}
}
}
}
Copying a sheet
A cell from a reader can be written again. Values and formulas (with their cached results) are kept; styles, links, merged ranges and widths are not read, so they are not copied. RowIndex and SkipRows keep the gaps between rows.
using Luanrobs.Sheets;
public static class SheetCopier
{
// Copies every sheet of a workbook into a new file. Values and formulas (with the results the
// file cached for them) are copied. Styles, links, merged cells and widths are not.
public static void Copy(byte[] source, string destinationPath)
{
using (var reader = new XlsxReader(source))
using (var writer = new XlsxWriter(destinationPath))
{
var buffer = new SheetCell[0];
for (int index = 0; index < reader.SheetCount; index++)
{
XlsxSheetWriter target = writer.AddSheet(reader.SheetNames[index]);
using (XlsxSheetReader sheet = reader.OpenSheet(index))
{
while (sheet.ReadRow())
{
// Rows without values are skipped by the reader: keep the gaps.
int gap = sheet.RowIndex - target.RowCount;
if (gap > 0)
{
target.SkipRows(gap);
}
if (buffer.Length < sheet.CellCount)
{
buffer = new SheetCell[sheet.CellCount];
}
for (int column = 0; column < sheet.CellCount; column++)
{
buffer[column] = sheet[column];
}
target.AddRow(buffer, sheet.CellCount);
}
}
}
}
}
}
CSV
CsvWriter and CsvReader handle comma-separated values as RFC 4180 describes. They implement the same row interfaces as the .xlsx classes (ISheetRowWriter and ISheetRowReader), so code that produces or consumes rows can serve both formats.
Options
CsvOptions is copied when a writer or reader is created.
| Field | Type | Default | Description |
|---|---|---|---|
Delimiter |
char |
, |
The character between fields. A double quote, \r or \n throws ArgumentException. Use ; for applications set to a language with a decimal comma, or \t for tab-separated files. Used by the writer and the reader. |
NewLine |
string |
"\r\n" |
Writer only. The line break after each row: "\r\n" or "\n", nothing else. The reader accepts \r\n, \n and \r. |
WriteBom |
bool |
false |
Writer only, and only for byte output (a stream, a file or ToArray). Starts the output with the UTF-8 byte order mark; a stream that is not at its start (rows appended to a file) gets none. The reader skips a byte order mark whatever this is. |
QuoteAll |
bool |
false |
Writer only. Puts every field in double quotes. |
DateFormat |
string |
yyyy-MM-dd HH:mm:ss |
Writer only. The .NET custom format, used with the invariant culture, for date cells. Setting null or empty throws ArgumentException; so does a format .NET does not accept, when the writer is created. |
Writing
The constructors write to memory (new CsvWriter(options), then ToText() or ToArray()), to a file (new CsvWriter(path, options)), to a Stream (UTF-8) or to a TextWriter, which decides the encoding. Streams and files are always UTF-8. For another encoding, create a StreamWriter with the encoding you need and pass it. With leaveOpen the stream or text writer stays open when the writer is closed.
How each cell is written, with the invariant culture whatever the culture of the thread:
| Cell | Written as |
|---|---|
| Text | The text as it is. |
| Number | The number in round-trip format, with a decimal point. A whole number is written with all its digits and never with an exponent (1000000000000000, not 1E+15). NaN, Infinity and -Infinity for those values. A number cell holds a double, so write identifiers longer than 15 digits as text. |
| Boolean | TRUE or FALSE. |
| Date | CsvOptions.DateFormat. |
| Error | Its code. |
| Formula | = followed by the formula text. The value is ignored. |
| Empty | Nothing. |
A field is put in double quotes when it contains the delimiter, a double quote, a carriage return or a line feed, or when it starts or ends with a space, or starts with the character U+FEFF (which a reader would take for a byte order mark); or always, with QuoteAll. A double quote inside a field is doubled. Every row ends with NewLine, the last one included. A row with no cells writes just the line break, and so does a row of one empty cell (unless QuoteAll is on); the reader reads that line as a row without fields. Style and link are ignored. ToText() never starts with a byte order mark; ToArray() does when WriteBom is true. Both can still be called after Close() and Dispose().
using System;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class CsvExport : MonoBehaviour
{
private void Start()
{
string path = Path.Combine(Application.persistentDataPath, "scores.csv");
// Semicolon and a byte order mark suit spreadsheet applications set to a language
// that writes the decimal comma.
var options = new CsvOptions
{
Delimiter = ';',
WriteBom = true,
NewLine = "\r\n"
};
using (var csv = new CsvWriter(path, options))
{
csv.AddRow("Player", "Points", "Note", "Date");
csv.AddRow("Ana", 1200, "said \"hi\"", new DateTime(2026, 10, 8, 14, 30, 0));
csv.AddRow("Bruno", 950, "two\nlines", new DateTime(2026, 10, 7));
}
// The same rows as text, with the default options.
var inMemory = new CsvWriter();
inMemory.AddRow("a", 1.5, true);
Debug.Log(inMemory.ToText());
}
}
The file of that sample, with the visible line breaks and the byte order mark left out, is:
Player;Points;Note;Date
Ana;1200;"said ""hi""";2026-10-08 14:30:00
Bruno;950;"two
lines";2026-10-07 00:00:00
Reading
CsvReader reads from a file, a Stream (UTF-8), a TextReader, or text in memory (CsvReader.FromText(text)). CsvReader.Parse(text) reads a whole text into a list of string[] rows.
- Rows end at
\r\n,\nor\routside quotes. A field that starts with a double quote runs to the next double quote that is not doubled, and may contain delimiters and line breaks. Characters between a closing quote and the next delimiter are kept as they are. A quote that is never closed ends at the end of the input. - The reader never throws for malformed text.
- A byte order mark at the start is skipped.
- A line break at the very end of the input does not make an extra row. An empty line elsewhere is a row without fields.
- Every non-empty field is a text cell. Convert it with
AsDouble,AsInt,AsBoolandAsDateTime, which use the invariant culture. An empty field is an empty cell. FieldCountis the exact number of fields of the row, trailing empty fields included.CellCountis the index of the last non-empty field plus one.GetField(column)returns the string,""for an empty field or a column beyond the row.RowIndexcounts every row from 0, empty lines included.- Streams and files are read as UTF-8.
using System.Collections.Generic;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class CsvImport : MonoBehaviour
{
[SerializeField] private TextAsset csvAsset;
private void Start()
{
// 1. A file written with a semicolon. The reader skips a byte order mark.
string path = Path.Combine(Application.persistentDataPath, "scores.csv");
var options = new CsvOptions { Delimiter = ';' };
using (var csv = new CsvReader(path, options))
{
while (csv.ReadRow())
{
string player = csv.GetField(0); // always a string, "" when empty
int points = csv[1].AsInt(); // every non-empty field is a text cell
bool hasNote = csv.CellCount > 2;
Debug.Log("Row " + csv.RowIndex + ": " + player + ", " + points + ", note: " + hasNote);
}
}
// 2. Text already in memory.
using (CsvReader fromText = CsvReader.FromText(csvAsset.text, options))
{
fromText.ReadRow();
Debug.Log("The first row has " + fromText.FieldCount + " fields.");
}
// 3. The whole text as arrays of strings.
List<string[]> rows = CsvReader.Parse(csvAsset.text, options);
Debug.Log("Rows: " + rows.Count);
}
}
Opening a .csv file in a spreadsheet application
- Delimiter. An application set to a language that writes the decimal comma often expects a semicolon between fields. Set
Delimiter = ';'. - Byte order mark. Some applications recognise UTF-8 only when the file starts with a byte order mark. Set
WriteBom = truewhen you write a file or a byte array, so accented characters are not garbled. - Numbers and dates. They are written with a decimal point and with
DateFormat, whatever the language of the device. An application that reads the file with the user's own settings may show them differently. If the file is for people in several languages, an .xlsx file avoids the question. - Text that starts with
=,+,-or@. Applications treat it as a formula (some also when a tab or a carriage return comes first). The package does not escape it: do not export text you did not write without checking it or prefixing it, with an apostrophe for example. - A first header named
ID. Some spreadsheet applications take a text file that starts with the two capitalsIDfor another format (SYLK) and show a warning before they open it.QuoteAll,WriteBomor another header text (Id) avoids it. This comes from general knowledge of those applications and was not tested here. - Applications. How Microsoft Excel, LibreOffice and Google Sheets treat these settings was not tested.
The typed mapping: SheetMap
SheetMap<T> describes once how objects of type T become rows and how rows become objects again. One call to Column per column: a header, a getter, and optionally a setter, a number format and a width.
using System;
using System.Collections.Generic;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class HighScore
{
public string Player;
public int Points;
public DateTime AchievedAt;
public bool Verified;
}
public class HighScoreExport : MonoBehaviour
{
// The map describes the columns once. It holds no data and can be reused.
private readonly SheetMap<HighScore> map = new SheetMap<HighScore>()
.Column("Player", s => s.Player, (s, c) => s.Player = c.AsString(), width: 20)
.Column("Points", s => s.Points, (s, c) => s.Points = c.AsInt(), SheetNumberFormats.Thousands)
.Column("Achieved at", s => s.AchievedAt, (s, c) => s.AchievedAt = c.AsDateTime(), SheetNumberFormats.Date, 14)
.Column("Verified", s => s.Verified, (s, c) => s.Verified = c.AsBool());
private void Start()
{
var scores = new List<HighScore>
{
new HighScore { Player = "Ana", Points = 12000, AchievedAt = new DateTime(2026, 10, 8), Verified = true },
new HighScore { Player = "Bruno", Points = 9500, AchievedAt = new DateTime(2026, 10, 7), Verified = false }
};
string folder = Application.persistentDataPath;
// Write: a file, a byte array, CSV text and a CSV file.
map.SaveXlsx(Path.Combine(folder, "highscores.xlsx"), scores, "Scores");
byte[] xlsx = map.ToXlsx(scores, "Scores");
string csv = map.ToCsv(scores);
map.SaveCsv(Path.Combine(folder, "highscores.csv"), scores);
// Read the rows back into new objects.
List<HighScore> fromXlsx = map.ReadXlsx(xlsx, () => new HighScore());
List<HighScore> fromCsv = map.ReadCsv(csv, () => new HighScore());
Debug.Log(fromXlsx.Count + " rows from xlsx, " + fromCsv.Count + " rows from csv.");
}
}
Declaring columns
Column(header, get, set = null, numberFormat = null, width = 0)
headeris the text of the header cell and also the key that finds the column when reading. Headers are compared ignoring case and surrounding spaces. A null header throwsArgumentNullException; a blank or repeated one throwsArgumentException.getreturns the value of one object. Anything that converts to a cell can be returned directly:s => s.Name,s => s.Points,s => s.When. A nullgetthrowsArgumentNullException.setstores a cell into an object when reading, for example(s, c) => s.Points = c.AsInt(). Null makes the column write-only.numberFormatis a number format code for the column in .xlsx files, or null.widthis the column width in .xlsx files in characters, up to 255. 0 is the default width; a negative or larger value throwsArgumentOutOfRangeException.
Column returns the map, so calls chain. ColumnCount is the number of columns declared.
Properties
| Property | Default | Description |
|---|---|---|
HeaderStyle |
A style with Bold set |
The style of the header row in .xlsx files. Null writes the header without a style. |
FreezeHeader |
true |
WriteSheet keeps the header row in place while the rows scroll. |
AutoFilter |
true |
WriteSheet adds filter buttons to the header row. |
IgnoreMissingColumns |
false |
When reading, a column with a setter whose header is not in the file is skipped instead of throwing. A header row in which none of the mapped columns is found still throws. |
Writing
| Method | What it does |
|---|---|
ToXlsx(items, sheetName = "Sheet1", options = null) |
Returns the bytes of a workbook with one sheet. |
SaveXlsx(path, items, sheetName = "Sheet1", options = null) |
Writes a workbook with one sheet to a file. It writes to path plus .tmp first and puts that file in the place of path only when it is complete: if a getter, the items or the disk throws while it is written, the temporary file is deleted and an earlier file at path is left as it was. An earlier file is then replaced with File.Replace, which keeps it as path plus .old.tmp until the new file is in place and then deletes it (where File.Replace is not supported, the same two renames are made one after the other). If this last step fails, nothing is deleted: the earlier file is put back at path if it had been moved, the new data stays in path plus .tmp, and the IOException names both files. Existing files with those two names are overwritten. |
ToCsv(items, options = null) |
Returns CSV text. |
SaveCsv(path, items, options = null) |
Writes a UTF-8 .csv file, through a temporary file and with the same replacement step as SaveXlsx. |
WriteSheet(sheet, items) |
Fills a sheet of a workbook you are writing: column widths, number formats, the frozen header, the header row, one row per item, and the filter. The sheet must not have rows yet (InvalidOperationException otherwise). |
WriteRows(target, items) |
Writes the header row and one row per item to any ISheetRowWriter, with no layout. |
A null item is written as an empty row. A map with no columns throws InvalidOperationException. One cell buffer is reused for all the rows of a call.
WriteSheet lets you combine a mapped sheet with other sheets:
using System.Collections.Generic;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class MatchResult
{
public string Team;
public int Goals;
}
public class MatchReport : MonoBehaviour
{
private void Start()
{
var results = new List<MatchResult>
{
new MatchResult { Team = "Blue", Goals = 3 },
new MatchResult { Team = "Red", Goals = 1 },
new MatchResult { Team = "Green", Goals = 2 }
};
var map = new SheetMap<MatchResult>
{
HeaderStyle = new SheetStyle { Bold = true, FillColor = SheetColor.FromHex("#DDDDDD") },
FreezeHeader = true,
AutoFilter = false
};
map.Column("Team", r => r.Team, width: 18)
.Column("Goals", r => r.Goals);
string path = Path.Combine(Application.persistentDataPath, "match.xlsx");
using (var workbook = new XlsxWriter(path))
{
// The map fills the first sheet: widths, header, frozen row, rows.
map.WriteSheet(workbook.AddSheet("Results"), results);
// Another sheet is written with the sheet API.
XlsxSheetWriter summary = workbook.AddSheet("Summary");
summary.SetColumnWidth(0, 18);
string goals = "SUM(Results!" + SheetAddress.Range(1, 1, results.Count, 1) + ")";
summary.AddRow("Total goals", SheetCell.Formula(goals));
}
// The same rows can go to a CSV writer: WriteRows needs only an ISheetRowWriter.
using (var csv = new CsvWriter(Path.Combine(Application.persistentDataPath, "match.csv")))
{
map.WriteRows(csv, results);
}
}
}
Reading
ReadXlsx(bytes, create, sheetName = null), ReadCsv(text, create, options = null) and ReadRows(source, create) read objects back. create makes one empty object, for example () => new HighScore().
- The first row that has cells is the header row. Each column that has a setter is matched to the header cell with the same text, ignoring case and surrounding spaces. If the file repeats a header, the first one counts. Columns of the file that the map does not declare are ignored.
- A column with a setter that is not in the header row throws
SheetFormatExceptionnaming the header, unlessIgnoreMissingColumnsis true. The message also lists the header cells that were found. When none of the mapped columns is in the header row, the exception is thrown whateverIgnoreMissingColumnssays: that is a wrong delimiter, a wrong sheet or a title row above the headers, not an optional column. - Every later row that has at least one value becomes one object:
create(), then each matched column's setter receives its cell. An empty cell is passed when the row is shorter than the header. - An input with no rows gives an empty list.
ReadXlsxopens the named sheet (the first when null; a name that does not exist throwsArgumentException, and a workbook with no worksheet throwsSheetFormatExceptionwhen the name is null) and disposes the readers it opened.ReadRowsreads its source to the end and does not dispose it.- Reading needs a class: a struct
TthrowsInvalidOperationException, because the setters would change a copy. So does a map where no column has a setter, and acreatedelegate that returns null. Writing accepts structs too.
using System.Collections.Generic;
using Luanrobs.Sheets;
using UnityEngine;
public class InventoryItem
{
public string Name;
public int Quantity;
public double Price;
}
public class InventoryImport : MonoBehaviour
{
[SerializeField] private TextAsset workbookAsset;
private void Start()
{
var map = new SheetMap<InventoryItem>()
.Column("Name", i => i.Name, (i, c) => i.Name = c.AsString())
.Column("Quantity", i => i.Quantity, (i, c) => i.Quantity = c.AsInt())
.Column("Price", i => i.Price, (i, c) => i.Price = c.AsDouble());
// Headers are matched ignoring case and surrounding spaces. A header the file lacks
// throws SheetFormatException unless IgnoreMissingColumns is on.
map.IgnoreMissingColumns = true;
// The first sheet, or a sheet chosen by name.
List<InventoryItem> items = map.ReadXlsx(workbookAsset.bytes, () => new InventoryItem());
List<InventoryItem> weapons = map.ReadXlsx(workbookAsset.bytes, () => new InventoryItem(), "Weapons");
Debug.Log(items.Count + " items, " + weapons.Count + " weapons.");
// Any row reader works, for example one sheet of an open workbook. It is not disposed.
using (var workbook = new XlsxReader(workbookAsset.bytes))
using (XlsxSheetReader sheet = workbook.OpenSheet(0))
{
List<InventoryItem> again = map.ReadRows(sheet, () => new InventoryItem());
Debug.Log(again.Count + " rows read from " + sheet.Name);
}
}
}
Why the mapping does not need reflection
Managed code stripping in IL2CPP builds removes code that nothing visibly uses. A library that finds members by name at run time (GetProperty, Activator.CreateInstance, attribute scanning) can lose the members it looks for. Ahead-of-time compilers, IL2CPP and WebGL among them, also cannot generate code at run time.
SheetMap<T> finds nothing by name. Each getter and setter is a delegate that you write, a lambda or a method of your own code. A delegate is an ordinary reference, so the linker sees the code it points to and keeps it. Objects are made by your create delegate, not by Activator. The only use of the Type object in the package is a check that T is not a struct, which does not touch the members of your type. Nothing needs a link.xml.
The demo uses SheetMap<T> for its high-score table. It was built as a Windows IL2CPP player with the managed stripping level High and run through its scenes, and built as a WebGL build and run in a headless browser; both passed. On 2026-10-15 an Android IL2CPP build (managed stripping level High) ran through its scenes on two Android emulators and passed; see Platform support.
Where files go
Write to a path under Application.persistentDataPath: a folder that belongs to your app and needs no permission. Read it on the main thread and pass the string on if you write from another thread. The package does not create folders: the folder must exist.
| Platform | What Application.persistentDataPath is |
What to know |
|---|---|---|
| Windows | Typically %USERPROFILE%\AppData\LocalLow\<company>\<product> |
Company and product are the names in Player Settings. |
| macOS | Typically ~/Library/Application Support/<company>/<product> |
|
| Linux | Typically ~/.config/unity3d/<company>/<product> |
|
| Android | The app's own storage folder | No permission is needed to write there. The package has no share feature: to hand the file to the player or to another app you need the platform's share mechanism, which this package does not include. |
| iOS | The app's own folder in its sandbox | The same remark about sharing. |
| WebGL | The browser's virtual file system | The file is not on the player's disk. Giving it to the player needs a JavaScript download that this version does not include. |
| Editor | As the desktop platform of the Editor |
Unity's scripting reference for Application.persistentDataPath is the authority for the exact location on each platform and Unity version.
The demo shows the full path on screen after each export. In the Editor and in desktop players it also has buttons that open the file and the folder, only when clicked.
In the Editor
The package has no Editor assembly: its classes are the same in Edit mode and in Play mode, and an Editor script uses them directly. This menu item exports the scenes of the Build Settings to a file the user chooses:
using Luanrobs.Sheets;
using UnityEditor;
using UnityEngine;
public static class SceneListExport
{
[MenuItem("Tools/Export Scene List")]
private static void Export()
{
string path = EditorUtility.SaveFilePanel("Export the scene list", string.Empty, "scenes", "xlsx");
if (string.IsNullOrEmpty(path))
{
return;
}
using (var workbook = new XlsxWriter(path))
{
XlsxSheetWriter sheet = workbook.AddSheet("Scenes");
sheet.SetColumnWidth(0, 60);
sheet.FreezePanes(1, 0);
sheet.AddRow(new SheetStyle { Bold = true }, "Scene", "Enabled");
foreach (EditorBuildSettingsScene scene in EditorBuildSettings.scenes)
{
sheet.AddRow(scene.path, scene.enabled);
}
}
Debug.Log("Saved " + path);
}
}
Put the script in a folder named Editor. If it lives in an assembly definition, that assembly must reference Luanrobs.Sheets.
Threading
- The package starts no threads, tasks or coroutines. Every call runs on the thread that makes it.
- It uses no Unity API except the two colour structs
ColorandColor32in the implicit conversions toSheetColor. Writers and readers can be created and used in Edit mode and on any thread. - No instance is thread-safe. An instance can be created and used on any thread, one thread at a time. Different instances are independent: two threads can each write their own workbook.
SheetCellandSheetColorare immutable values. ASheetStyleis a mutable object: do not change it while another thread writes with it.- A
SheetMap<T>whose columns are declared can be used by several threads at once, because its methods do not change it. Declaring columns and setting its properties is not thread-safe. Your getters and setters run on the thread that calls the map, so they must not touch data that another thread changes at the same time, and no Unity object. - The package keeps no mutable static state. There is nothing to reset when you enter Play mode with Domain Reload disabled.
- WebGL has no threads. Use slices over several frames; see Large exports.
Error handling
The same rules apply to the whole package.
| Situation | Exception |
|---|---|
| A wrong argument: null, empty, out of range, a name or value that breaks a rule | ArgumentNullException, ArgumentOutOfRangeException or ArgumentException. When a writer or one of its sheets throws it, that writer is finished: see below. |
| A wrong order or state: layout after the first row, a sheet that is no longer the current one, a closed writer, a writer that failed, a sheet that is full | InvalidOperationException. |
| A reader that was disposed | ObjectDisposedException. |
| Input that is not a readable spreadsheet | SheetFormatException, with an English message that says what was found. |
| Stream and disk errors | The original IOException, UnauthorizedAccessException and so on. They are never caught or wrapped. |
| An output that would need ZIP64 | NotSupportedException. |
Nothing is logged by the package, and no exception is swallowed. The CSV reader is the one lenient parser: it never throws for malformed text.
Which exception a call throws is in the XML documentation of each member and in the API reference. The ones you are likely to meet:
- A text over 32,767 characters, a formula over 8,192, a link over 2,079:
ArgumentException. - A date cell before 1899-12-31:
ArgumentOutOfRangeException. - A count over 16,384 cells in one row, a negative count, a column or width out of range:
ArgumentOutOfRangeException. - A sheet name that breaks the rules, an overlapping merge, a missing sheet name in
OpenSheet(string):ArgumentException. SetColumnWidth,SetColumnStyleorFreezePanesafter the first row; any call on an earlier sheet:InvalidOperationException.ToArray()on a writer that has an output, orToText()on a CSV writer that has one:InvalidOperationException.
After a failure the writer is finished. After any exception thrown by a writer or by one of its sheets, an argument exception included, the output is incomplete and the writer can only be disposed. A row that was being added may already be partly in the output. Every method except Dispose then throws InvalidOperationException, and Dispose does not throw because of it and does not try to finish the workbook: it only releases the output. A file written to a path is left behind incomplete; delete it. A stream you passed with leaveOpen stays open and holds what was written so far. So check values before you write them, for example a date against 1900-01-01, instead of catching the exception and writing on.
Programming mistakes (wrong arguments, wrong order) are meant to throw, so that you fix them. What to catch is the input you do not control: a file chosen by a player, a download, a path on a disk that may be full.
using System;
using System.IO;
using Luanrobs.Sheets;
using UnityEngine;
public class SafeImport : MonoBehaviour
{
// Reads the first column of the first sheet of a file the player chose.
public bool TryLoad(string path)
{
try
{
using (var workbook = new XlsxReader(path))
{
if (workbook.SheetCount == 0)
{
Debug.LogWarning("The workbook has no worksheet.");
return false;
}
using (XlsxSheetReader sheet = workbook.OpenSheet(0))
{
while (sheet.ReadRow())
{
Debug.Log(sheet[0].AsString());
}
}
}
return true;
}
catch (SheetFormatException exception)
{
// Not an .xlsx file, damaged, or a feature that is not supported.
Debug.LogWarning("This file cannot be read as a workbook: " + exception.Message);
}
catch (IOException exception)
{
// Missing file, file in use, disk error: passed on unchanged.
Debug.LogWarning("The file could not be read: " + exception.Message);
}
catch (UnauthorizedAccessException exception)
{
Debug.LogWarning("No permission to read the file: " + exception.Message);
}
return false;
}
}
Platform support
The package is managed C# with no platform-specific code: no native plugin, no platform #if, no Android or iOS library. The platforms it was run on are in the table under Tested configurations; other platforms were not run. What differs between platforms is around the package, not in it:
| Platform | What to know |
|---|---|
| Windows, macOS, Linux (player and Editor) | Application.persistentDataPath is a normal folder. Application.streamingAssetsPath is a normal folder. |
| Android | Application.persistentDataPath is the app's own storage. Files inside StreamingAssets are not plain files: read them with UnityWebRequest, or ship the workbook as a TextAsset. |
| iOS | Application.persistentDataPath is the app's sandbox. Handing the file to another app needs the platform's share feature, which the package does not include. |
| WebGL | No threads: export on the main thread or in slices. Application.persistentDataPath is the browser's virtual file system, and a JavaScript download is needed to give the file to the player; this version has none. |
| Other platforms Unity builds for | Nothing is claimed. The package contains no platform-specific code. |
Tested configurations
Each row is one configuration, run on one Windows 11 machine (the Android rows on emulators started on it). The package was corrected on 2026-10-09 after a code review, and again on 2026-10-15 after a second review. A result dated 2026-10-15 was run on the package as it is now; a result dated 2026-10-09 was run between the two; every other row was run on 2026-10-08, before both, and was not repeated. A cell that says not run yet means that part has not been run, and nothing is claimed for it.
| Configuration | What is run | Result |
|---|---|---|
| EditMode tests, Unity 6000.3.12f1, Windows 11 Editor | The package's EditMode test suite. | Passed on 2026-10-15: 2100 of 2100 tests, among them the suites that run under the pt-BR and de-DE cultures. |
| Windows player, Mono | The demo built for this target and run through its scenes automatically, with the exported files read back. | Passed on 2026-10-09: all four scenes in a 1280 x 720 window, no input, 100,000 rows exported and read back. |
| Windows player, IL2CPP | The demo built for this target and run through its scenes automatically, with the exported files read back. | Passed on 2026-10-15, in Unity 6000.3.12f1: all four scenes in a 1280 x 720 window, no input, 100,000 rows exported and read back, with the default managed stripping level; the exported files are identical, byte for byte, to those of the Mono player. With the managed stripping level High it passed on 2026-10-09 and was not repeated. |
| Android, IL2CPP | The demo built for this target (ARM64 and x86-64, managed stripping level High) and run through its scenes automatically, with the exported files read back. | Passed on 2026-10-15, on two x86-64 emulators: Android 16 (API 36, Vulkan, 1080 x 2400) with an APK from Unity 6000.3.12f1 in the development project, and Android 7.0 (API 24, OpenGL ES 3, 1080 x 1920) with an APK from Unity 6000.0.84f1 in a new project with the package installed from a tarball. All four scenes, 100,000 rows exported and read back; the exported files were copied off the emulator and checked with openpyxl 3.1.5 and Python's csv module. A physical device and ARM64 code: not run yet. |
| Clean project, tarball install | The package packed as a tarball and installed in a new project made by Unity, with the Demo sample imported; EditMode tests, sample scenes, a Windows Mono player run through its scenes. | Passed on 2026-10-15, in Unity 6000.3.12f1 and in Unity 6000.0.84f1: 2100 of 2100 tests in each, the four scenes opened with no missing script, and the player run passed. The workbooks written by the tests (55) and by the players were checked with openpyxl 3.1.5 and read front to back from their local ZIP headers; the 33 compressed outputs of the tests were decompressed with Python's zlib. |
| WebGL build | The demo built for this target and run through its scenes automatically in a browser, with the exported files read back. | Passed on 2026-10-08 in headless Microsoft Edge 154 with a software renderer: all four scenes, 100,000 rows exported and read back. Other browsers and a real GPU: not run yet. |
| Declared minimum, Unity 6000.0.84f1 | Compile and EditMode tests in Unity 6000.0.84f1. | Passed on 2026-10-15: 2100 of 2100 tests in a new project with the package installed from a tarball, and the four sample scenes opened with no missing script. |
| Files written, checked with openpyxl 3.1.5 | Workbooks written by the tests and the demo, loaded and compared with openpyxl 3.1.5. | Passed on 2026-10-15, in Unity 6000.3.12f1 (the development project and a clean project) and in Unity 6000.0.84f1 (a clean project): in each, the 55 workbooks written by the tests were loaded, 50 of them compared with their expected cells, styles, widths, panes, merges, filters and links (the one with 100,000 rows loaded in read-only mode) and the other 5 checked for structure. In the two clean projects all 55 were also read front to back from their local ZIP headers with Python, and the 33 compressed outputs of the tests were decompressed with Python's zlib. The files the demo wrote in the two clean Mono players, in the Windows IL2CPP player of the development project and in the Android API 36 and API 24 players were checked the same way, the .csv with Python's csv module. |
| Files read, made with openpyxl 3.1.5 | Workbooks made with openpyxl 3.1.5, read with XlsxReader and compared with the expected values. |
Passed on 2026-10-09: 21 small workbooks, 9 made with openpyxl 3.1.5 and 12 assembled from XML strings, read and compared with values written into the tests. |
| Play mode with Domain Reload disabled | A script of the development project, not part of the package, enters Play mode three times in a row in the Unity 6000.3.12f1 Editor with Enter Play Mode Options on and Domain Reload disabled. In each session it writes the same .xlsx and .csv files through the public API (in memory, and saved to disk twice so that the second save replaces the first), reads them back, compares them with the files it wrote in Edit mode before the first session, and compares every static field of the package with its state before the first session. | Passed on 2026-10-15: in each of the three sessions the 13 files and the summary of what was read back were identical, byte for byte, to the Edit mode ones, and the 57 static fields of the package (compiler-generated caches included) were unchanged. Unity 6000.0.84f1 and the demo scenes in this mode: not run yet. |
The player runs used no input device: a driver walks the scenes, calls the scene controllers and reads the exported files back. The WebGL page ran in a headless browser on a software renderer, so it says nothing about speed on a real GPU. Files made by Microsoft Excel, LibreOffice and Google Sheets were not available on the test machine and were not tested. Files written by this package were not opened in those applications, and files made by them were not read. The reader tests use files made with openpyxl 3.1.5 and workbooks assembled from XML strings that imitate what other producers write.
What was tested and what was not
This is the state of version 1.0.0 on 2026-10-15. Everything that was run was run on one Windows 11 machine (Android on emulators started on it), in Unity 6000.3.12f1 and, for the declared minimum, Unity 6000.0.84f1. The package was corrected on 2026-10-09 after a code review and again on 2026-10-15 after a second review; what was run on the package as it is now is marked "after the second corrections", a result dated 2026-10-09, or 2026-10-15 without that mark, was run between the two, and the rest is from 2026-10-08 and was not repeated. The table under Tested configurations has the results per configuration. Nothing is claimed beyond this section.
What was run
- The EditMode test suite passed completely on 2026-10-15, after the second corrections, in Unity 6000.3.12f1 (in the development project and in a clean project) and in Unity 6000.0.84f1 (in a clean project): 2100 of 2100 in each. On 2026-10-09 it had passed with 2088 tests in both versions. It covers the DEFLATE compressor and decompressor, the ZIP code, the .xlsx writer and reader, CSV and
SheetMap<T>; a set of 552 test cases is run once under each of the pt-BR, de-DE and invariant cultures. Six tests check that the package keeps no mutable static state, two of them to prove that the checks can fail. - On 2026-10-15, after the second corrections, the files written by the tests (55 workbooks) in the development project and in the two clean projects were loaded with openpyxl 3.1.5, 50 of them compared with what was written and the other 5 checked for structure; in the clean projects all were also read front to back from their local ZIP headers with Python and the 33 compressed outputs were decompressed with Python's
zlib(the same checks had passed on 2026-10-09). 21 workbooks, 9 made with openpyxl 3.1.5 and 12 assembled from XML strings, were read back withXlsxReaderand compared. openpyxl 3.1.5 is the only third-party reader used. - The demo was built and run through its four scenes by an automatic driver as a Windows Mono player and a Windows IL2CPP player (also with managed stripping level High), all again on 2026-10-09 after the corrections, and as a WebGL build in headless Microsoft Edge 154 (on 2026-10-08 only). On 2026-10-15, after the second corrections, the Windows IL2CPP player of the development project (Unity 6000.3.12f1, default managed stripping level) was built and run again and passed, including the second .csv export over the first file. The files the Windows players exported were checked with openpyxl 3.1.5 and the csv module of Python; the 100,000-row file is identical, byte for byte, in the Mono and the IL2CPP player. The Windows screenshots were looked at.
- A project on Unity 6000.0.84f1 with the package and the imported sample compiled, opened the four scenes with no missing script or reference, and passed the same tests. The project was made new on 2026-10-08; on 2026-10-09 the corrected package and sample were copied into it and the run was repeated.
- On 2026-10-15, after the second corrections, the package was packed as a tarball and installed in two new projects made by Unity 6000.3.12f1 and Unity 6000.0.84f1 (their default packages, plus uGUI and the Test Framework), with the Demo sample imported. In each: 2100 of 2100 EditMode tests passed, the four sample scenes opened with no missing script, and a Windows Mono player built from the sample scenes ran through them and passed; its driver also exports the .csv a second time over the first file, which goes through the replacement step of
SaveCsv. The files written by the tests and the players were checked as above, and the CSV with Python's csv module. - On 2026-10-15 the demo ran through its four scenes as an Android IL2CPP player (managed stripping level High, ARM64 and x86-64) on two x86-64 emulators: Android 16 (API 36) with an APK from Unity 6000.3.12f1, whose minimum is API 25, and Android 7.0 (API 24) with an APK from Unity 6000.0.84f1, whose minimum is API 23. Both passed. Both runs were repeated after the second corrections and passed again, including the second .csv export over the first file: API 36 with a new APK from the development project, and API 24 with a new APK from Unity 6000.0.84f1, built in another new project with the package installed from a new tarball. The files exported were copied off the emulator, checked with openpyxl 3.1.5 and the csv module, and are identical, byte for byte, to the files of the Windows players. The screenshots were looked at.
- On 2026-10-15, after the second corrections, a script of the development project entered Play mode three times in a row in Unity 6000.3.12f1 with Domain Reload disabled. In each session the .xlsx and .csv files it wrote through the public API, and what it read back from them, were identical, byte for byte, to what it wrote in Edit mode before the first session, and every static field of the package was unchanged. The Enter Play Mode settings were put back afterwards.
What was not tested
- Android. Only x86-64 emulators at API 24 and API 36 were run; no physical device, no ARM64 code, and no other Android version. Nothing was touched or clicked on the emulator screen.
- Other systems. Windows 10 and other Windows machines or graphics APIs, macOS, Linux, iOS, and real phones were not run.
- Browsers. WebGL ran only in headless Microsoft Edge 154 with a software renderer. Chrome, Firefox, Safari and a real GPU were not tried. The exported file stays in the browser's virtual file system, so it was checked only by reading it back inside the player (4,491,352 bytes, the same size as in the Windows players), not with openpyxl.
- Other spreadsheet applications. No file made by Microsoft Excel, LibreOffice or Google Sheets was available. Files written by this package were never opened in them, and whether they open every file without a message is unproven.
- Domain Reload disabled. Play mode with Domain Reload disabled was run only in the Unity 6000.3.12f1 Editor on this machine, by the development-project script above, with Scene Reload left on. It was not run in Unity 6000.0.84f1 or with the demo scenes open. That the package keeps no mutable static state is also checked by tests that read every static field and compare them before and after full workloads.
- Input. The demo ran with the legacy input handling only and with no real pointer input; the button paths were exercised through the buttons' click events and the scene controllers. The Open file and Show folder buttons and the product link were never clicked.
- Clean projects. Only a tarball install in new Built-in projects was tried (2026-10-15). URP, a project with the Input System package and an install under
Assetswere not tried, and neither was the Input System branch of the demo at run time. - Review. A second independent review of the corrections of 2026-10-09 was done on 2026-10-15, by reading the code and running small programs built from the package's sources outside Unity. The corrections that followed it, on 2026-10-15: the shared strings limit also counts items, so a small file with millions of tiny or empty items is refused instead of filling memory;
SaveXlsxandSaveCsvno longer delete the earlier file before the new one is in place, and when the new file cannot take its place they keep both and say where each is; a cell that holds only a time in a 1904-system workbook is read on 1899-12-31 and written back as a time. The quadratic cost of several merges per row and the shared formula limit on large sheets are documented under Limitations and were not changed. These corrections were not reviewed again. - After the corrections. The WebGL build was made on 2026-10-08, before the corrections of 2026-10-09, and was not repeated. After the second corrections of 2026-10-15 the Windows IL2CPP player with the managed stripping level High was not built again (the IL2CPP player with the default level and the Android API 24 and 36 runs were), and
File.Replacewas not run on WebGL, where it may not be supported (the code then makes the same two renames itself). - Speed and memory. The figures in Large exports come from this one machine, which was busy with other work. They are indications, not a benchmark.
- Platform notes. The text on where
Application.persistentDataPathpoints on macOS, Linux, Android and iOS, and onStreamingAssetson Android, comes from general Unity knowledge and was not checked on those platforms. The sample import was reproduced by a script that copies the sample the way the Package Manager does, not through the Package Manager window.
Memory notes
- Writer. A sheet is not held as a whole. While it works the writer keeps the column settings, merges, links and filter of the current sheet, the styles, and, when
UseSharedStringsis true, a shared string table of at most 65,536 distinct texts and about 4 million characters; all of it is released when the workbook is closed or the writer is disposed, also when you keep the writer object. With no output (new XlsxWriter()), it also keeps the compressed file, andToArray()returns a new array each time. For a large export use a file or aStream, andUseSharedStrings = falsewhen the texts are mostly different. On WebGL a file is memory too:Application.persistentDataPathis held in the tab, so there a writer over your ownMemoryStreamholds the workbook once, where a file that is read back for a download holds it twice. - Reader.
new XlsxReader(bytes)wraps your array and does not copy it. A stream that cannot seek is copied into memory first. The reader holds the shared strings and the style table; sheet rows are read as you ask for them. The shared strings of a workbook are all loaded when it is opened, and a table of more than 134,217,728 characters, each item counted as its length plus 16 for the memory an item takes beyond its text (so at most 8,388,608 items), is refused withSheetFormatException. That keeps the table under about 256 MB of text and items on a 64-bit runtime, however many small or empty items a file holds.ReadAllRows()holds the whole sheet in memory, at about 48 bytes for every column up to the last used one of each row, and stops at 4,000,000 cells unless you pass another limit;SheetMap.ReadXlsxreads row by row and holds only the list of objects. UseReadRow()for a sheet you do not need all at once. - CSV. The writer and the reader stream.
ToText(),ToArray(),ParseandReadAllRowshold everything. - TextAsset. A workbook referenced by a
TextAssetin a scene is loaded with the scene, as any asset is. A large workbook is better read from a file or fromStreamingAssets. - Allocations.
SheetCellis a struct, so aSheetCell[]buffer that you reuse needs no array per row. A string you build for a cell is allocated by your own code.
Limitations
These are known and stated up front. The changelog has the same list; the README has the five that matter most.
- Out of scope in 1.0.0. Charts, images, pivot tables, conditional formatting, formula evaluation, password protection, the old binary
.xlsformat,.ods, cell comments, rich text inside one cell, Google Sheets or any online sync, and Editor importers that turn sheets into ScriptableObjects. - Also not included. Automatic column width, row heights, font name and size, vertical alignment, a WebGL browser-download helper, CSV formula-injection escaping, and encodings other than UTF-8 for streams and files.
- Limits. 1,048,576 rows and 16,384 columns per sheet; 32,767 characters per text, 8,192 per formula and 2,079 per link; 65,530 links per sheet; 64,000 different styles per workbook; column width up to 255; number format codes of up to 255 characters; sheet names of 1 to 31 characters, and not
History, a name spreadsheet applications reserve. Going past one throws an exception. When reading: at most 134,217,728 characters of shared strings in a workbook, where each item counts as its length plus 16 (so at most 8,388,608 items), and 4,000,000 cells in oneReadAllRows()call unless you pass a higher limit; past either the reader throwsSheetFormatException. - Large sheets.
MergeCellscompares a new range with every earlier range of the sheet when it does not start below all of them, which is the case for a second merge in the same row, so tens of thousands of such merges take seconds; one merge per row, from the top down, stays fast. When reading, a sheet keeps the first formula of each shared formula group up to 16,777,216 characters in all; past that, a cell that reuses a later group reports an emptyFormulaText, as a cell whose formula text the file does not give. - Formulas are stored, not calculated.
SheetCell.Formulawrites the formula text only. A spreadsheet application calculates it when it opens the file. This package's reader, and any reader that does not calculate, sees no value for it. - Set the layout before the first row. Column widths, column styles and frozen panes must be set before the first row of a sheet; a later call throws
InvalidOperationException. Only the sheet added last can be written to. - Styles, links, merged ranges and column widths are not read back. Cells from a reader have no style and no link, and a merged range is returned as plain cells with the value in its top-left cell.
- Dates. Only the 1900 date system is written. A date before 1899-12-31 cannot be stored in a date cell: writing one throws
ArgumentOutOfRangeException. 1899-12-31 itself is the day of a time without a date: a cell that holds only a time is read as that day and can be written again. This also holds for a workbook in the 1904 date system, so there a cell dated 1904-01-01 is read on 1899-12-31, with its time. Dates are stored as given, with no time zone conversion, and a date read from a text is the clock value as written, whateverZor offset follows it. - Numbers are doubles. Integers beyond 2^53 and decimals beyond about 15 significant digits are not kept exactly, in .xlsx and in .csv alike, because a number cell holds a double. Write 64-bit identifiers (Steam IDs, ticks) as text:
AsLong()reads a text that is a whole number exactly. - No ZIP64. Files of 4 GiB or more are not supported: the writer throws
NotSupportedExceptionand the reader throwsSheetFormatException. - The file type can be reported as a plain ZIP.
[Content_Types].xmlis the last entry of the archive, so a tool that guesses the file type from the first ZIP entry may report a generic ZIP archive. - CSV text that starts with
=,+,-or@is treated as a formula by spreadsheet applications when they open the file (some also when a tab or a carriage return comes first). The package does not escape it: check or prefix (with an apostrophe, for example) any text you did not write yourself. - CSV is culture-invariant. Numbers are always written with a decimal point and dates with
CsvOptions.DateFormat. An application that opens the file with the user's own number settings may show them differently. - WebGL. There are no threads, so export on the main thread or in slices over several frames.
Application.persistentDataPathis the browser's virtual file system, so giving the file to the player needs a JavaScript download that this version does not include. - Android StreamingAssets. Files inside
StreamingAssetsare not plain files: read them withUnityWebRequest, or ship the workbook as aTextAsset(.bytes) and passtextAsset.bytestoXlsxReader. - Other applications. Files made by Microsoft Excel, LibreOffice and Google Sheets were not available on the test machine and were not tested. Which configurations were run is listed under Tested configurations.
API reference
Namespace: Luanrobs.Sheets. Assembly: Luanrobs.Sheets.
If your scripts live in an assembly definition, add a reference to Luanrobs.Sheets. All row and column indexes are zero-based.
SheetCellKind
public enum SheetCellKind
| Value | Description |
|---|---|
Empty = 0 |
No value. A cell that only has a formula and no cached result is also empty. |
Text = 1 |
A string. Read it with Text. |
Number = 2 |
A double-precision number. Read it with Number. |
Boolean = 3 |
A boolean. Read it with Boolean. |
DateTime = 4 |
A date, a time or both. Read it with DateTime. |
Error = 5 |
A spreadsheet error such as #DIV/0!. The code is in Text. |
SheetCell
public readonly struct SheetCell : IEquatable<SheetCell>
One cell value, used to write rows and to read them back. Immutable.
| Member | Description |
|---|---|
static readonly SheetCell Empty |
A cell with no value; the same as default(SheetCell). |
const string DateTimeTextFormat |
yyyy-MM-dd HH:mm:ss, the format AsString() prints dates in. |
SheetCellKind Kind { get; } |
The type of the value. |
bool IsEmpty { get; } |
True when the cell has no value and no formula. |
string Text { get; } |
The string of a Text cell, or the code of an Error cell. Null for every other kind. |
double Number { get; } |
The value of a Number cell. 0 for every other kind. |
bool Boolean { get; } |
The value of a Boolean cell. False for every other kind. |
DateTime DateTime { get; } |
The value of a DateTime cell, with DateTimeKind.Unspecified. default(DateTime) for every other kind. |
string FormulaText { get; } |
The formula without the leading =, or null when the cell has no formula. A cell that reuses a shared formula has that formula moved to its own position. An empty string when the file gives no text for the formula, or when the sheet's shared formulas passed the limit given under Limitations (readers only). |
bool HasFormula { get; } |
True when the cell has a formula. |
SheetStyle Style { get; } |
The style used when the cell is written. Null on cells from a reader. |
string LinkUrl { get; } |
The address a click opens. Null on cells from a reader. |
static SheetCell Formula(string formula) |
A formula cell. One leading = is removed. ArgumentException when null, empty or only =. |
static SheetCell Link(string text, string url) |
A text cell with a link. A null text shows the address. ArgumentException when the address is null or empty. |
SheetCell WithStyle(SheetStyle style) |
A copy with the given style. Null removes it. |
SheetCell WithLink(string url) |
A copy with the given link. Null or empty removes it. |
string AsString() |
The value as a string for any kind. Never null. |
double AsDouble(double fallback = 0d) |
The value as a number, or the fallback. |
int AsInt(int fallback = 0) |
AsDouble rounded half away from zero, or the fallback when there is no number or it does not fit. |
long AsLong(long fallback = 0L) |
The same for 64-bit integers. |
bool AsBool(bool fallback = false) |
The value as a boolean, or the fallback. |
DateTime AsDateTime(DateTime fallback = default) |
The value as a date, or the fallback. |
Equals, ==, != and GetHashCode compare kind, value and formula text, not style or link. ToString() is AsString(). The conversion table is in Cells and conversions. Implicit conversions to SheetCell exist from string, char, double, float, int, uint, long, ulong, short, ushort, byte, sbyte, decimal, bool, DateTime and the nullable char?, double?, float?, int?, long?, decimal?, bool? and DateTime?.
SheetStyle
public sealed class SheetStyle
A mutable bag of properties. Not thread-safe. The properties and their defaults are in Styles and number formats.
| Member | Description |
|---|---|
SheetStyle() |
A style with every property at its default. |
bool Bold, bool Italic, bool Underline, bool Wrap |
Text and wrapping. Default false. |
SheetColor? FontColor, SheetColor? FillColor |
Colours. Default null. |
SheetBorders Borders |
The sides with a border line. Default None. |
SheetBorderLine BorderLine |
The thickness of the lines. Default Thin. |
SheetAlign Align |
Horizontal alignment. Default General. |
string NumberFormat |
A number format code. Null, empty and General mean none. Default null. |
SheetStyle Clone() |
A new style with the same values. |
SheetAlign, SheetBorders, SheetBorderLine
| Type | Values |
|---|---|
public enum SheetAlign |
General = 0, Left = 1, Center = 2, Right = 3 |
[Flags] public enum SheetBorders |
None = 0, Left = 1, Right = 2, Top = 4, Bottom = 8, All = 15 |
public enum SheetBorderLine |
Thin = 0, Medium = 1, Thick = 2 |
SheetColor
public readonly struct SheetColor : IEquatable<SheetColor>
| Member | Description |
|---|---|
byte R, G, B |
The components, 0 to 255. |
SheetColor(byte r, byte g, byte b) |
Creates a colour. |
static SheetColor FromHex(string hex) |
Parses RRGGBB or #RRGGBB. ArgumentNullException for null, FormatException for anything else. |
string ToHex() |
Six upper-case hexadecimal digits, RRGGBB. |
string ToString() |
ToHex() with a leading #. |
==, !=, Equals, GetHashCode |
Compare the three components. |
implicit operator SheetColor(Color32) |
Alpha is ignored. |
implicit operator SheetColor(Color) |
Components are clamped to 0..1; alpha is ignored. |
SheetNumberFormats
public static class SheetNumberFormats
String constants for SheetStyle.NumberFormat: General, Integer, Decimal2, Thousands, Thousands2, Percent, Percent2, Date, DateTime, Time and Text. The codes are in Styles and number formats.
SheetAddress
public static class SheetAddress
Converts between zero-based indexes and A1 notation. Thread-safe.
| Member | Description |
|---|---|
const int MaxRows |
1,048,576. |
const int MaxColumns |
16,384. |
static string ColumnName(int column) |
0 is A, 25 is Z, 26 is AA, 16383 is XFD. ArgumentOutOfRangeException outside 0..16383. |
static string Cell(int row, int column) |
A1 for (0, 0). ArgumentOutOfRangeException for an index out of range. |
static string Range(int firstRow, int firstColumn, int lastRow, int lastColumn) |
A1:C10. The corners may be given in any order. One cell gives a single address such as B2. |
static bool TryParseCell(string address, out int row, out int column) |
Parses B2, b2 or $B$2. False, with both indexes 0, when the text is not a single cell address inside the sheet limits. |
SheetCompression
public enum SheetCompression
| Value | Description |
|---|---|
Store = 0 |
No compression. A larger file. |
Fast = 1 |
DEFLATE with a short match search. The default. |
Compact = 2 |
DEFLATE with a longer match search: aims at a smaller file and takes longer to write. |
SheetFormatException
public sealed class SheetFormatException : Exception
Thrown by the readers when the data is not a spreadsheet the package can read: not a ZIP archive or not an .xlsx workbook, damaged, or using an unsupported feature such as a password or ZIP64. The message is in English and says what was found. Constructors: (string message) and (string message, Exception innerException). Stream and disk errors are not wrapped in it.
XlsxWriterOptions
public sealed class XlsxWriterOptions
| Member | Description |
|---|---|
SheetCompression Compression { get; set; } |
Default Fast. |
bool UseSharedStrings { get; set; } |
Default true. |
string DateFormat { get; set; } |
Default yyyy-mm-dd hh:mm:ss. ArgumentException for null or empty. |
CsvOptions
public sealed class CsvOptions
| Member | Description |
|---|---|
char Delimiter { get; set; } |
Default ,. ArgumentException for ", \r or \n. |
string NewLine { get; set; } |
Writer only. Default "\r\n"; only "\r\n" or "\n" (ArgumentException otherwise). |
bool WriteBom { get; set; } |
Writer only, byte outputs only. Default false. |
bool QuoteAll { get; set; } |
Writer only. Default false. |
string DateFormat { get; set; } |
Writer only. Default yyyy-MM-dd HH:mm:ss. ArgumentException for null or empty. |
ISheetRowWriter
public interface ISheetRowWriter
Something rows can be appended to. Implemented by XlsxSheetWriter and CsvWriter.
| Member | Description |
|---|---|
void AddRow(SheetCell[] cells, int count) |
Appends one row made of the first count cells. The array is not kept. |
ISheetRowReader
public interface ISheetRowReader
A forward-only reader of rows. Implemented by XlsxSheetReader and CsvReader.
| Member | Description |
|---|---|
bool ReadRow() |
Advances to the next row. False when there are no more. |
int RowIndex { get; } |
The zero-based position of the current row, or -1 before the first ReadRow(). Positions can have gaps. After ReadRow() has returned false, XlsxSheetReader gives -1 again and CsvReader keeps the number of the last row. |
int CellCount { get; } |
The index of the last non-empty cell of the current row plus one. 0 when there is no current row. |
SheetCell this[int column] { get; } |
The cell at a column. An empty cell at or beyond CellCount. ArgumentOutOfRangeException for a negative column. |
XlsxWriter
public sealed class XlsxWriter : IDisposable
Writes a workbook one sheet and one row at a time. Not thread-safe; usable on any thread, one at a time.
| Member | Description |
|---|---|
XlsxWriter(XlsxWriterOptions options = null) |
Builds the workbook in memory. |
XlsxWriter(string path, XlsxWriterOptions options = null) |
Writes a file, replacing one that exists. The folder must exist. ArgumentNullException for a null path, ArgumentException for an empty one. |
XlsxWriter(Stream output, XlsxWriterOptions options = null, bool leaveOpen = false) |
Writes to a stream that is writable and need not seek. Dispose closes the stream unless leaveOpen is true; Close does not. ArgumentNullException for null, ArgumentException for a stream that cannot be written. |
int SheetCount { get; } |
The number of sheets added. |
bool IsClosed { get; } |
True after Close() completed. |
XlsxSheetWriter AddSheet(string name) |
Finishes the sheet before and starts a new one. ArgumentNullException, ArgumentException for a name that breaks the rules, InvalidOperationException when closed or after a failure. |
void Close() |
Finishes the workbook. A workbook with no sheet gets Sheet1. Calling it again does nothing. InvalidOperationException after a failure. |
byte[] ToArray() |
Closes the writer if needed and returns the workbook. Only for a writer created without a stream or a path. InvalidOperationException otherwise. |
void Dispose() |
Calls Close() unless a call failed earlier, then releases the output. Never throws because of an earlier failure. |
XlsxSheetWriter
public sealed class XlsxSheetWriter : ISheetRowWriter
One sheet of a workbook being written, returned by AddSheet. It has no public constructor.
| Member | Description |
|---|---|
string Name { get; } |
The sheet name. |
int RowCount { get; } |
Rows written or skipped so far; the index of the next row. |
void SetColumnWidth(int column, double width) |
Before the first row. Width in characters, more than 0 and up to 255. |
void SetColumnStyle(int column, SheetStyle style) |
Before the first row. Null removes the style. |
void FreezePanes(int rows, int columns) |
Before the first row. Rows 0 to 1048575, columns 0 to 16383. |
void AddRow(params SheetCell[] cells) |
Appends a row. No arguments: an empty row. |
void AddRow(SheetStyle rowStyle, params SheetCell[] cells) |
Appends a row with a row style. |
void AddRow(SheetCell[] cells, int count) |
Appends the first count cells of a buffer. count from 0 to the buffer length and at most 16384. |
void AddRow(SheetCell[] cells, int count, SheetStyle rowStyle) |
The same, with a row style. |
void SkipRows(int count) |
Leaves the next rows empty. ArgumentOutOfRangeException for a negative count; InvalidOperationException past 1,048,576 rows. |
void MergeCells(int firstRow, int firstColumn, int lastRow, int lastColumn) |
Merges a rectangle. A single cell is ignored. ArgumentException for an overlap. |
void SetAutoFilter() |
Filter buttons on row 0 over the whole sheet, decided when the sheet is finished. |
void SetAutoFilter(int firstRow, int firstColumn, int lastRow, int lastColumn) |
Filter buttons on the first row of a rectangle. Replaces an earlier filter. |
AddRow throws ArgumentNullException for a null array; ArgumentOutOfRangeException for a bad count or a date before 1899-12-31; ArgumentException for a text over 32,767 characters, a formula over 8,192 or one with a character XML cannot store, a link over 2,079 or one with a control character, or a number format with a control character or more than 255 characters; InvalidOperationException when the sheet already has 1,048,576 rows or 65,530 links, the workbook would have more than 64,000 different styles, the sheet is no longer current, or the writer is closed.
XlsxReader
public sealed class XlsxReader : IDisposable
Reads the sheets of a workbook. Not thread-safe; usable on any thread, one at a time.
| Member | Description |
|---|---|
XlsxReader(string path) |
Opens a file; it stays open until disposed. |
XlsxReader(byte[] data) |
Opens a workbook in memory. The array is not copied. |
XlsxReader(Stream input, bool leaveOpen = false) |
Opens a stream. ArgumentException for a stream that cannot be read. |
int SheetCount { get; } |
The number of worksheets. Chart sheets are not counted. |
IReadOnlyList<string> SheetNames { get; } |
The worksheet names in workbook order, hidden sheets included. |
int FindSheet(string name) |
The zero-based index of the sheet, ignoring case, or -1. ArgumentNullException for a null name. |
XlsxSheetReader OpenSheet(int index) |
A new reader positioned before the first row. ArgumentOutOfRangeException, ObjectDisposedException, SheetFormatException. |
XlsxSheetReader OpenSheet(string name) |
The same by name, ignoring case. ArgumentNullException, ArgumentException when there is no such sheet. |
void Dispose() |
Releases the file or stream. Sheet readers opened from it can no longer be used. Calling it again does nothing. |
All three constructors throw SheetFormatException for data that is not a readable workbook; the first also throws ArgumentNullException or ArgumentException for a null or empty path.
XlsxSheetReader
public sealed class XlsxSheetReader : ISheetRowReader, IDisposable
Reads the rows of one sheet from top to bottom. It has no public constructor.
| Member | Description |
|---|---|
string Name { get; } |
The sheet name. |
bool ReadRow() |
Advances to the next row that has a value or a formula. ObjectDisposedException, SheetFormatException. |
int RowIndex { get; } |
The zero-based row position, or -1 before the first ReadRow() and after ReadRow() has returned false. |
int CellCount { get; } |
The index of the last cell with a value or a formula plus one. 0 when there is no current row. |
SheetCell this[int column] { get; } |
The cell at a column. ArgumentOutOfRangeException for a negative column. |
const long DefaultMaxCells |
4,000,000: the most cells ReadAllRows() holds. |
List<SheetCell[]> ReadAllRows() |
Every remaining row; the index of an entry is its row index; skipped rows are empty arrays. SheetFormatException past DefaultMaxCells cells. |
List<SheetCell[]> ReadAllRows(long maxCells) |
The same with a limit of your choice (1 or more; ArgumentOutOfRangeException otherwise). |
void Dispose() |
Stops reading this sheet. The workbook reader stays usable. |
CsvWriter
public sealed class CsvWriter : ISheetRowWriter, IDisposable
| Member | Description |
|---|---|
CsvWriter(CsvOptions options = null) |
Builds the text in memory. |
CsvWriter(string path, CsvOptions options = null) |
Writes a UTF-8 file, replacing one that exists. The folder must exist. |
CsvWriter(Stream output, CsvOptions options = null, bool leaveOpen = false) |
Writes UTF-8 text to a stream. |
CsvWriter(TextWriter output, CsvOptions options = null, bool leaveOpen = false) |
Writes to a text writer, which decides the encoding. WriteBom is ignored. |
int RowCount { get; } |
Rows written so far. |
void AddRow(params SheetCell[] cells) |
Appends a row. No arguments: an empty line. InvalidOperationException when closed. |
void AddRow(SheetCell[] cells, int count) |
Appends the first count cells of a buffer. |
string ToText() |
The text written so far, without a byte order mark. Only for a writer with no stream, path or text writer. |
byte[] ToArray() |
The text as UTF-8 bytes, with the byte order mark when WriteBom is true. Only for a writer with no stream, path or text writer. |
void Close() |
Flushes and stops accepting rows. |
void Dispose() |
Calls Close() and releases the output. |
CsvReader
public sealed class CsvReader : ISheetRowReader, IDisposable
| Member | Description |
|---|---|
CsvReader(string path, CsvOptions options = null) |
Opens a UTF-8 file; it stays open until disposed. |
CsvReader(Stream input, CsvOptions options = null, bool leaveOpen = false) |
Reads UTF-8 text from a stream, from its current position. |
CsvReader(TextReader input, CsvOptions options = null, bool leaveOpen = false) |
Reads from a text reader, which decides the encoding. |
static CsvReader FromText(string text, CsvOptions options = null) |
A reader over text in memory. |
static List<string[]> Parse(string text, CsvOptions options = null) |
A whole text as rows of strings; an empty field is "", never null. |
bool ReadRow() |
Advances to the next row. ObjectDisposedException when disposed. |
int RowIndex { get; } |
The zero-based number of the current row, empty lines included; -1 before the first ReadRow(). |
int FieldCount { get; } |
The exact number of fields of the current row. 0 for an empty line. |
int CellCount { get; } |
The index of the last non-empty field plus one. |
SheetCell this[int column] { get; } |
A text cell, or an empty cell for an empty field and beyond FieldCount. |
string GetField(int column) |
The field as a string; "" for an empty field or a column beyond the row. |
List<SheetCell[]> ReadAllRows() |
Every remaining row; each array has CellCount cells. |
void Dispose() |
Releases the input. |
SheetMap of T
public sealed class SheetMap<T>
| Member | Description |
|---|---|
SheetMap() |
A map without columns. |
int ColumnCount { get; } |
The number of columns declared. |
SheetStyle HeaderStyle { get; set; } |
The header style in .xlsx files. Default: bold. Null: none. |
bool FreezeHeader { get; set; } |
Default true. |
bool AutoFilter { get; set; } |
Default true. |
bool IgnoreMissingColumns { get; set; } |
Default false. A header row with none of the mapped columns throws either way. |
SheetMap<T> Column(string header, Func<T, SheetCell> get, Action<T, SheetCell> set = null, string numberFormat = null, double width = 0d) |
Declares the next column and returns the map. |
void WriteRows(ISheetRowWriter target, IEnumerable<T> items) |
Header row and one row per item, with no layout. |
void WriteSheet(XlsxSheetWriter sheet, IEnumerable<T> items) |
Layout, header and rows on an empty sheet. |
byte[] ToXlsx(IEnumerable<T> items, string sheetName = "Sheet1", XlsxWriterOptions options = null) |
A one-sheet workbook as bytes. |
void SaveXlsx(string path, IEnumerable<T> items, string sheetName = "Sheet1", XlsxWriterOptions options = null) |
A one-sheet workbook as a file, written through path plus .tmp (and path plus .old.tmp while an earlier file is replaced); a failure leaves an earlier file at path and never deletes the new data. ArgumentException for an empty path; IOException naming the files when the new file cannot take the place of the old one. |
string ToCsv(IEnumerable<T> items, CsvOptions options = null) |
CSV text. |
void SaveCsv(string path, IEnumerable<T> items, CsvOptions options = null) |
A UTF-8 .csv file, written through path plus .tmp in the same way as SaveXlsx. ArgumentException for an empty path; IOException naming the files when the new file cannot take the place of the old one. |
List<T> ReadRows(ISheetRowReader source, Func<T> create) |
Objects from any row reader. The source is not disposed. |
List<T> ReadXlsx(byte[] data, Func<T> create, string sheetName = null) |
Objects from a sheet of a workbook; the first sheet when the name is null. |
List<T> ReadCsv(string text, Func<T> create, CsvOptions options = null) |
Objects from CSV text. |
The write methods throw ArgumentNullException for a null argument and InvalidOperationException when the map has no columns. The read methods throw ArgumentNullException for a null argument, InvalidOperationException for a struct T, a map with no setter or a create that returns null, and SheetFormatException for a missing column, and from ReadXlsx also for a workbook that has no worksheet when no sheet name is given. See The typed mapping: SheetMap.
Troubleshooting and FAQ
Cannot implicitly convert type 'Rank' to 'Luanrobs.Sheets.SheetCell'
The value is of a type that has no conversion to a cell, an enum for example. Convert it yourself in the getter and the setter: to its number and back, or with ToString() for a name.
using Luanrobs.Sheets;
public enum Rank
{
Bronze,
Silver,
Gold
}
public class RankedPlayer
{
public string Name;
public Rank Rank;
}
public static class RankedPlayerMap
{
// "s => s.Rank" does not compile: an enum does not convert to SheetCell.
// Convert it yourself, here to its number and back.
public static SheetMap<RankedPlayer> Create()
{
return new SheetMap<RankedPlayer>()
.Column("Name", p => p.Name, (p, c) => p.Name = c.AsString())
.Column("Rank", p => (int)p.Rank, (p, c) => p.Rank = (Rank)c.AsInt());
}
}
InvalidOperationException from SetColumnWidth, SetColumnStyle or FreezePanes
These calls are made after the first row. The file is written as a stream, so the head of the sheet is already written. Move them above the first AddRow. The same exception comes from any call on a sheet that is no longer the current one: write each sheet completely before you add the next.
ArgumentOutOfRangeException when writing a date
The date is before 1899-12-31, which a spreadsheet date cell cannot hold (1899-12-31 itself is the day of a time without a date). Check the date before you write it and write earlier dates as text; see Dates. After the exception the writer can only be disposed, so catching it and writing on does not work.
The spreadsheet application shows ##### in a date column
The column is too narrow for the date. The package does not size columns. Call SetColumnWidth before the first row.
A formula cell is empty in a preview, or in my own reader
The package stores the formula and no result. An application that calculates, such as a spreadsheet application, shows the result when it opens the file. A preview or a reader that does not calculate has nothing to show. With this package's reader, check HasFormula and FormulaText.
SheetFormatException: the data is an old .xls file or a password-protected workbook
Both are OLE compound files and are not supported. Save the file again as an .xlsx workbook without a password, and read that.
SheetFormatException: the data is not a ZIP archive
The bytes are not an .xlsx file. Check that the file was copied as binary, that a TextAsset was read with bytes and not text, and that a download completed. A file renamed from .csv or .xls is not an .xlsx file either.
My .xlsx is in StreamingAssets and File.ReadAllBytes fails on Android
StreamingAssets on Android is inside the app package. Use UnityWebRequest, or keep the workbook as a TextAsset renamed to .bytes. See Reading from StreamingAssets.
The export freezes the game
A large export on the main thread stands still until it ends. Use a background thread, or slices over several frames on WebGL. See Large exports.
On WebGL the file was written but I cannot find it
On WebGL Application.persistentDataPath is the browser's virtual file system, not a folder of the player. This version has no JavaScript download for it. See Where files go.
Accented characters are garbled when I open the .csv
The application did not recognise UTF-8. Set WriteBom = true in CsvOptions. If the columns are not split either, try Delimiter = ';'.
SheetFormatException: The header row (row 1) has no column named "X"
Thrown by a SheetMap<T> when the header of a column that has a setter is not in the header row of the file, ignoring case and surrounding spaces. The message ends with the header cells it did find. Fix the header, or set IgnoreMissingColumns to true to skip the column. The first row that has cells is taken as the header row: when a title row sits above the headers, read it away first (reader.ReadRow()) and call map.ReadRows(reader, create). When the row is listed as a single cell with ; or a tab inside, the file uses another delimiter: set CsvOptions.Delimiter. ReadCsv takes the CSV text, not a path. The variant "has none of the mapped columns" is thrown even with IgnoreMissingColumns, for the same causes.
SheetMap.ReadXlsx returns an empty list
The sheet has no row with values, or only a header row. Check the sheet name (the first sheet is read when it is null).
The row numbers I read do not match the list index
The reader skips rows that are empty or only formatted, and RowIndex is the position in the sheet. ReadAllRows() returns a list in which the index is the row index and skipped rows are empty arrays.
Do I need a link.xml, or anything for Domain Reload disabled?
No. The package uses no reflection, so it needs no link.xml, and it keeps no mutable static state, so there is nothing to reset.
An application reports a problem with a file this package wrote
Files made by Microsoft Excel, LibreOffice and Google Sheets were not available on the test machine, and files written by this package were not opened in them. If an application reports a problem, send the file and the application and its version to the address below.
Support
Email: luanrobs@gmail.com
When reporting a problem, please include your Unity version, the platform (and device model and OS version for a device), the exception with its message, and, when you can share it, a small file that shows the problem.
Online: https://luanrobs.com/sheet-maker/
Manual: https://luanrobs.com/sheet-maker/docs/
Changelog: https://luanrobs.com/sheet-maker/changelog/
I maintain and support this package myself. If it saves you time, a review on the Asset Store helps a lot. Thank you.