25 lines
936 B
TypeScript
25 lines
936 B
TypeScript
import { Capacitor } from '@capacitor/core'
|
|
|
|
function csvCell(v: string | number | null | undefined): string {
|
|
const s = v == null ? '' : String(v)
|
|
return '"' + s.replace(/"/g, '""') + '"'
|
|
}
|
|
|
|
// 导出 UTF-8 BOM 的 CSV,Excel 可直接打开中文不乱码;返回落盘位置(原生平台)
|
|
export async function downloadCsv(filename: string, rows: (string | number | null | undefined)[][]): Promise<string> {
|
|
const content = rows.map(r => r.map(csvCell).join(',')).join('\r\n')
|
|
const text = '\ufeff' + content
|
|
if (Capacitor.isNativePlatform()) {
|
|
const { downloadText } = await import('./download')
|
|
return downloadText(filename, text)
|
|
}
|
|
const blob = new Blob([text], { type: 'text/csv;charset=utf-8' })
|
|
const url = URL.createObjectURL(blob)
|
|
const a = document.createElement('a')
|
|
a.href = url
|
|
a.download = filename
|
|
a.click()
|
|
window.setTimeout(() => URL.revokeObjectURL(url), 10000)
|
|
return ''
|
|
}
|