KSExcel Reference
KSExcel is the class to extend when your LWC component needs to read or write data in Excel. All methods are async and return when the Excel operation completes.
Import
import { KSExcel } from 'kstone/api';
ksGetRange()
Returns the address of the currently selected range in Excel.
async ksGetRange() → Promise<string>
Returns: A sheet-qualified address string, e.g. "Sheet1!A1:C5".
Example:
const address = await this.ksGetRange();
this.targetRange = address; // "Sheet1!B2"
ksWrite(data, target?, namedRange?)
Writes a 2D array to a range. Optionally creates an Excel Table and named range.
async ksWrite(data, target?, namedRange = true) → Promise<WriteResult>
Parameters:
| Param | Type | Default | Description |
|---|---|---|---|
data | string[][] | required | 2D array. First row treated as headers when namedRange = true. |
target | string | "A1" on active sheet | Cell address ("B3"), sheet-qualified address ("Sheet2!C1"), or named range |
namedRange | boolean | true | When true, wraps data in an Excel Table and creates a named range |
Returns: { tableName: string | null, address: string, rowCount: number }
Example:
const result = await this.ksWrite(
[['Id', 'Name', 'Revenue'], ['001...', 'Acme', 500000]],
'Sheet1!A1'
);
console.log(result.tableName); // "KS_1714000000"
console.log(result.rowCount); // 1
ksWriteTable(headers, rows, target?, namedRange?)
Convenience wrapper around ksWrite. Accepts an array of record objects and a headers list — converts to the 2D format automatically.
ksWriteTable(headers, rows, target?, namedRange = true) → Promise<WriteResult>
Parameters:
| Param | Type | Description |
|---|---|---|
headers | string[] | Column names. Controls the column order. |
rows | object[] | Array of record objects. Missing fields are written as empty string. |
target | string | Same as ksWrite. |
namedRange | boolean | Same as ksWrite. |
Example:
const accounts = await getAccounts();
// accounts = [{ Id: '001...', Name: 'Acme', Industry: 'Tech' }, ...]
await this.ksWriteTable(
['Id', 'Name', 'Industry'],
accounts,
'Sheet1!A1'
);
ksInsert(base64, filename)
Inserts a base64-encoded .xlsx file as new sheets at the end of the active workbook.
async ksInsert(base64, filename) → Promise<{ success: true }>
Parameters:
| Param | Type | Description |
|---|---|---|
base64 | string | Base64-encoded .xlsx file content |
filename | string | Filename shown in any error messages |
Example:
const { base64 } = await this.ksCall('/api/docs/generate', { templateId, data });
await this.ksInsert(base64, 'AccountReport.xlsx');
ksSaveTables()
Reads all Excel Tables from the active worksheet and returns them as structured data.
async ksSaveTables() → Promise<SaveTablesResult>
Returns:
{
tables: [
{
tableName: 'KS_Accounts',
headers: ['Id', 'Name', 'Industry'],
rows: [['001...', 'Acme', 'Technology'], ...]
}
]
}
Example:
const { tables } = await this.ksSaveTables();
for (const table of tables) {
console.log(table.tableName, table.rows.length, 'rows');
}
ksQuery(soql, target?, options?)
Executes a SOQL query on Salesforce and writes the results to Excel as a formatted Table. The Keelstone server holds the Salesforce access token — your LWC never handles it directly.
The server automatically:
- Fetches field metadata from Salesforce to identify picklist fields and required fields
- Applies in-cell dropdown validation for picklist fields
- Highlights required field headers in yellow
- Auto-fits column widths
- Hides the
Idcolumn (configurable)
async ksQuery(soql, target?, options = {}) → Promise<QueryResult>
Parameters:
| Param | Type | Default | Description |
|---|---|---|---|
soql | string | required | Any valid SOQL query string |
target | string | "A1" | Write target — cell address or sheet-qualified address |
options.hideId | boolean | true | Whether to hide the Id column |
options.autofit | boolean | true | Whether to auto-fit column widths after writing |
Returns: { tableName: string, address: string, rowCount: number, totalSize: number }
rowCount— records actually writtentotalSize— total records matching the query (may exceedrowCountif SOQL has no LIMIT or Salesforce paginates)
Example:
const result = await this.ksQuery(
'SELECT Id, Name, AnnualRevenue, Industry FROM Account WHERE Industry = \'Technology\' LIMIT 200',
'Sheet1!A1',
{ hideId: false, autofit: true }
);
this.statusMessage = `${result.rowCount} records written`;
ksGetCellComments(address?)
Returns comments on a cell, or all comments in the workbook.
async ksGetCellComments(address?) → Promise<Comment[]>
Returns: Array of comment objects:
[{
id: 'comment-id',
address: 'Sheet1!A1',
text: 'First comment',
authorName: 'Matthew',
resolved: false,
replies: [{ id, text, authorName }]
}]
ksAddCellComment(address, text)
Adds a new comment to a cell.
async ksAddCellComment(address, text) → Promise<{ id: string, ok: true }>
ksReplyToCellComment(commentId, text)
Adds a reply to an existing comment.
async ksReplyToCellComment(commentId, text) → Promise<{ ok: true }>
ksResolveCellComment(commentId, resolved?)
Resolves or reopens a cell comment.
async ksResolveCellComment(commentId, resolved = true) → Promise<{ ok: true }>
ksDeleteCellComment(commentId)
Deletes a cell comment.
async ksDeleteCellComment(commentId) → Promise<{ ok: true }>
ksAddChart(dataRange, options?)
Creates a chart from an existing range already in the sheet. The chart is embedded in the worksheet.
async ksAddChart(dataRange, options = {}) → Promise<{ chartName: string, ok: true }>
Parameters:
| Param | Type | Description |
|---|---|---|
dataRange | string | Range address, e.g. "Sheet1!A1:C10" |
options.chartType | string | Excel chart type (e.g. "ColumnClustered", "Line", "Pie") |
options.title | string | Chart title |
options.chartName | string | Name for the chart object |
options.sheetName | string | Sheet to place the chart on |
options.position | object | { left, top, width, height } in points |
options.xAxisTitle | string | X-axis label |
options.yAxisTitle | string | Y-axis label |
options.showLegend | boolean | Show legend (default true) |
options.showDataLabels | boolean | Show data labels (default false) |
ksAddChartFromData(labels, series, options?)
Writes data arrays to the sheet and creates a chart from them in one call.
async ksAddChartFromData(labels, series, options = {}) → Promise<{ chartName: string, ok: true }>
Parameters:
| Param | Type | Description |
|---|---|---|
labels | string[] | Category labels |
series | { name: string, values: number[] }[] | Data series |
options.dataTarget | string | Where to write the data (default: active sheet A1) |
options.chartType | string | Same as ksAddChart |
options.chartPosition | object | Same as options.position in ksAddChart |
| All other options | — | Same as ksAddChart |
ksDeleteChart(chartName, sheetName?)
Deletes a chart by name.
async ksDeleteChart(chartName, sheetName?) → Promise<{ ok: true }>
ksListCharts()
Lists all charts across all sheets in the workbook.
async ksListCharts() → Promise<{ name: string, sheetName: string }[]>
ksCall(endpoint, body?)
Low-level method inherited from DocumentAPI. Call this when you need to hit a server endpoint that isn't covered by a named method.
async ksCall(endpoint, body = {}) → Promise<any>
Example:
const { base64, filename } = await this.ksCall('/api/docs/generate', {
templateId: this.selectedTemplate,
recordId: this.recordId,
});