Create, Load, and Save Workbooks
- 13 minutes to read
The Spreadsheet Document API allows you to create workbooks, load existing documents, and save workbooks in different spreadsheet formats.
Create a Workbook
Use the parameterless Workbook constructor to create a workbook. The Workbook instance contains at least one worksheet in its Sheets collection. You cannot remove the last worksheet from the collection.
using DevExpress.Docs.Spreadsheet;
using Workbook workbook = new Workbook();
// Customize the workbook, then save or export it.
Note
The Workbook class implements IDisposable. Use a using statement in C# or a Using statement in VB.NET to release workbook resources.
Load a Workbook
You can load a document from a stream or a byte array.
Load from a Stream
Pass a document stream to the Workbook constructor:
using System.IO;
using DevExpress.Docs.Spreadsheet;
using FileStream stream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(stream);
// Customize the workbook, then save or export it.
If you do not specify the document format, the API attempts to determine it automatically. If the API cannot determine the format, it throws an exception.
Specify the document format when you know the format of the source document:
using System.IO;
using DevExpress.Docs.Spreadsheet;
using FileStream stream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(stream, DocumentFormat.Xlsx);
// Customize the workbook, then save or export it.
Load from a Byte Array
Pass a byte array to the Workbook constructor:
using System.IO;
using DevExpress.Docs.Spreadsheet;
byte[] buffer = File.ReadAllBytes("Document.xlsx");
using Workbook workbook = new Workbook(buffer);
Specify the document format if automatic format detection is unavailable or unsuitable:
using System.IO;
using DevExpress.Docs.Spreadsheet;
byte[] buffer = File.ReadAllBytes("Document.xlsx");
using Workbook workbook = new Workbook(buffer, DocumentFormat.Xlsx);
Specify the Document Format
Use the DocumentFormat type to specify the document format.
The following table lists available formats:
| Format | Description |
|---|---|
DocumentFormat.Xls |
Microsoft Excel 97–2003 workbook format. |
DocumentFormat.Xlsx |
Microsoft Excel Open XML workbook format. |
DocumentFormat.Csv |
Comma-separated values format. |
DocumentFormat.Text |
Text format. |
DocumentFormat.Xlsm |
Microsoft Excel macro-enabled workbook format. |
DocumentFormat.Xlt |
Microsoft Excel 97–2003 template format. |
DocumentFormat.Xltx |
Microsoft Excel Open XML template format. |
DocumentFormat.Xltm |
Microsoft Excel macro-enabled template format. |
DocumentFormat.Xlsb |
Microsoft Excel binary workbook format. |
DocumentFormat.XmlSpreadsheet2003 |
Microsoft Excel 2003 XML Spreadsheet format. |
Warning
If the API cannot determine the document format automatically, it throws an exception. If the specified format does not match the actual document format, the API usually throws an exception (for example, if you load XLSX data as DocumentFormat.Xls). The API loads the document if the specified format is a related format (for example, DocumentFormat.Xlsm for XLSX data or DocumentFormat.Xlt for XLS data). If you specify the DocumentFormat.Csv or DocumentFormat.Text format, the API loads any content as text and does not throw an exception.
Specify Load Options
Pass a LoadOptions object to the Workbook(stream, options) or Workbook(buffer, options) constructor to specify the document format, formula calculation settings, and CSV and text file settings.
| Property | Description |
|---|---|
| DocumentFormat | Specifies the format of the source document. The default DocumentFormat.Undefined value enables automatic format detection. |
| CalculateOnLoad | Specifies whether to calculate formulas when the API loads the document. |
| CsvOptions | Specifies settings that the API uses to load CSV files. |
| TextOptions | Specifies settings that the API uses to load text files. |
If the CalculateOnLoad property is true, the API calculates formulas that have no stored results and all formulas in a document marked as not calculated. Formulas with stored results keep these results. To recalculate all formulas, call the Workbook.CalculateFull method after you load the document.
The following code snippet loads an XLSX document and calculates formulas in the workbook:
using System.IO;
using DevExpress.Docs.Spreadsheet;
LoadOptions loadOptions = new LoadOptions() {
DocumentFormat = DocumentFormat.Xlsx,
CalculateOnLoad = true
};
using FileStream stream = File.OpenRead("Document.xlsx");
using Workbook workbook = new Workbook(stream, loadOptions);
// Customize the workbook, then save or export it.
Load CSV and Text Files
LoadOptions.CsvOptions and LoadOptions.TextOptions properties provide access to CSV and text file load settings. Use the following settings to specify how the API reads the file:
| Property | Description |
|---|---|
| Delimiter | Gets or sets the character that separates values in a row. |
| TextQualifier | Gets or sets the character that encloses values in the loaded file. |
| Encoding | Gets or sets the character encoding of the loaded file. |
| AutoDetectEncoding | Gets or sets whether the API detects the character encoding of the loaded file. |
| Culture | Gets or sets the culture that the API uses to parse numbers and dates in the loaded file. |
| DetectValueTypes | Gets or sets whether the API detects numbers, dates, and Boolean values in the loaded file. |
| ColumnTypes | Gets data types for individual columns in the loaded file. |
| ImportFormulas | Gets or sets whether the API loads values that start with an equal sign (=) as formulas. |
| StartRow | Gets or sets the number of rows to skip at the beginning of the file. |
| MaxRowCount | Gets or sets the maximum number of rows to load. |
| TrimBlanks | Gets or sets whether the API removes leading and trailing spaces from loaded values. |
The following code snippet loads a CSV file that uses semicolons as delimiters and commas as decimal separators, and displays the value of cell B2 in the console:
using System;
using System.Globalization;
using System.IO;
using DevExpress.Docs.Spreadsheet;
LoadOptions loadOptions = new LoadOptions() {
CsvOptions = new CsvLoadOptions() {
Delimiter = ';',
Culture = new CultureInfo("de-DE")
}
};
using FileStream stream = File.OpenRead("Document.csv");
using Workbook workbook = new Workbook(stream, loadOptions);
Worksheet worksheet = workbook.Worksheets[0];
Console.WriteLine(worksheet.Cells["B2"].Value);
To load data from a CSV or text file to an existing worksheet, call the Worksheet.Import(stream, options, topLeft) method.
The following code snippet imports data from a CSV file to an existing worksheet, starting at cell A3, and saves the workbook to an XLSX file:
using System;
using System.Globalization;
using System.IO;
using DevExpress.Docs.Spreadsheet;
Directory.CreateDirectory("output");
using Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];
worksheet.Cells["A1"].Value = "Price List";
CsvLoadOptions csvOptions = new CsvLoadOptions() {
Delimiter = ';',
Culture = new CultureInfo("de-DE")
};
using (FileStream input = File.OpenRead("Document.csv")) {
// Import file data and get the cell range that contains the data.
CellRange imported = worksheet.Import(input, csvOptions, "A3");
Console.WriteLine($"Imported rows: {imported.BottomRowIndex - imported.TopRowIndex + 1}");
}
using FileStream output = File.Create(Path.Combine("output", "Document.xlsx"));
workbook.Save(output);
Save a Workbook
Use Workbook.Save methods to save a workbook to a stream or byte array. The API does not calculate formulas before it saves a workbook. To calculate formulas, specify save options.
Save to a Stream
Pass an output stream to the Save(Stream, DocumentFormat) method:
using System.IO;
using DevExpress.Docs.Spreadsheet;
using Workbook workbook = new Workbook();
// Customize the workbook.
using FileStream stream = File.Create("Document.xlsx");
workbook.Save(stream, DocumentFormat.Xlsx);
You can omit the DocumentFormat parameter. In this instance, the Spreadsheet Document API attempts to determine the format automatically. If the API cannot determine the format, it saves the workbook in the XLSX format.
using System.IO;
using DevExpress.Docs.Spreadsheet;
using Workbook workbook = new Workbook();
// Customize the workbook.
using FileStream stream = File.Create("Document.xlsx");
workbook.Save(stream);
Save to a Byte Array
Call Save(DocumentFormat) to save a workbook to a byte array in the specified output format:
using DevExpress.Docs.Spreadsheet;
using Workbook workbook = new Workbook();
// Customize the workbook.
byte[] buffer = workbook.Save(DocumentFormat.Xlsx);
If you do not specify the document format, the Spreadsheet Document API attempts to determine the format automatically. If the API cannot determine the format, it saves the workbook in the XLSX format.
Specify Save Options
Pass a SaveOptions object to the Workbook.Save(stream, options) or Workbook.Save(options) method to specify the output format, formula calculation settings, and CSV and text file settings.
| Property | Description |
|---|---|
| DocumentFormat | Specifies the output document format. The default DocumentFormat.Undefined value enables automatic format detection. |
| CalculateBeforeSave | Specifies whether to calculate formulas before the API saves the workbook. |
| CsvOptions | Specifies settings that the API uses to save CSV files. |
| TextOptions | Specifies settings that the API uses to save text files. |
If the CalculateBeforeSave property is true, the API calculates formulas that have outdated results. To recalculate all formulas, call the Workbook.CalculateFull method before you save the workbook.
Note
If the API skips calculation and the workbook contains outdated formula results, the API marks an XLSX, XLSM, XLTX, XLTM, or XLSB document as not calculated. Microsoft Excel recalculates formulas when it loads such a document. The Spreadsheet Document API calculates formulas in such a document if you set the CalculateOnLoad property to true or call a Workbook.Calculate() method. Other formats cannot store this mark. If you save a workbook in these formats without formula calculation, the document contains outdated formula results.
The following code snippet calculates formulas and saves a workbook to an XLSX file:
using System.IO;
using DevExpress.Docs.Spreadsheet;
using Workbook workbook = new Workbook();
// Customize the workbook.
SaveOptions saveOptions = new SaveOptions() {
DocumentFormat = DocumentFormat.Xlsx,
CalculateBeforeSave = true
};
using FileStream stream = File.Create("Document.xlsx");
workbook.Save(stream, saveOptions);
Save a Worksheet to a CSV or Text File
A CSV or text file stores data from a single worksheet. SaveOptions.CsvOptions and SaveOptions.TextOptions properties provide access to CSV and text file save settings. Use the following settings to specify the data to save and the output file format:
| Property | Description |
|---|---|
| Worksheet | Gets or sets the worksheet to save. |
| Range | Gets or sets the cell range to save. |
| Delimiter | Gets or sets the character that separates values in a row. |
| TextQualifier | Gets or sets the character that encloses values in the output file. |
| QuotationMode | Gets or sets when the API encloses values in text qualifiers. |
| Encoding | Gets or sets the character encoding of the output file. |
| WritePreamble | Gets or sets whether to write the encoding preamble (byte order mark) at the beginning of the file. |
| Culture | Gets or sets the culture that the API uses to format numbers and dates in the output file. |
| ExportFormulas | Gets or sets whether to save cell formulas instead of formula results. |
| ExportFormattedValues | Gets or sets whether to save cell values with number formats applied. |
| SkipHiddenRows | Gets or sets whether to exclude hidden rows from the output file. |
| SkipHiddenColumns | Gets or sets whether to exclude hidden columns from the output file. |
| RepeatMergedCellValues | Gets or sets whether to write the merged cell value to each cell position in a merged range. |
| TrimLeadingEmptyRowsAndColumns | Gets or sets whether to exclude empty rows and columns that precede worksheet data. |
| NewlineAfterLastRow | Gets or sets whether to write a line break after the last row. |
Note
If the workbook contains multiple worksheets and you do not specify the worksheet or cell range to save, Workbook.Save methods throw an InvalidOperationException.
The following code snippet saves the Products worksheet to a CSV file with semicolon delimiters and a UTF-8 byte order mark:
using System.IO;
using DevExpress.Docs.Spreadsheet;
Directory.CreateDirectory("output");
using Workbook workbook = new Workbook();
Worksheet products = workbook.Worksheets[0];
products.Name = "Products";
products.Cells["A1"].Value = "Product";
products.Cells["B1"].Value = "Price";
products.Cells["A2"].Value = "Chai";
products.Cells["B2"].Value = 18;
products.Cells["A3"].Value = "Chang";
products.Cells["B3"].Value = 19;
workbook.Worksheets.Add(new Worksheet("Notes"));
// A CSV file stores a single worksheet. Specify the worksheet to save.
SaveOptions saveOptions = new SaveOptions() {
CsvOptions = new CsvSaveOptions() {
Worksheet = products,
Delimiter = ';',
WritePreamble = true
}
};
using FileStream stream = File.Create(Path.Combine("output", "Document.csv"));
workbook.Save(stream, saveOptions);
Related APIs
| API | Description |
|---|---|
| Workbook() | Creates a workbook. |
| Workbook(Stream) | Creates a workbook from a document stream. |
| Workbook(Stream, DocumentFormat) | Creates a workbook from a document stream in the specified format. |
| Workbook(Byte[]) | Creates a workbook from a byte array. |
| Workbook(Byte[], DocumentFormat) | Creates a workbook from a byte array in the specified format. |
| Workbook(Stream, LoadOptions) | Creates a workbook from a document stream with the specified load options. |
| Workbook(Byte[], LoadOptions) | Creates a workbook from a byte array with the specified load options. |
| Save(Stream) | Saves the workbook to a stream. |
| Save(Stream, DocumentFormat) | Saves the workbook to a stream in the specified format. |
| Save(Stream, SaveOptions) | Saves the workbook to a stream with the specified save options. |
| Save() | Saves the workbook to a byte array. |
| Save(DocumentFormat) | Saves the workbook to a byte array in the specified format. |
| Save(SaveOptions) | Saves the workbook to a byte array with the specified save options. |