TX Sheet Control

CSV, XML and JSON Data

Topic

CSV files, tabular XML and JSON records carry the values of one worksheet between TX Sheet Control and other applications. You exchange them through the central load and save APIs, which are available in the browser editor, the Angular integration, the Node.js server control and the .NET server control.

These formats transfer values only. They do not transfer formatting, tables, charts, dashboards, print settings or formula definitions: use XLSX or TXWB to retain workbook features. The APIs are included in the main editor and server packages, so no additional data package is required. There are no new ribbon commands for these formats.

How Tabular Import and Export Works

Each of the three formats has its own stream type:

FormatStream typeInput and output
CSVCSVUTF-8 delimited rows: comma by default, optionally semicolon or tab
XMLXMLUTF-8 tabular rows and scalar fields, not Excel 2003 SpreadsheetML
JSONJSONUTF-8 arrays of records or arrays of row arrays, not workbook JSON

A malformed or canceled load preserves the current workbook. Strings beginning with = remain literal data rather than executing as formulas.

Warning

The Workbook Is Replaced. A successful load replaces the entire workbook with one worksheet. Reacquire worksheet, range and cell handles after loading.

Pass Data, Format and Settings Separately

Every load follows the contract load(data, format, options), and the three arguments are separate:

  • The data, the first argument, is the only place for CSV, XML and JSON content.
  • The format, the second argument, selects the parser.
  • The options, the third argument, contain flat configuration only. Nested format wrappers and data fields in options are rejected.

Serialize JSON arrays and records with JSON.stringify before loading: this API exchanges tabular JSON text rather than workbook objects. The following calls load a customer as CSV, XML and JSON. editor is the initialized Spreadsheet of the browser editor, created as in JavaScript:

await editor.load('Customer;Amount\nMüller;125,5', StreamType.CSV, {
    sheetName: 'Orders', delimiter: ';', decimalSeparator: ','
});

await editor.load('<rows><row><Customer>Müller</Customer></row></rows>', StreamType.XML);
await editor.load(JSON.stringify([{ Customer: 'Müller', Amount: 125.5 }]), StreamType.JSON);

The code works as follows:

Byte input remains available for uploaded files. String input is supported only for the three tabular formats: XLSX and TXWB still require bytes in JavaScript. Strings are encoded as UTF-8 internally, and byte limits and event sizes use the encoded length, not JavaScript's character count.

Load and Save in the Browser

The browser editor and a standalone Workbook share the same methods:

  • load accepts CSV, XML and JSON text strings, Uint8Array or ArrayBuffer.
  • save returns UTF-8 bytes as Uint8Array.
  • saveText returns a string.

Supply a stream type explicitly rather than relying on a filename extension.

JavaScript

The following code imports a CSV file with a semicolon and a decimal comma, changes the worksheet and offers its values as a JSON download:

import { StreamType } from '@txtextcontrol/tx-sheet-control';

// editor is an initialized Spreadsheet instance.
await editor.load(await file.text(), StreamType.CSV, { delimiter: ';', decimalSeparator: ',', sheetName: 'Orders' });

const sheet = editor.workbook.sheets.get('Orders');
sheet.cell('B2').setValue(125.5);
sheet.range('A1:B1').format({ bold: true });

// Exchange values as readable JSON records. Formatting remains in the workbook.
const json = await editor.save(StreamType.JSON, { sheetName: 'Orders', pretty: true });
const url = URL.createObjectURL(new Blob([new Uint8Array(json)], {
    type: 'application/json;charset=utf-8'
}));

const link = document.createElement('a');
link.href = url;
link.download = 'orders.json';
link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);

The code works as follows:

TypeScript

TypeScript applications can use the public interfaces CsvLoadOptions, CsvSaveOptions, TabularLoadOptions, TabularSaveOptions and JsonSaveOptions. Pass format settings directly as the options argument: there is no csv, xml or json wrapper. The data always belongs in the first argument, and options never contain data.

import { StreamType, type CsvSaveOptions } from '@txtextcontrol/tx-sheet-control';

const options: CsvSaveOptions = {
    sheetName: 'Orders', range: 'A1:B2', delimiter: ';',
    decimalSeparator: ',', bom: true, lineEnding: '\r\n'
};

