blob: c59525309f29ff9f4eefc41dfc89637914dd959c [file]
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import type { TableData } from './tableUtils';
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const EXCEL_EXTENSION = '.xlsx';
export const exportFile = async (tableData: TableData, type: 'csv' | 'xlsx') => {
if (!tableData?.rows || tableData.rows.length === 0) {
return;
}
const { saveAs } = await import('file-saver');
if (type === 'xlsx') {
const XLSX = await import('xlsx-js-style');
const wb = XLSX.utils.book_new();
const ws = XLSX.utils.aoa_to_sheet([tableData.columnNames, ...tableData.rows]);
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
const excelBuffer = XLSX.write(wb, {
bookType: 'xlsx',
type: 'array'
});
const blob = new Blob([excelBuffer], { type: EXCEL_TYPE });
saveAs(blob, `export${EXCEL_EXTENSION}`);
} else {
const separator = ',';
const header = tableData.columnNames.join(separator);
const rows = tableData.rows.map(row => row.join(separator));
const content = [header, ...rows].join('\n');
const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
saveAs(blob, `export.${type}`);
}
};