anfra docs
anfra SDK

Export

Let readers download a query's whole result as a file

query.export() has the host make a file of a query's whole result and download it for the reader. Use it for a "Download CSV" button next to a table or chart.

query.export() comes from the export plugin. anfra serve installs it, but another host may not. Offer it only when the plugin is installed and the reader may export data:

if (Anfra.plugins.has('export') && Anfra.user.permissions.canExportData) {
  downloadButton.hidden = false
  downloadButton.addEventListener('click', async () => {
    try {
      await byRegion.export()
    } catch (err) {
      showError(downloadButton, err.message) // next to the button; see Errors below
    }
  })
}

What the file holds

The file holds every row of the query's result, not only the pages your page has loaded. It is run with the same inputs as the result on screen: the mapped controls, the cross-filter selection, the sort and the time zone. A control the reader changed but has not applied yet is not in it, so call app.execute() first if it should be.

Don't build a CSV from query.result.rows yourself. A paged result holds only the pages loaded, and export() gets the rest.

Values are written raw: numbers with every digit, dates in ISO 8601, and null as an empty cell. A large result takes as long to export as the query takes to run in full.

Options

const controller = new AbortController()
const file = await byRegion.export({
  filename: 'Revenue by region',                        // the extension is added
  format: 'csv',
  formatOptions: { header: 'labels', bom: true },
  signal: controller.signal,                            // an AbortController's signal, to cancel
})
// { url, filename, format, rowCount, expiresAt }

Every option is optional:

OptionDefaultDoes
filenameThe app's title and the query's name, such as Sales - byRegion.csvNames the file. The extension is added.
format'csv'The file format. CSV is the only one today.
formatOptions.header'labels'The header row: the columns' 'labels', as readers see them; their 'names', the keys in a result's rows, which stay stable for programs; or 'none'.
formatOptions.bomtrueStarts the file with a byte order mark, which Excel needs to read non-ASCII text.
signalCancels the export. query.abort() does not cancel it.

The promise resolves once the file is made and its download has started. export() changes nothing on the query: its state, result and error stay as they were.

Errors

export() rejects with the same error classes as a query, naming the query in entity: a QueryError for a bad option, or a TransportError when the server can't be reached. Show the failure next to the button, and leave the rest of the page as it is.

  • Plugins: checking that the host installed export.
  • Results: paging, and why result.rows may not hold every row.
  • Environment: Anfra.user.permissions.canExportData.

On this page