Angular_代码块_ Excel文件上传
前台Excel文件上传数据
————html
<nz-col nzXs="24" nzSm="6" nzMd="4" nzLg="4">
<se>
<button nz-button (click)="uploadExcel.click()"
style="color: white; background-color: rgb(48, 170, 48); border-radius: 5px">
<i nz-icon nzType="upload"></i>
<span>文件上傳</span>
</button>
<br />
{{filename}}
<input #uploadExcel type="file" id="inputFileurl" hidden (change)="readExcel($event)" />
</se>
</nz-col>
Excel文件上传数据前台数据sheet工具把文件解析为json数据
————js
//文件上传
readExcel(obj: any) {
const file = obj?.target?.files[0];
if (file.name.substring(file.name.length - 4) !== 'xlsx') {
this.msg.error('文件上传失败,请确认文件格式');
return;
}
const that = this;
this.ibitag = [];
this.filename = ""
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = function (e) {
const data = e?.target?.result;
const excelFile = XLSX.read(data, {type: 'binary' });
const str: any =
//读取excel第一页
//excelFile.Sheets[excelFile.SheetNames[0]]
XLSX.utils.sheet_to_json(excelFile.Sheets[excelFile.SheetNames[0]]);
for (let i = 0; i < str.length; i++) {
that.ibitag.push({
//str[i].这里写excel栏位
id: str[i].NO,
code: str[i].机种,
model: str[i].型号,
})
}
that.filename = file.name
}
}
文件解析后传到后台
//文件保存
saveTag() {
console.log(this.ibitag)
this.http.post(webApiUrls.holdlist.save, JSON.stringify(this.ibitag))
.subscribe(res => {
if (res.status == "200") {
this.msg.success(res.msg);
this.selectAllSn()
} else {
this.msg.error(res.msg)
this.selectAllSn()
}
})
}
后台接收存储数据
引入fastjson_jar包接收数json类型据
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
把接收到的json数据(JSONArray.parseArray(data, DpmOqcHoldList.class))方法转换成list集合
@PostMapping("save")
@Transactional
public JsonResult save(@RequestBody String data){
//前台data字符串数据利用方法JSONArray.parseArray(data, DpmOqcHoldList.class)转换为指定类型的集合
List<DpmOqcHoldList> datas = JSONArray.parseArray(data, DpmOqcHoldList.class);
int i=0;
for (DpmOqcHoldList e:datas){
i = dpmOqcHoldListDao.insertSelective(e);
}
if(i==0){
return new JsonResult(400,"插入失败请联系IT!");
}
return new JsonResult(200,"插入成功");
}