作者:Vincy。最后修改于2022年9月23日。
将数据导出到excel文件主要是用来进行备份。当进行数据库备份时,excel格式是一种方便阅读和管理的格式。对于一些应用程序来说,导出数据对服务器数据库的备份或离线拷贝非常重要。
这篇文章展示了如何使用PHP导出数据到excel。有很多方法可以实现这个功能。我们已经看到了一个从MySQL导出数据的例子。
本文使用PHPSpreadSheet库来实现PHP excel导出。
它是一个流行的库,支持读取和写入excel文件。它将通过其内置的函数使excel的导入-导出操作更加顺畅。
本文的完整例子将让你创建自己的导出工具或你的应用程序。
关于这个例子
它将显示一个包含数据库记录列表和 "导出到Excel "按钮的最小界面。通过点击这个按钮,它将调用为这个例子创建的自定义ExportService。
该服务实例化了PHPSpreadsheet库类,并设置了列头和值。然后,它通过设置PHPSpreadsheet实例创建一个写作者对象,将数据输出到Excel。
按照下面的步骤,让这个例子在你的环境中运行。
- 创建并设置数据库,并将数据输出到excel。
- 下载本文末尾的代码并配置数据库。
- 在应用程序中添加PHPSpreadSheet库和其他依赖项。
我们已经使用PHPSpreadsheet库来存储提取的图片URL。
- 创建并设置数据库,将数据导出到excel中
创建一个名为 "db_excel_export "的数据库,并将以下SQL脚本导入其中。
structure.sql
--
-- Table structure for table `tbl_products`
--
CREATE TABLE `tbl_products` (
`id` int(8) NOT NULL,
`name` varchar(255) NOT NULL,
`price` double(10,2) NOT NULL,
`category` varchar(255) NOT NULL,
`product_image` text NOT NULL,
`average_rating` float(3,1) NOT NULL
);
--
-- Dumping data for table `tbl_products`
--
INSERT INTO `tbl_products` (`id`, `name`, `price`, `category`, `product_image`, `average_rating`) VALUES
(1, 'Tiny Handbags', 100.00, 'Fashion', 'gallery/handbag.jpeg', 5.0),
(2, 'Men\'s Watch', 300.00, 'Generic', 'gallery/watch.jpeg', 4.0),
(3, 'Trendy Watch', 550.00, 'Generic', 'gallery/trendy-watch.jpeg', 4.0),
(4, 'Travel Bag', 820.00, 'Travel', 'gallery/travel-bag.jpeg', 5.0),
(5, 'Plastic Ducklings', 200.00, 'Toys', 'gallery/ducklings.jpeg', 4.0),
(6, 'Wooden Dolls', 290.00, 'Toys', 'gallery/wooden-dolls.jpeg', 5.0),
(7, 'Advanced Camera', 600.00, 'Gadget', 'gallery/camera.jpeg', 4.0),
(8, 'Jewel Box', 180.00, 'Fashion', 'gallery/jewel-box.jpeg', 5.0),
(9, 'Perl Jewellery', 940.00, 'Fashion', 'gallery/perls.jpeg', 5.0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_products`
--
ALTER TABLE `tbl_products`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_products`
--
ALTER TABLE `tbl_products`
MODIFY `id` int(8) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
- 下载代码并配置数据库
源代码包含以下文件。本节解释数据库的配置。
一旦你从本页面下载了excel导出代码,你可以在lib文件夹中找到DataSource.php文件。打开它并在其中配置数据库的细节,如下所示。
<?php
class DataSource
{
const HOST = 'localhost';
const USERNAME = 'root';
const PASSWORD = '';
const DATABASENAME = 'db_excel_export';
...
...
?>
- 在应用程序中添加PHPSpreadSheet库和其他依赖项
当你看到PHPSpreadsheet的文档时,它提供了一个易于遵循的安装步骤。
它给出了将PHPSpreadsheet和相关的依赖项添加到应用程序中的合成器命令。
composer require phpoffice/phpspreadsheet
对于PHP版本7
在composer.json文件中加入下面的规范。
{
"require": {
"phpoffice/phpspreadsheet": "^1.23"
},
"config": {
"platform": {
"php": "7.3"
}
}
}
然后运行
composer update
**注意:**PHPSpreadsheet至少需要PHP7.3版本。
它是如何工作的
带有导出选项的简单界面
本页从MySQL数据库中获取数据并以网格形式显示。在数据网格的下面,本页显示了一个 "Excel导出 "按钮。
通过点击这个按钮,动作参数被发送到URL,以调用PHP中的Excel导出服务。
index.php
<?php
require_once __DIR__ . '/lib/Post.php';
$post = new post();
$postResult = $post->getAllPost();
$columnResult = $post->getColumnName();
if (! empty($_GET["action"])) {
require_once __DIR__ . '/lib/ExportService.php';
$exportService = new ExportService();
$result = $exportService->exportExcel($postResult, $columnResult);
}
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="./style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="table-container">
<table id="tab">
<thead>
<tr>
<th width="5%">Id</th>
<th width="35%">Name</th>
<th width="20%">Price</th>
<th width="25%">Category</th>
<th width="25%">product Image</th>
<th width="20%">Average Rating</th>
</tr>
</thead>
<tbody>
<?php
if (! empty($postResult)) {
foreach ($postResult as $key => $value) {
?>
<tr>
<td><?php echo $postResult[$key]["id"]; ?></td>
<td><?php echo $postResult[$key]["name"]; ?></td>
<td><?php echo $postResult[$key]["price"]; ?></td>
<td><?php echo $postResult[$key]["category"]; ?></td>
<td><?php echo $postResult[$key]["product_image"]; ?></td>
<td><?php echo $postResult[$key]["average_rating"]; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<div class="btn">
<form action="" method="POST">
<a
href="<?php echo strtok($_SERVER["REQUEST_URI"]);?><?php echo $_SERVER["QUERY_STRING"];?>?action=export"><button
type="button" id="btnExport" name="Export"
value="Export to Excel" class="btn btn-info">Export
to Excel</button></a>
</form>
</div>
</div>
</body>
</html>
PHP模型调用准备好的查询来获取要导出的数据
这是一个PHP模型类,它被调用来从数据库中读取数据。数据数组将被发送到导出服务以建立excel表对象。
*getColumnName()*读取数据库表的列名数组。这个数组将提供数据以形成excel中的第一行,从而创建一个列头。
*getAllPost()*读取将被迭代的数据行,并设置数据单元格的值。
lib/Post.php
<?php
class Post
{
private $ds;
public function __construct()
{
require_once __DIR__ . '/DataSource.php';
$this->ds = new DataSource();
}
public function getAllPost()
{
$query = "select * from tbl_products";
$result = $this->ds->select($query);
return $result;
}
public function getColumnName()
{
$query = "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=N'tbl_products'";
$result = $this->ds->select($query);
return $result;
}
}
?>
PHP excel导出服务
该服务有助于将数据导出到excel表格中。通过设置PHP header()属性,结果文件将被下载到浏览器中。
columnResult有列数据。
这个例子实例化了PHPSpreadSheet库类并设置了列头和值。然后,它通过设置电子表格实例创建一个写作者对象,将数据输出到excel。
lib/ExportService.php
<?php
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Calculation\TextData\Replace;
require_once __DIR__ . '/../vendor/autoload.php';
class ExportService
{
public function exportExcel($postResult, $columnResult)
{
$spreadsheet = new Spreadsheet();
$spreadsheet->getProperties()->setTitle("excelsheet");
$spreadsheet->setActiveSheetIndex(0);
$spreadsheet->getActiveSheet()->SetCellValue('A1', ucwords($columnResult[0]["COLUMN_NAME"]));
$spreadsheet->getActiveSheet()->SetCellValue('B1', ucwords($columnResult[1]["COLUMN_NAME"]));
$spreadsheet->getActiveSheet()->SetCellValue('C1', ucwords($columnResult[2]["COLUMN_NAME"]));
$spreadsheet->getActiveSheet()->SetCellValue('D1', ucwords($columnResult[3]["COLUMN_NAME"]));
$spreadsheet->getActiveSheet()->SetCellValue('E1', str_replace('_', ' ', ucwords($columnResult[4]["COLUMN_NAME"], '_')));
$spreadsheet->getActiveSheet()->SetCellValue('F1', str_replace('_', ' ', ucwords($columnResult[5]["COLUMN_NAME"], '_')));
$spreadsheet->getActiveSheet()
->getStyle("A1:F1")
->getFont()
->setBold(true);
$rowCount = 2;
if (! empty($postResult)) {
foreach ($postResult as $k => $v) {
$spreadsheet->getActiveSheet()->setCellValue("A" . $rowCount, $postResult[$k]["id"]);
$spreadsheet->getActiveSheet()->setCellValue("B" . $rowCount, $postResult[$k]["name"]);
$spreadsheet->getActiveSheet()->setCellValue("C" . $rowCount, $postResult[$k]["price"]);
$spreadsheet->getActiveSheet()->setCellValue("D" . $rowCount, $postResult[$k]["category"]);
$spreadsheet->getActiveSheet()->setCellValue("E" . $rowCount, $postResult[$k]["product_image"]);
$spreadsheet->getActiveSheet()->setCellValue("F" . $rowCount, $postResult[$k]["average_rating"]);
$rowCount ++;
}
$spreadsheet->getActiveSheet()
->getStyle('A:F')
->getAlignment()
->setWrapText(true);
$spreadsheet->getActiveSheet()
->getRowDimension($rowCount)
->setRowHeight(- 1);
}
$writer = IOFactory::createWriter($spreadsheet, 'Xls');
header('Content-Type: text/xls');
$fileName = 'exported_excel_' . time() . '.xls';
$headerContent = 'Content-Disposition: attachment;filename="' . $fileName . '"';
header($headerContent);
$writer->save('php://output');
}
}
?>