[英]Read and export excel file using javascript
我想使用 html 和 javascript 创建一个 web 页面,用户可以在其中上传 excel(.xlsx, .xls) 文件作为输入。
我是否需要使用 Node js 来做到这一点,或者是否可以使用 excel-js 库的一些 cdn 脚本标签,这对我不起作用(我不知道为什么)
<script src="https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.2.1/exceljs.min.js" integrity="sha512-DPjFYmSXYGB7/5k/Z4h5iw1i29Vl//jj3I7v79DRy+T0o4KssDku6Hf7ImlIV87KmNIh+euT5H0LJhQmTnbC/A==" crossorigin="anonymous"></script>
每当我尝试使用这个库的一些 function 时,它都会抛出错误
function excelChange (event) {
var input = event.target.files[0]
const workbook = createAndFillWorkbook();
const sheet = workbook.xlsx.writeFile(input);
console.log(sheet)}
我应该采取什么方法来实现这一目标?
CSV Excel 文件用逗号分隔,如姓名、年龄、约翰、33、鲍勃、55、
因此,您可以将其作为字符串读取并从中创建一个数组。 然后将数组渲染成表格。 反向操作以制作 CSV Excel 文件。
const excelString = ` name, age, john, 33, bob, 55, `; function parse(string){ return string.trim().split("\n").map(row => row.trim().split(",").map(val => val.trim()).filter(str => str)); } const parsed = parse(excelString); const [head, ...body] = parsed; function addElement(tag, data, editable){ const elm = document.createElement(tag); if(data) elm.textContent = data; if(editable) elm.contentEditable = true; return elm; } document.querySelector("table").appendChild( addElement("tr") ); head.map(header => { document.querySelector("tr:last-child").appendChild( addElement("th", header, true) ); }); body.map(row => { document.querySelector("table").appendChild(addElement("tr")); row.map(item => { document.querySelector("tr:last-child").appendChild( addElement("td", item, true) ); }); }); function table2excel(){ return Array.from(document.querySelectorAll("tr")).map(row => { return Array.from(row.querySelectorAll("th, td")).map(elm => elm.textContent); }).map(row => row.join(",")).join(",\n").concat(",") } const newExcel = table2excel(); console.log(newExcel) document.querySelector("button").addEventListener("click", () => console.log(table2excel()))
<table /> <button>Log table</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.