Skip to content

Export Large CSV Files Without Freezing the UI ​

Account directory with compact rows, an Export CSV control, and a Preparing CSV status panel.

A virtualized data grid can scroll smoothly through many records while still stalling during CSV export. Virtualization reduces rendered DOM nodes; it does not reduce the number of fields that must be serialized into a file.

To keep the interface responsive during a large client-side export, collect the intended records, serialize bounded batches in a Web Worker and assemble the result in order. Keep the main-thread work bounded, too. Merely making an export function async does not move its CPU work off the main thread.

RevoGrid Pro's ExportCsvWorkerPlugin implements this pipeline for loaded grid data. This article explains when it helps, when it does not, and how to measure it without treating total export time as the only metric.

What makes a CSV export expensive? ​

A CSV encoder has to inspect values, escape quotes and delimiters, handle line breaks, and assemble bytes or strings. Even if every row is already in memory, this work can monopolize the browser's main thread. The user notices unresponsive buttons and stalled scroll, not the number of rows currently rendered.

There are three separate costs:

StageWork
Resolve export dataDetermine rows, order, columns, headers and field mappings
SerializeEncode each cell, escape values, insert delimiters and construct file parts
DeliverAssemble the Blob, create a download or upload to another service

Putting the serialization stage in a worker does not make the other stages free. Sending a giant object graph to a worker can itself cause expensive structured cloning and extra memory use.

A bounded export pipeline ​

In the v4.4.3 implementation, the worker export captures the ordered row membership and column mapping from the grid stores, then creates one batch at a time.

text
Visible grid store rows + ordered columns
    |
    +--> write headers once
    |
    +--> project bounded batch to exported fields
              |
              +--> clone-safe primitive values --> worker formatter
              |
              +--> complex values / unavailable worker
                       --> main-thread formatter after yielding
    |
    v
Ordered Blob parts --> final CSV Blob --> download

The released implementation caps a batch at 2,048 rows and targets 16,384 cells per batch (at least one row, so a very wide single row can exceed that target). These are implementation details, not configurable API guarantees or benchmark results. Projecting the fields prevents unrelated row properties from entering the worker. The encoder awaits each worker result before requesting the next batch; it does not queue the entire dataset into worker messages.

Complex values use the main-thread formatter so they retain the existing CSV serialization behavior. If a worker cannot start or fails, subsequent formatting uses the bounded fallback and yields between batches. This reduces the size of individual main-thread jobs, but does not guarantee that each job finishes within a frame budget.

React implementation ​

Install RevoGrid Pro and the React data grid. The worker is an opt-in plugin. Use a single export in flight; this example displays progress as a busy state rather than inventing a percentage that the API does not expose.

tsx
import { useRef, useState } from 'react';
import { RevoGrid } from '@revolist/react-datagrid';
import { ExportCsvWorkerPlugin } from '@revolist/revogrid-pro';
import '@revolist/revogrid-pro/styles.css';

type Order = { id: string; customer: string; amount: number };
const plugins = [ExportCsvWorkerPlugin];
const columns = [
  { prop: 'id', name: 'Order ID', sortable: true },
  { prop: 'customer', name: 'Customer', sortable: true },
  { prop: 'amount', name: 'Amount', sortable: true },
];

export function OrdersGrid({ rows }: { rows: Order[] }) {
  const grid = useRef<HTMLRevoGridElement>(null);
  const inFlight = useRef(false);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  async function exportCsv() {
    if (inFlight.current) return;
    inFlight.current = true;
    setBusy(true);
    setError('');
    try {
      const exporter = (await grid.current?.getPlugins())?.find(
        plugin => plugin instanceof ExportCsvWorkerPlugin,
      );
      if (!exporter) throw new Error('CSV export is not ready');
      await exporter.exportFile({
        filename: 'orders',
        columnDelimiter: ',',
        bom: true,
      });
    } catch (reason) {
      setError(reason instanceof Error ? reason.message : 'Export failed');
    } finally {
      inFlight.current = false;
      setBusy(false);
    }
  }

  return (
    <>
      <button disabled={busy} onClick={() => void exportCsv()}>
        {busy ? 'Preparing CSV…' : 'Download CSV'}
      </button>
      {error && <p role="alert">{error}</p>}
      <RevoGrid ref={grid} style={{ height: 420 }} readonly filter
        columns={columns} source={rows} plugins={plugins} />
    </>
  );
}

For an upload or file validation instead of a download, use exportBlob(options). It returns null if the cancelable beforeexport event cancels the request. The event also lets the application replace the export data.

