layui表格导入和导出excel的前端代码怎么写 php后端如何编写代码
时间: 2024-04-30 10:24:46 浏览: 22
前端代码:
```
// layui表格导出excel
var table = layui.table;
var exportArr = []; // 导出数据
table.exportFile(['表头1', '表头2', '表头3'], exportArr, 'xls文件名', 'xls');
// layui表格导入excel
var upload = layui.upload;
upload.render({
elem: '#upload',
url: 'upload.php',
accept: 'file',
exts: 'xls|xlsx',
done: function(res){
if(res.code == 0){
layer.msg('导入成功');
}else{
layer.msg(res.msg);
}
},
error: function(){
layer.msg('上传失败');
}
});
```
后端代码(PHP):
```
// 导入excel
if($_FILES['file']['error'] == 0){
$filename = $_FILES['file']['tmp_name'];
require_once 'PHPExcel/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel5');
$objPHPExcel = $objReader->load($filename);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
for($row = 2; $row <= $highestRow; $row++){
$rowData = array();
for($col = 0; $col < $highestColumnIndex; $col++){
$val = $sheet->getCellByColumnAndRow($col, $row)->getValue();
$rowData[] = $val;
}
// 然后根据需要进行操作,如插入数据库等
}
}
// 导出excel
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:filename=文件名.xls");
echo iconv("UTF-8", "GBK", "表头1")."\t".iconv("UTF-8", "GBK", "表头2")."\t".iconv("UTF-8", "GBK", "表头3")."\t\n";
foreach($exportArr as $key => $val){
echo iconv("UTF-8", "GBK", $val['col1'])."\t".iconv("UTF-8", "GBK", $val['col2'])."\t".iconv("UTF-8", "GBK", $val['col3'])."\t\n";
}
```
其中,PHPExcel是一个用于读取、写入和操作Excel文件的PHP库,需要先下载并引入PHPExcel.php文件。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)