前端预览 Csv,Excel文件
kingcwt2022-07-27前端react antd
后端返回一个文件地址链接,然后前端预览,记录一下 简单的插件及其预览实现的代码
Csv 转换为Table 预览
/**
* SeriesModelDetail组件
* 只展示csv相关代码
*/
import { usePapaParse } from 'react-papaparse'
const SeriesModelDetail: React.FC<Props> = () => {
const { readRemoteFile } = usePapaParse()
const [columns, setColumns] = useState<any[]>([])
const [data, setData] = useState<any[]>([])
// 数据格式化为Table数据格式
const handleComplete = (file:{data:any[], meta:any, [propsName:string]:any}) => {
const column:any[] = []
Array.isArray(file?.meta.fields) && file?.meta.fields.forEach((item: any) => {
column.push({ title: item, dataIndex: item, key: item })
})
setColumns(column)
const newData:any[] = []
Array.isArray(file.data) && file.data.forEach((i, rowKey) => {
newData.push({ ...i, rowKey })
})
setData(newData)
}
//Csv
const analysisCsvData = () => {
// currentDocument.link 代表后端返回的远程文件地址链接
return (
readRemoteFile(currentDocument.link, {
header: true,
download: true,
complete: handleComplete
})
)
}
return (
<Table scroll={{ x: 800 }} rowKey={(item) => item.rowKey} columns={columns} dataSource={data}></Table>
)
}
export default SeriesModelDetail
Excel 转换为Table 预览
import { read, utils } from 'xlsx'
const SeriesModelDetail: React.FC<Props> = () => {
const [sheetColumnscolumns, setSheetColumns] = useState([])
const [rows, setRows] = useState([])
const analysisSheetData = async () => {
const wb = read(await (await fetch(currentDocument.link)).arrayBuffer(), { type: 'array', cellDates: true, cellNF: false, cellText: false })
const data:any = utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]], { header: 1, raw: false, dateNF: 'yyyy-mm-DD h:mm' })
setSheetColumns(data[0].map((r: any) => ({ dataIndex: r, title: r })))
setRows(data.slice(1).map((r: any[]) => r.reduce((acc, x, i) => {
acc[data[0][i]] = x
return acc
}, {})))
}
return(
<Table scroll={{ x: 800 }} rowKey={(item) => item.date} columns={sheetColumnscolumns} dataSource={rows}></Table>
)
}
其他预览库: