parent
eb6db892d9
commit
ae03f4dc6e
@ -0,0 +1,33 @@ |
||||
import * as XLSX from 'xlsx';
|
||||
import { saveAs } from 'file-saver';
|
||||
|
||||
const EXCEL_TYPE = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
|
||||
const EXCEL_EXTENSION = '.xlsx'; |
||||
export function exportAsExcelFile(json: any[], excelFileName: string): void {
|
||||
const worksheet: XLSX.WorkSheet = XLSX.utils.json_to_sheet(json);
|
||||
const workbook: XLSX.WorkBook = { Sheets: { 'data': worksheet }, SheetNames: ['data'] };
|
||||
const excelBuffer: any = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
|
||||
saveAsExcelFile(excelBuffer, excelFileName);
|
||||
} |
||||
|
||||
export function saveAsExcelFile(buffer: any, fileName: string): void {
|
||||
const data: Blob = new Blob([buffer], {
|
||||
type: EXCEL_TYPE
|
||||
});
|
||||
saveAs(data, fileName + '_export_' + new Date().getTime() + EXCEL_EXTENSION);
|
||||
} |
||||
|
||||
export function convertKeys<Raw = any, Target = any>(excelData: Raw[], keysMap: Record<string, string>): Target[] { |
||||
return excelData.map(excelItem => { |
||||
const reorderedItem: any = {}; |
||||
|
||||
// 按照keysMap中定义的顺序重建对象
|
||||
Object.entries(keysMap).forEach(([originalKey, newKey]) => { |
||||
if (excelItem.hasOwnProperty(originalKey)) { |
||||
reorderedItem[newKey] = excelItem[originalKey]; |
||||
} |
||||
}); |
||||
|
||||
return reorderedItem; |
||||
}); |
||||
} |
Loading…
Reference in new issue