Excel文件数据转成JSON数据
Excel文件数据转成JSON数据
场景:如果你从后端请求得来的是一些excel文件,在前端使用的是json数据,那么如何把excel文件的内容转成json数据使用呢?如果有需要,就请阅读此篇文章,希望可以帮到你
安装包
- 1.package.josn
"dependencies": {
"xlsx": "^0.18.5",
"file-saver": "^2.0.5"
}
导入
import * as XLSX from 'xlsx';
utils.js 文件使用
export async function convertExcelFile(filePath){
let url = `api` //这里需要更换成实际场景中的接口地址
try {
const response = await axios.get(url, { responseType: 'arraybuffer' });
// Convert the response data to a Uint8Array
const data = new Uint8Array(response.data);
// Read the Excel file
const workbook = XLSX.read(data, { type: 'array' });
// Assuming you have only one sheet in the Excel file
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
// Convert sheet data to JSON
const jsonData = XLSX.utils.sheet_to_json(sheet, { header: 1 }); //数据是二维数组
// Extract headers from the first row
const headers = jsonData[0];
// Create an array of objects
const jsonArray = jsonData.slice(1).map(row => {
const obj = {};
headers.forEach((header, index) => {
obj[header] = row[index];
});
return obj;
});
return jsonArray
} catch (error) {
console.error('Error fetching data:', error);
}
}
备注:实际使用中如遇到问题或错误,欢迎评论区交流!