赞
踩
- <?php
- require 'vendor/autoload.php';
- use PhpOfficePhpSpreadsheetIOFactory;
-
- if ($_FILES['file']['error'] == 0) {
- $file = $_FILES['file']['tmp_name'];
- $reader = IOFactory::createReader('Xlsx');
- $spreadsheet = $reader->load($file);
- $worksheet = $spreadsheet->getActiveSheet();
-
- // 获取数据并处理
- $data = [];
- foreach ($worksheet->getRowIterator() as $row) {
- $rowData = [];
- foreach ($row->getCellIterator() as $cell) {
- $rowData[] = $cell->getValue();
- }
- $data[] = $rowData;
- }
-
- // 处理数据
- // ...
-
- // 返回处理结果
- echo json_encode([
- 'status' => 1,
- 'message' => '上传成功'
- ]);
- } else {
- echo json_encode([
- 'status' => 0,
- 'message' => '上传失败'
- ]);
- }
- ?>
2. 在UniApp中调用接口
在UniApp项目中,使用uni.request来调用上述接口,将Excel文件作为FormData上传到服务器。
- export default {
- methods: {
- importExcel() {
- uni.chooseMessageFile({
- count: 1,
- success: (res) => {
- const tempFilePath = res.tempFiles[0].path;
- uni.uploadFile({
- url: 'http://localhost/import.php',
- filePath: tempFilePath,
- name: 'file',
- success: (res) => {
- const data = JSON.parse(res.data);
- if (data.status === 1) {
- uni.showToast({
- title: '导入成功',
- icon: 'success'
- });
- } else {
- uni.showToast({
- title: '导入失败',
- icon: 'none'
- });
- }
- },
- fail: () => {
- uni.showToast({
- title: '上传失败',
- icon: 'none'
- });
- }
- });
- }
- });
- }
- }
- }
通过UniApp实现数据的Excel导出
- <?php
- require 'vendor/autoload.php';
- use PhpOfficePhpSpreadsheetSpreadsheet;
- use PhpOfficePhpSpreadsheetWriterXlsx;
-
- // 获取数据
- $data = [
- ['name', 'age', 'gender'],
- ['Tom', 20, 'Male'],
- ['Lisa', 25, 'Female'],
- // ...
- ];
-
- // 创建Excel文件
- $spreadsheet = new Spreadsheet();
- $worksheet = $spreadsheet->getActiveSheet();
- $worksheet->fromArray($data);
-
- // 下载文件
- $writer = new Xlsx($spreadsheet);
- header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
- header('Content-Disposition: attachment;filename="export.xlsx"');
- $writer->save('php://output');
- ?>
2. 在UniApp中调用接口
在UniApp项目中,使用uni.downloadFile来下载导出的Excel文件。
- export default {
- methods: {
- exportExcel() {
- uni.downloadFile({
- url: 'http://localhost/export.php',
- success: (res) => {
- uni.saveFile({
- tempFilePath: res.tempFilePath,
- success: (res) => {
- uni.showToast({
- title: '导出成功',
- icon: 'success'
- });
- }
- });
- },
- fail: () => {
- uni.showToast({
- title: '导出失败',
- icon: 'none'
- });
- }
- });
- }
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。