ThinkPHP框架中实现文件压缩和导出功能需要使用到两个核心类:ZipArchive
和PHPExcel
。
ZipArchive
类是PHP自带的压缩文件操作类,可以方便地将多个文件压缩成一个文件。具体使用方式如下:
$zip = new ZipArchive();
$zipName = 'example.zip';
if ($zip->open($zipName, ZipArchive::CREATE) === true) {
$zip->addFile('file1.txt', 'file1.txt');
$zip->addFile('file2.txt', 'file2.txt');
$zip->close();
}
上述代码将文件file1.txt
和file2.txt
压缩为一个名为example.zip
的文件。
而PHPExcel
类则是一个用于导出Excel文件的开源类库。使用方式如下:
// 导出Excel文件
$objPHPExcel = new \PHPExcel();
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B1', 'World');
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="example.xls"');
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
上述代码将生成一个包含Hello
和World
两个单元格的Excel文件,并以文件流的形式输出到浏览器中供用户下载。
在ThinkPHP框架中,我们可以将上述两个类封装为一个工具类,方便在控制器中调用。以下是一个示例:
<?php
namespace app\common\utils;
use ZipArchive;
use PHPExcel;
class ExportUtils
{
/**
* 压缩文件
*
* @param array $files 待压缩文件列表
* @param string $zipName 压缩后文件名
* @return bool|string
*/
public static function zipFiles($files, $zipName)
{
$zip = new ZipArchive();
if ($zip->open($zipName, ZipArchive::CREATE) !== true) {
return false;
}
foreach ($files as $file) {
if (file_exists($file)) {
$zip->addFile($file, basename($file));
}
}
$zip->close();
return $zipName;
}
/**
* 导出Excel文件
*
* @param array $data 导出数据
* @param array $columns 导出列名
* @param string $filename 文件名
* @return bool
*/
public static function exportExcel($data, $columns, $filename)
{
// 创建PHPExcel对象
$objPHPExcel = new PHPExcel();
// 设置当前活动的sheet
$objPHPExcel->setActiveSheetIndex(0);
// 设置列名
$colIndex = 'A';
foreach ($columns as $column) {
$objPHPExcel->getActiveSheet()->setCellValue($colIndex . '1', $column);
$colIndex++;
}
// 设置数据
$rowIndex = 2;
foreach ($data as $row) {
$colIndex = 'A';
foreach ($row as $value) {
$objPHPExcel->getActiveSheet()->setCellValue($colIndex . $rowIndex, $value);
$colIndex++;
}
$rowIndex++;
}
// 设置HTTP头信息
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
header('Cache-Control: max-age=0');
// 输出Excel文件
$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
return true;
}
}
在控制器中,我们可以直接调用该工具类中的方法来实现文件压缩和导出功能:
<?php
namespace app\index\controller;
use app\common\utils\ExportUtils;
class Index
{
public function export()
{
// 导出Excel文件
$data = [
['张三', '20', '男'],
['李四', '22', '女'],
['王五', '21', '男'],
];
$columns = ['姓名', '年龄', '性别'];
ExportUtils::exportExcel($data, $columns, 'example');
}
public function zip()
{
// 压缩文件
$files = [
'/path/to/file1.txt',
'/path/to/file2.txt',
];
$zipName = 'example.zip';
ExportUtils::zipFiles($files, $zipName);
}
}
上述代码示例实现了在ThinkPHP中实现文件压缩和导出功能,其中ZipArchive
和PHPExcel
类是关键的类库。