[前端] 读取Excel数据并上传
JS库:xlsx.full.min.js , axios.min.js
HTML :
1 <input type="file" id="fileUpload" class="form-control" data-show-preview="false">
JS :
1 var s_objson = null; //用于存储Excel数据 2 3 $(document).ready(function () { 4 document.getElementById('fileUpload').addEventListener('change', handleFile, false); 5 }); 6 7 function handleFile(e) { 8 try { 9 10 s_objson = null; 11 12 var files = e.target.files; 13 var i, f; 14 15 var reader = new FileReader(); 16 17 f = files[0]; 18 var name = f.name; 19 reader.onload = function (e) { 20 21 var data = e.target.result; 22 var workbook = XLSX.read(data, { type: 'binary' }); 23 var sheet0 = workbook.Sheets[workbook.SheetNames[0]]; //获取第一个Sheet 24 var excelData = XLSX.utils.sheet_to_json(sheet0); 25 //var excelData = XLSX.utils.sheet_to_json(sheet0, { range: 10 }); //指定从Excel第11行开始,第11行为列名 26 27 s_objson = excelData.map((elem) => { 28 //let objKey = Object.keys(elem); 29 return { 30 "属性名1": elem["对应的列名"], 31 "属性名2": elem["对应的列名"], 32 "属性名3": elem["对应的列名"] 33 }; 34 }); 35 }; 36 reader.readAsBinaryString(f); 37 } 38 catch (err) { 39 } 40 } 41 42 43 function Upload() { 44 45 if (s_objson == null) { 46 return; 47 } 48 49 $.ajax({ 50 type: "post", 51 url: "后端API的地址", 52 data: JSON.stringify(s_objson), 53 dataType: "json", 54 contentType: 'application/json;charset=UTF-8', 55 success: function (res) { 56 }, 57 error: function (xmlHttpRequest, textStatus, errorThrown) {} 60 }); 61 62 }
Controller:
1 [HttpPost] 2 public ActionResult UploadData([FromBody] List<对象类型> data) 3 { 4 try 5 { 6 //处理 7 return Json(new { status = true });13 14 } 15 catch (Exception ex) 16 { 17 return Json(new { status = false, msg = ex.Message }); 18 } 19 }