Skip to main content

Document Reading

Use context.document.read in a server-side Studio script to extract text from an uploaded document. It reuses the tenant Runtime's document parser. The first read parses the file and stores the result; subsequent reads of unchanged content reuse that result.

context.file.read returns the original bytes as Base64. context.document.read returns parsed text chunks, headings, captions, page references and a continuation position.

Read Excel or CSV by row and column​

Use context.document.readRows for original .xlsx or UTF-8 comma-separated .csv files. It reads the source table directly, rather than splitting the Markdown text returned by read.

In a form task button, replace excel_file with the attachment field API name:

export default async function main(
payload: FormButtonRuntimePayload,
context: StudioScriptContext,
) {
const files = payload.draft?.data?.excel_file;
const fileId = Array.isArray(files) ? files[0] : undefined;
if (typeof fileId !== 'string') throw new Error('Please upload a spreadsheet first.');

const page = await context.document.readRows({
fileId,
// sheetName: 'Sheet1', // Omit to use the first worksheet; CSV uses CSV.
headerRow: 1,
startRow: 2,
limit: 100,
});

return {
rows: page.rows.map(row => ({
rowNumber: row.rowNumber,
email: row.data['邮箱'],
number: row.data['数字'],
firstColumn: row.cells[0]?.value,
})),
nextStartRow: page.nextStartRow,
hasMore: page.hasMore,
};
}

row.data['邮箱'] looks up the exact trimmed source header, not a form field API name. row.cells[0] is column A; rowNumber and each cell's column start at 1. A row may look like:

{
"rowNumber": 2,
"data": {
"邮箱": "contact@solncn.com",
"数字": "120.5",
"多部门": "[\"department-1\",\"department-2\"]"
}
}

CSV values stay strings, including numbers, dates, JSON and identifiers with leading zeroes. Convert explicitly when required: Number(row.data['数字']) after checking for empty/invalid values, or JSON.parse(value) after verifying that the cell contains the expected JSON. Quoted commas, escaped quotes, a UTF-8 BOM and multiline cells are handled by the CSV parser without shifting columns. CSV row numbers refer to logical records, not physical lines inside multiline cells.

XLSX values retain numbers and booleans; dates use ISO strings. Formula cells return saved results and formula metadata; formulas are not recalculated. cells also exposes letter, header, type, displayText, merged and masterAddress.

Row read parameters and pagination​

ParameterDescription
fileIdRequired uploaded XLSX or CSV asset UUID
sheetNameExact worksheet name; defaults to the first worksheet. CSV uses CSV
headerRow1-based header row, default 1, maximum 1000
startRowFirst data row, strictly after headerRow; defaults to the next row, maximum 100000
limitRows per call, 1–1000, default 200

Results include fileAssetId, fileName, mimeType, sheetName, headerRow, startRow, endRow, rowCount, dataRowCount, columns, rows, hasMore and nextStartRow. Row counts include blank rows within the worksheet range. Retain the same file, worksheet and header settings when continuing:

const next = page.nextStartRow === null ? null : await context.document.readRows({
fileId,
sheetName: page.sheetName,
headerRow: page.headerRow,
startRow: page.nextStartRow,
limit: 100,
});

Limits: 20 MiB per file, 50 worksheets, 100000 rows and 200 columns per worksheet, and 1000000 total worksheet cells. Empty or duplicate trimmed headers reject with DATA_PROCESSING_SPREADSHEET_EMPTY_HEADER or DATA_PROCESSING_SPREADSHEET_DUPLICATE_HEADER. An unknown worksheet rejects with DATA_PROCESSING_SPREADSHEET_SHEET_NOT_FOUND; invalid CSV quoting rejects with DATA_PROCESSING_SPREADSHEET_INVALID_CSV; non-UTF-8 CSV rejects with DATA_PROCESSING_SPREADSHEET_CSV_UTF8_REQUIRED. Old .xls files must first be saved as .xlsx or UTF-8 CSV.

Reading returns data only. Writing rows into a form requires explicit field mapping and normal form SDK validation; the source file is unchanged.

Read a document​

export default async function main(
payload: StudioScriptRuntimeContextPayload,
context: StudioScriptContext,
) {
const fileId = payload.input.fileId;
if (typeof fileId !== 'string') throw new Error('A fileId is required.');

const result = await context.document.read({
fileId,
maxChunks: 20,
maxChars: 30000,
});

return {
filename: result.document.filename,
text: result.content.map((chunk) => chunk.text).join('\n\n'),
next: result.position.next,
};
}

Pass a real uploaded file asset ID from the current workspace, such as an attachment's asset ID. A file URL, conversation selection ID or external document ID is not a file asset ID. The Runtime supplies the execution identity and workspace; scripts cannot override these through the input.

Parameters​

ParameterTypeDescription
fileIdstringRequired file asset UUID
startChunknumberZero-based chunk index; default 0
startCharacternumberZero-based character offset within the first chunk; default 0
maxChunksnumberInteger from 1 to 50; default 20
maxCharsnumberInteger from 1000 to 100000; default 30000

Result and continuation​

FieldDescription
documentfileId, filename, mimeType, byte size, pageCount and chunkCount
contentChunks with chunkIndex, text, headings, captions, pageNumbers, characterStart, characterEnd and complete
position.hasMoreWhether unread content remains
position.next{ startChunk, startCharacter } for the next read, or null when finished

Chunk and character limits can split a chunk. Use both fields from position.next to avoid skipping or repeating text:

const first = await context.document.read({ fileId, maxChars: 10000 });
if (first.position.next) {
const next = await context.document.read({
fileId,
...first.position.next,
maxChars: 10000,
});
// Consume next.content and continue using next.position.next if needed.
}

Formats and execution​

Supported extensions include PDF, DOC/DOCX, XLS/XLSX/ODS, PPT/PPTX/ODP, ODT, CSV, TXT, Markdown, HTML, XML, JSON, YAML, common images, EPUB, EML, VTT and TeX. OCR and layout extraction depend on the deployed parser and source quality. Parsed chunks are a text representation, not the original editable file or guaranteed structured spreadsheet rows.

The file must be ready and within the deployed parser's size limit. Initial parsing of large or scanned files can take longer than a cached read. Configure an appropriate script execution timeout within the platform's allowed budget; do not assume parsing finishes within the default script timeout. Browser page assets call this method through a declared server action, not directly from client code.

Errors​

The method rejects on failure. Common error messages include:

CodeMeaning
SL_COMMAND_INPUT_INVALIDInvalid UUID, range, type or unknown input field
DOCUMENT_FILE_NOT_FOUNDThe file is absent from the current workspace
DOCUMENT_FILE_NOT_READYThe file is not ready to read
DOCUMENT_FORMAT_UNSUPPORTEDUnsupported file extension
DOCUMENT_FILE_TOO_LARGEThe configured parser size limit was exceeded
DOCUMENT_READ_POSITION_INVALIDThe requested continuation position is invalid

Parser availability and processing failures also reject the call; catch errors when the script needs to handle them explicitly.