Skip to main content

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:

ParamTypeDefaultDescription
datastring[][]required2D array. First row treated as headers when namedRange = true.
targetstring"A1" on active sheetCell address ("B3"), sheet-qualified address ("Sheet2!C1"), or named range
namedRangebooleantrueWhen 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:

ParamTypeDescription
headersstring[]Column names. Controls the column order.
rowsobject[]Array of record objects. Missing fields are written as empty string.
targetstringSame as ksWrite.
namedRangebooleanSame 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:

ParamTypeDescription
base64stringBase64-encoded .xlsx file content
filenamestringFilename 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 Id column (configurable)
async ksQuery(soql, target?, options = {})Promise<QueryResult>

Parameters:

ParamTypeDefaultDescription
soqlstringrequiredAny valid SOQL query string
targetstring"A1"Write target — cell address or sheet-qualified address
options.hideIdbooleantrueWhether to hide the Id column
options.autofitbooleantrueWhether to auto-fit column widths after writing

Returns: { tableName: string, address: string, rowCount: number, totalSize: number }

  • rowCount — records actually written
  • totalSize — total records matching the query (may exceed rowCount if 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:

ParamTypeDescription
dataRangestringRange address, e.g. "Sheet1!A1:C10"
options.chartTypestringExcel chart type (e.g. "ColumnClustered", "Line", "Pie")
options.titlestringChart title
options.chartNamestringName for the chart object
options.sheetNamestringSheet to place the chart on
options.positionobject{ left, top, width, height } in points
options.xAxisTitlestringX-axis label
options.yAxisTitlestringY-axis label
options.showLegendbooleanShow legend (default true)
options.showDataLabelsbooleanShow 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:

ParamTypeDescription
labelsstring[]Category labels
series{ name: string, values: number[] }[]Data series
options.dataTargetstringWhere to write the data (default: active sheet A1)
options.chartTypestringSame as ksAddChart
options.chartPositionobjectSame as options.position in ksAddChart
All other optionsSame 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,
});