const csv = await editor.save(StreamType.CSV, options);
// Send csv bytes in a response or offer them as a browser download.

The code works as follows:

Load Data in an ASP.NET Core View

In ASP.NET Core, the Razor tag helper TXSheetControlTagHelper includes the editor assets and initializes the control. In the txsheetcontrolready event, use event.detail as the editor instance and call the same browser load and save APIs shown above. No server round trip is required for tabular import and export in the editor.

document.addEventListener('txsheetcontrolready', async (event) => {
    if (!(event instanceof CustomEvent) || !(event.target instanceof HTMLElement) || event.target.id !== 'orders-editor') return;

    const editor = event.detail;
    const { StreamType } = TXTextControl.TXSheetControl;
    const response = await fetch('/orders.json');

    if (!response.ok) throw new Error('The orders file could not be loaded.');

    await editor.load(await response.text(), StreamType.JSON, { sheetName: 'Orders' });
    editor.workbook.sheets.at(0).range('A1:B1').format({ bold: true });
});

The code works as follows:

  • The handler returns unless the event is a CustomEvent of the element with the ID orders-editor.
  • event.detail is the editor, and StreamType comes from TXTextControl.TXSheetControl.
  • fetch requests /orders.json. If the response is not OK, the handler throws an error.
  • load loads the text of the response as JSON into the worksheet Orders. SheetCollection.at returns the first worksheet, and format makes its range A1:B1 bold.

The solution's Razor sample has a CSV, XML & JSON sample link to /TabularData. It includes matching sample files, upload controls, CSV locale settings, JSON and XML export options and an API and text preview.

Load and Save From an Angular Component

Import the component TXSheetControlComponent from @txtextcontrol/tx-sheet-control/angular and the stream type from the main package. Call TXSheetControlComponent.load and TXSheetControlComponent.save on the initialized component, for example from an application button handler after the editor's ready event. No extra Angular data package is needed.

import { ViewChild } from '@angular/core';
import { StreamType } from '@txtextcontrol/tx-sheet-control';
import { TXSheetControlComponent } from '@txtextcontrol/tx-sheet-control/angular';

// Members of an Angular component whose template contains <tx-sheet-control>.
@ViewChild(TXSheetControlComponent) editor!: TXSheetControlComponent;

async importOrders(file: File): Promise<void> {
    await this.editor.load(await file.text(), StreamType.JSON, { sheetName: 'Orders', maxCells: 100000 });
}

async exportOrders(): Promise<Uint8Array> {
    return this.editor.save(StreamType.CSV, { delimiter: ';', bom: true });
}

The code works as follows:

  • The members belong to an Angular component whose template contains the tx-sheet-control element. @ViewChild makes the TXSheetControlComponent of this template available as editor.
  • importOrders loads the text of a file as JSON into the worksheet Orders and accepts at most 100,000 cells (LoadOptions.maxCells).
  • exportOrders returns the CSV bytes of the worksheet, with a semicolon as delimiter and a BOM.

Process Data in Node.js

Use @txtextcontrol/tx-sheet-control-server independently of the browser package. Filesystem access belongs to the application: the control accepts text or bytes and returns export bytes.

import { readFile, writeFile } from 'node:fs/promises';
import { ServerSheetControl, StreamType } from '@txtextcontrol/tx-sheet-control-server';

const control = new ServerSheetControl();

try {
    await control.load(await readFile('orders.json', 'utf8'), StreamType.JSON, { sheetName: 'Orders' });

    const sheet = control.workbook.sheets.get('Orders');
    sheet.cell('C1').setText('Total');
    sheet.cell('C2').setFormula('=B2*1.19');
    await writeFile('orders.xml', await control.save(StreamType.XML));
    await writeFile('orders.xlsx', await control.save(StreamType.SpreadsheetML));
} finally {
    control.destroy();
}

The code works as follows:

Process Data in .NET

Install TXTextControl.TXSheetControl.Server. The control and its Workbook expose two ways to load:

  • LoadTextAsync for CSV, XML and JSON content. LoadTextAsync never probes the filesystem.
  • LoadAsync with byte, filename and stream overloads. LoadAsync(string, ...) always means a filename.