Deploy the worker asset alongside the distribution and allow it under your site's Content Security Policy worker-src directive. Test the production bundle, not just the dev server, since the asset URL and policy may differ.

What exactly goes into the file? ​

The worker export uses visible grid row and column order, including pinned sections; it excludes filtered or trimmed rows. Here visible refers to the logical grid view rather than just the virtualized viewport. On a remotely paged or infinite source, only loaded rows are available.

Row membership is captured at export start, but values are read as batches are processed. If the user or a remote update changes a cell during export, the file can include values from different moments. A read-only UI alone does not prevent server refreshes. If an exact snapshot is required, freeze the relevant source revision or export from a versioned immutable copy. For a full remote dataset, perform an authorized backend export against the query and a defined revision.

The final Blob still lives in browser memory. This implementation is not a streaming-to-disk writer or an unlimited-size export.

CSV quoting is also not protection against spreadsheet formula injection. If fields contain untrusted strings, define a CSV-to-spreadsheet safety policy for values starting with formula control characters. Preserve the difference between an intentional numeric negative value and a dangerous user-supplied formula-like string.

Measure responsiveness as well as export duration ​

A faster total export can still create an unacceptable input delay. Measure at least wall-clock export time, frame gaps, long tasks and the resulting byte length. Compare exactly the same data, export scope, headers and formatting options. Validate the output separately.

The following browser-side harness measures an exporter that returns a Blob. It does not include file-picker/download time. It uses the Long Tasks API where supported and samples animation frame gaps; the latter also reflects OS scheduling, refresh rate and other page activity.

ts
export async function measureCsv(run: () => Promise<Blob | null>) {
  const longTasks: number[] = [];
  let observer: PerformanceObserver | undefined;
  if (typeof PerformanceObserver !== 'undefined' &&
      PerformanceObserver.supportedEntryTypes.includes('longtask')) {
    observer = new PerformanceObserver(list => {
      for (const entry of list.getEntries()) longTasks.push(entry.duration);
    });
    observer.observe({ type: 'longtask' });
  }

  let maxFrameGapMs = 0;
  let previous = await new Promise<number>(requestAnimationFrame);
  let frame = 0;
  function tick(now: number) {
    maxFrameGapMs = Math.max(maxFrameGapMs, now - previous);
    previous = now;
    frame = requestAnimationFrame(tick);
  }
  frame = requestAnimationFrame(tick);
  const start = performance.now();

  try {
    const blob = await run();
    const exportMs = performance.now() - start;
    // Allow a frame and queued observer records to arrive after serialization.
    await new Promise<number>(requestAnimationFrame);
    await new Promise<void>(resolve => setTimeout(resolve, 0));
    if (observer) {
      for (const entry of observer.takeRecords()) longTasks.push(entry.duration);
    }
    return {
      exportMs,
      maxFrameGapMs,
      longTaskCount: observer ? longTasks.length : null,
      longestTaskMs: observer ? Math.max(0, ...longTasks) : null,
      bytes: blob?.size ?? null,
    };
  } finally {
    cancelAnimationFrame(frame);
    observer?.disconnect();
  }
}

After finding the plugin as in the React example, call measureCsv(() => exporter.exportBlob({ bom: true })). For a synchronous reference encoder, call it inside the same harness and wrap its returned text in a Blob. Ensure the baseline includes equivalent data collection and produces equivalent CSV bytes before comparing results.

Use deterministic fixtures at 10,000, 100,000 and 500,000 rows, with 8 and 32 exported columns. Include quoted text, delimiters, newline characters, Unicode and missing values. Run one cold trial and at least five warm trials per configuration; report median and range, along with browser, version, machine, CPU throttling, row count and file bytes. Run again with the worker asset blocked to measure the fallback. Parse the outputs with a CSV parser and assert row count, order, field values and BOM handling.

Do not infer a measured speedup from the batch size or from worker usage. The protocol above is a reproducible measurement recipe, not a published performance result.

How this differs from synchronous export APIs ​

AG Grid CSV export documents direct download and string-returning APIs, with controls for row and column scope. Compare export semantics as well as timing; these APIs have different option names and defaults. The documentation alone does not establish a cross-product responsiveness benchmark.

For your own application, a worker is useful for client-owned loaded data. A server job is usually more appropriate for exporting every matching record from a remote database, particularly when the resulting file is too large to hold comfortably in memory.

See the background CSV export guide for the plugin configuration. The grid-at-scale demo demonstrates virtualization independently of export; it is not a CSV benchmark. Try RevoGrid Pro to integrate the worker into your actual dataset and measure the effect.

For differences beyond CSV export, see RevoGrid vs AG Grid.