导入导出excel前端html代码
时间: 2023-08-27 15:04:01 浏览: 225
以下是一个简单的前端 HTML 代码示例,用于导入和导出 Excel 表格:
```html
<!DOCTYPE html>
<html>
<head>
<title>Excel Import/Export Example</title>
</head>
<body>
<h1>Excel Import/Export Example</h1>
<!-- 导入表格 -->
<input type="file" id="fileInput">
<button onclick="importExcel()">Import</button>
<!-- 导出表格 -->
<button onclick="exportExcel()">Export</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.15.6/xlsx.full.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
<script>
function importExcel() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[sheetName];
const result = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
console.log(result);
};
reader.readAsArrayBuffer(file);
}
function exportExcel() {
const header = ['Name', 'Age', 'Gender'];
const data = [
['John', 25, 'Male'],
['Jane', 30, 'Female'],
['Bob', 20, 'Male']
];
const worksheet = XLSX.utils.aoa_to_sheet([header, ...data]);
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
const buffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
saveAs(new Blob([buffer], { type: 'application/octet-stream' }), 'example.xlsx');
}
</script>
</body>
</html>
```
这个代码示例使用了 xlsx.js 和 FileSaver.js 库来实现导入和导出 Excel 表格的功能。注意,这个例子只是一个简单的示例,实际上你可能需要根据你自己的需求进行修改。
阅读全文