Pass CsvLoadOptions or TabularLoadOptions, or the corresponding save options, directly, without wrapper objects. Caller-provided streams remain open. File saves replace the destination only after successful serialization.

using TXTextControl.TXSheetControl.Server;

await using var control = new ServerSheetControl();
await control.LoadTextAsync("Customer;Amount\nMüller;125,5", StreamType.CSV, new CsvLoadOptions {
        Delimiter = ";", DecimalSeparator = ",", SheetName = "Orders"
    });

var sheet = await control.Workbook.Sheets.GetAsync("Orders");
await sheet.Cell("B2").SetValueAsync(125.5);
await sheet.Range("A1:B1").FormatAsync(new { bold = true });
await control.SaveAsync("orders.json", StreamType.JSON, new JsonSaveOptions { SheetName = "Orders", Pretty = true });

using var xml = new MemoryStream();
await control.Workbook.SaveAsync(xml, StreamType.XML);
// xml remains open for further processing.

The code works as follows:

Cancel an Operation

Pass a CancellationToken to the .NET operation overload. In JavaScript and TypeScript, use the root signal option (LoadOptions.signal). Cancellation is checked before commit, and parsing does not partially apply rows.

Save Tabular Content as a String

Use saveText in JavaScript, TypeScript, Angular and Node.js. Its .NET counterpart is SaveTextAsync. Both accept the same flat export settings as save and SaveAsync, and both support CSV, XML and JSON only. The methods export the values and calculated results of one worksheet without changing the workbook.

// Browser editor; the same calls work on Workbook, the Angular component, or Node.js ServerSheetControl.
const csvText = await editor.saveText(StreamType.CSV, { delimiter: ';', decimalSeparator: ',' });
const xmlText = await editor.saveText(StreamType.XML, { range: 'A1:C10' });
const jsonText = await editor.saveText(StreamType.JSON, { pretty: true });

The code works as follows:

In .NET, call SaveTextAsync on the control or on its workbook:

using TXTextControl.TXSheetControl.Server;

string csvText = await control.SaveTextAsync(StreamType.CSV, new CsvSaveOptions
{
    Delimiter = ";", DecimalSeparator = ",", Range = "A1:C10"
});

string xmlText = await control.Workbook.SaveTextAsync(StreamType.XML);
string jsonText = await control.SaveTextAsync(StreamType.JSON, new JsonSaveOptions { Pretty = true });

SaveTextAsync returns the CSV of A1:C10 with the settings of a CsvSaveOptions object and indented JSON. Workbook.SaveTextAsync returns the XML.

The following applies to string export:

  • The BOM. String export omits a CSV BOM generated by bom: true or Bom = true, but a U+FEFF character stored in cell data is preserved. Byte and file exports continue to honor the BOM option.
  • The settings. The settings object is never changed.
  • Sizes. Size limits and the byte counts of progress and events use the UTF-8 export length, including any requested BOM, rather than the string's character count.
  • Events. The usual Saving and Saved, export progress, failure and cancellation behavior applies once per call.
  • Binary formats. These text methods reject XLSX, TXWB and PDF. Use save or SaveAsync for them.

The .NET server sample supports --tabular [output-directory] to load CSV text, calculate totals and save CSV, XML and JSON strings. Its README gives a runnable command.

How CSV Is Read and Written

CSV accepts double-quoted fields, escaped quotes (""), embedded line breaks, a leading UTF-8 BOM and CRLF, LF or CR record endings. Export uses CRLF by default; set lineEnding: '\n' for LF. bom: true adds a UTF-8 BOM for applications that require one.

Numbers, Booleans and Text

Numeric inference uses a period by default. For common German CSV files, use decimalSeparator: ',' together with delimiter: ';'.

  • Not inferred: thousands separators, dates and locale-formatted booleans.
  • Booleans: true and false become booleans.
  • Text: leading-zero identifiers and integers beyond JavaScript's safe integer range remain text.

Set inferTypes: false (LoadOptions.inferTypes) to keep every CSV field as a string.

Null Cells, Header Rows and Formulas

