使用axios通过oss的url获取.xlsx文件流,处理后得到json格式数据:
安装xlsx:
npm install xlsx
javascript
import axios from "axios";
import * as XLSX from "xlsx";
//#region xlsx(oss) to json
async function getFileStream(url) {
const response = await axios.get(url, { responseType: "blob" });
return response.data;
}
async function convertFileStreamToWorkbook(fileStream) {
const reader = new FileReader();
return new Promise((resolve, reject) => {
reader.onload = (event) => {
try {
const workbook = XLSX.read(event.target.result, { type: "binary" });
resolve(workbook);
} catch (error) {
reject(error);
}
};
reader.onerror = (error) => {
reject(error);
};
reader.readAsBinaryString(fileStream);
});
}
async function convertWorkbookToJson(workbook) {
const sheetName = workbook.SheetNames[0]; // 获取第一个工作表的名称
const worksheet = workbook.Sheets[sheetName]; // 获取第一个工作表对象
const jsonData = XLSX.utils.sheet_to_json(worksheet); // 将工作表对象转换为JSON对象
return jsonData;
}
export async function xlsxToJson(OSSUrl) {
const fileStream = await getFileStream(OSSUrl);
const workbook = await convertFileStreamToWorkbook(fileStream);
const jsonData = await convertWorkbookToJson(workbook);
return jsonData;
}
//#endregion
使用:
javascript
(async () => {
const json = await xlsxToJson(
"https://xxxxxxx.xlsx" // ossUrl
);
setAuthorDatas([...json]);
})();