html + layui+ php layui表格导入和导出excel php后端如何编写代码
时间: 2024-01-12 09:03:02 浏览: 146
实现 layui 表格导入和导出 Excel 的后端代码可以参考以下示例:
导出 Excel:
```php
<?php
//连接数据库
$conn = mysqli_connect("localhost","root","","test");
//查询数据
$sql = "SELECT * FROM users";
$result = mysqli_query($conn, $sql);
//引入PHPExcel库
require_once './PHPExcel/PHPExcel.php';
//创建PHPExcel对象
$objPHPExcel = new PHPExcel();
//设置表头
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', 'ID');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B1', '姓名');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C1', '年龄');
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D1', '性别');
//循环输出数据
$i = 2;
while ($row = mysqli_fetch_array($result)) {
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $row['id']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, $row['name']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $row['age']);
$objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $row['sex']);
$i++;
}
//设置文件名和下载方式
$filename = '用户信息.xlsx';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '"');
header('Cache-Control: max-age=0');
//输出Excel文件
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
//关闭连接
mysqli_close($conn);
?>
```
导入 Excel:
```php
<?php
//连接数据库
$conn = mysqli_connect("localhost","root","","test");
//引入PHPExcel库
require_once './PHPExcel/PHPExcel.php';
//获取上传的Excel文件
$file = $_FILES['file']['tmp_name'];
//创建PHPExcel对象
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objPHPExcel = $objReader->load($file);
//获取当前工作表
$sheet = $objPHPExcel->getSheet(0);
//获取最大行数和列数
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
//循环读取数据
for ($i = 2; $i <= $highestRow; $i++) {
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i, NULL, TRUE, FALSE);
//插入数据到数据库
$sql = "INSERT INTO users (name, age, sex) VALUES (
'" . $rowData[0][1] . "',
'" . $rowData[0][2] . "',
'" . $rowData[0][3] . "'
)";
mysqli_query($conn, $sql);
}
//关闭连接
mysqli_close($conn);
//跳转到列表页面
header("Location: list.php");
?>
```
注意:上述代码中,需根据实际情况修改数据库连接信息、Excel 文件路径和表格列名等。
阅读全文