要实现在基于 Vue 及 iview 的页面中添加上传 Excel 文件的功能,并将文件传到后端用 php
进行处理,可以通过以下步骤:
在 Vue 组件中添加一个上传按钮,与上述步骤类似,不再赘述。
在上传成功后,将 Excel 文件传到后端使用 php 进行处理,并将处理后的数据发送回前端。
可以使用 Vue 的 axios 库向后端发送 POST 请求,将 Excel 文件以 FormData 的形式上传到后
端。代码如下:
import axios from "axios";
readExcelFile(file) {
const formData = new FormData();
formData.append("file", file);
axios.post("/api/read_excel.php", formData).then(response => {
const data = response.data;
console.log("表头:", data.header);
console.log("数据:", data.rows);
}).catch(error => {
console.error(error);
});
},
以上代码中,将 Excel 文件添加到 FormData 中,并将 FormData 与请求的 URL 一起使用 axios
发送 POST 请求。在后端接收到请求后,可以通过如下的 php 脚本处理 Excel 文件,并返回
处理后的数据:
<?php
header("Content-Type:text/html;charset=utf-8");
date_default_timezone_set("Asia/Shanghai");
require_once "PHPExcel/PHPExcel.php";
$inputFileType = PHPExcel_IOFactory::identify($_FILES["file"]["tmp_name"]);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($_FILES["file"]["tmp_name"]);
$sheetData = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$title = "";
$tableHeader = [];
$tableData = [];
foreach ($sheetData as $row) {
if (strpos($row["A"], "线") !== false || strpos($row["A"], "SFC") !== false) {
// 如果找到标题,则开始读取表头和数据