CSV has no representation that distinguishes a null cell from an empty string, and its text format does not retain scalar type metadata. For typed interchange, use JSON or XML.

Export includes every selected row, including its first row. SaveOptions.hasHeaderRow does not change CSV output.

By default, escapeFormulas: true (SaveOptions.escapeFormulas) prefixes formula-like text with an apostrophe for spreadsheet consumers. Set it to false when exact text exchange is required. Imported text is always literal, regardless of this export setting. Actual formulas export their calculated result, not their expression.

How JSON Is Read and Written

Record arrays generate a header row from the union of property names, in first-seen order. An array of records looks like this:

[
  { "Customer": "Müller", "Amount": 125.5, "Active": true, "Note": null },
  { "Customer": "Alpine", "Amount": 42, "Active": false, "Note": "=literal text" }
]
  • Missing properties become null cells.
  • JSON scalar types are retained. inferTypes does not convert JSON strings.
  • Nested objects and arrays inside a field are rejected.

Rows Instead of Records

Alternatively, load positional rows such as [["Customer","Amount"],["Müller",125.5]]. Export row arrays with { format: 'rows' } (SaveOptions.format): all selected rows are included, and hasHeaderRow is ignored in this mode. Use row arrays to retain an otherwise header-only selection, since an empty record array carries no schema.

Field Names of a Record Export

The default record export uses the first selected row as field names. Empty headings become Column1, Column2 and so on, and duplicate resulting names are rejected. Set hasHeaderRow: false to generate names and include the first selected row as data. Use pretty: true for readable JSON.

How XML Is Read and Written

XML export uses this row and field schema:

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <field name="Customer" type="string">Müller</field>
    <field name="Amount" type="number">125.5</field>
    <field name="Active" type="boolean">true</field>
    <field name="Note" type="null"/>
  </row>
</rows>
  • Field names are attribute values, so headings may contain spaces and punctuation.
  • Supported types are string, number, boolean and null.
  • Characters and line breaks are escaped as required.

XML Input

XML input also accepts named leaf fields, for example <Orders><Order><Customer>Müller</Customer><Amount>125.5</Amount></Order></Orders>. Untyped fields use numeric and boolean inference; disable it with { inferTypes: false }. Explicit field types are honored independently of inference.

  • Container elements accept child elements and whitespace, without data attributes.
  • Leaf fields accept name and type attributes, plus namespace declarations.
  • Rejected are nested field elements, duplicate field names, mixed container text, unsupported attributes and types, DTDs and external entities.

This is a tabular XML format, not a general XML-to-workbook mapper. Header selection follows the same rules as JSON record export.

Select the Worksheet and Range

Exports use the active worksheet unless sheetName selects another one. range selects an inclusive A1 rectangle, for example B2:E100. Without it, export includes A1 through the last populated cell: formatting alone does not extend the selection.

Formula values are calculated from a captured workbook without changing the live selection. Specify a range that covers spill results when you export dynamic arrays.

Set Limits for Input and Output

All formats use UTF-8 only. The default input and output limits are 32 MiB and 1,000,000 rectangular cells, including blanks. Load limits include 1,048,576 rows and 16,384 columns, and generated JSON and XML header rows count toward these limits.

Set LoadOptions.maxFileBytes, LoadOptions.maxCells, LoadOptions.maxRows and LoadOptions.maxColumns to bound application input. Larger byte and cell limits may be configured, up to 512 MiB and 100,000,000 cells. XML parsing additionally limits the decoded source to 32 MiB of characters.

Limits reject input and output rather than truncating it. Parsing and serialization run in memory, so leave memory and execution-time headroom for the workbook and the calculated values.

What Happens to Dates, Dashboards and Properties

Dates export their underlying cell values, commonly spreadsheet serial numbers. Date display formats are not transferred. Record exports require unique headings. JSON uses its standard number precision, so represent long identifiers and exact decimal strings as text when necessary.

If the workbook contains dashboards, set the root omitDashboards: true (SaveOptions.omitDashboards) to explicitly export worksheet data only. Use TXWB or ODS when dashboards must be retained. Document properties apply to document formats and are not serialized into CSV, XML or JSON.

Next Steps