如何利用php和uniapp实现数据的excel导入与导出
导入和导出数据是我们在web开发中经常遇到的需求。而Excel作为常用的数据格式之一,能够以表格形式清晰地展示数据,并且具有较高的兼容性,成为了很多人的选择。本篇文章将介绍如何利用PHP和UniApp分别实现数据的Excel导入和导出。
首先,我们来看如何通过PHP实现数据的Excel导入。
可以通过Composer进行安装,将以下代码添加到composer.json文件中:
{
"require": {
"phpoffice/phpexcel": "^1.8"
}
}然后在命令行中执行composer install来完成安装。
本书是全面讲述PHP与MySQL的经典之作,书中不但全面介绍了两种技术的核心特性,还讲解了如何高效地结合这两种技术构建健壮的数据驱动的应用程序。本书涵盖了两种技术新版本中出现的最新特性,书中大量实际的示例和深入的分析均来自于作者在这方面多年的专业经验,可用于解决开发者在实际中所面临的各种挑战。
466
立即学习“PHP免费学习笔记(深入)”;
<?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' => '上传失败'
]);
}
?>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');
?>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'
});
}
});
}
}
}通过以上步骤,我们可以轻松实现数据的Excel导入和导出功能。无论是在PHP后端还是UniApp前端,都能够通过相关的库和接口来完成这一任务。希望本文能够对你有所帮助!
以上就是如何利用PHP和UniApp实现数据的Excel导入与导出的详细内容,更多请关注php中文网其它相关文章!
全网最新最细最实用WPS零基础入门到精通全套教程!带你真正掌握WPS办公! 内含Excel基础操作、函数设计、数据透视表等
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号