1.
<a onClick={this.uploadFileExcel}>
Template Import
</a>
2.
// 模板导入
@Bind()
templateImport(value) {
if (!value || !value.length) return;
value.map(item => {
this.props.CompoundDS.create({
"compoundId": item[`Compound ID`],
"mw": item[`FW`],
"fw": item[`MW`],
"batchId": item[`PharmaronLot`],
"purity": item[`Purity(%)`],
"storageCondition": item[`Storage Condition`],
})
})
}
// 上传文件(解析excel)
@Bind()
uploadFileExcel() {
readExcels(this.templateImport);
}
3.
import XLSX from "@/public/xlsx.core.min.js";
export async function readExcels(templateImport) {
if (!document.getElementById('readLocalFile')) { //如若已经有对应的dom元素直接点击,没有则add一个
let inputFile = document.createElement("input");
inputFile.setAttribute("id", "readLocalFile");
inputFile.setAttribute("type", "file");
inputFile.setAttribute("accept", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel");
inputFile.setAttribute("multiple", false); //是否可以多选。这里设置为否
inputFile.click();
document.body.appendChild(inputFile);
document.getElementById('readLocalFile').addEventListener('change', function (e) { //选择文件后执行
let files = e.target.files;
if (files.length == 0) return;
let file = files[0];
let reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function (e) { //处理load事件。读取操作完成时触发。
let data = e.target.result;
let workbook = XLSX.read(data, { type: 'binary' }); //XLSX:/xlsx.core.min.js 通过XLSX.read(data, {type: type})方法读取excel 后面介绍
let sheetNames = workbook.SheetNames; // 工作表名称集合
let worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
let json = XLSX.utils.sheet_to_json(worksheet); // 读取workbook 这里可以自己写方法输出表格 这里建议使用XLSX.utils.工具类输出数据 这里以json格式输出数据 还有其他格式 代码后介绍
templateImport(json); // templateImport为一个方法,这个方法中可以获取到解析的数据
if (typeof (callback) == "function") callback(json); //回调
document.getElementById('readLocalFile').value = null; //读取后清空
};
});
} else {
document.getElementById('readLocalFile').click(); //已有dom元素则点击
}
}
另一种方法
// 引入
import XLSX from "@/public/xlsx.core.min.js";
const file = ""; // 文件流
let reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function(e) {
let data = e.target.result;
let workbook = XLSX.read(data, { type: 'binary' })
let sheetNames = workbook.SheetNames; // 工作表名称集合
let worksheet = workbook.Sheets[sheetNames[0]];
let json = XLSX.utils.sheet_to_json(worksheet); // 解析结果
}