EasySwoole 文書:EasySwoole 輸入匯出 Execl 表格

EasySwooleでExcelのインポートとエクスポートを行うには、PHPExcelライブラリを使用できます。次に簡単な例を示します。

  1. まず、PHPExcelライブラリをインストールするには
composer require phpoffice/phpexcel
  1. Excelファイルとしてエクスポート
<?php
use EasySwoole\Http\AbstractInterface\Controller;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class ExcelController extends Controller
{
public function index()
{
// 创建一个新的Excel对象
$spreadsheet = new Spreadsheet();
// 设置表格属性
$spreadsheet->getProperties()
->setTitle('导出Excel示例')
->setSubject('导出Excel示例')
->setDescription('这是一个导出Excel示例');
// 创建一个工作表
$sheet = $spreadsheet->getActiveSheet();
// 设置表头
$sheet->setCellValue('A1', '姓名')
->setCellValue('B1', '年龄');
// 设置数据行
$sheet->setCellValue('A2', '张三')
->setCellValue('B2', 20);
$sheet->setCellValue('A3', '李四')
->setCellValue('B3', 25);
// 创建一个新的Excel文件写入器
$writer = new Xlsx($spreadsheet);
// 将Excel文件写入到指定的路径
$filename = '/path/to/exported/excel.xlsx';
$writer->save($filename);
// 下载Excel文件
$this->response()->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$this->response()->withHeader('Content-Disposition', 'attachment;filename="excel.xlsx"');
$this->response()->withFile($filename);
}
}
  1. Excelシートをインポート:
<?php
use EasySwoole\Http\AbstractInterface\Controller;
use PhpOffice\PhpSpreadsheet\IOFactory;
class ExcelController extends Controller
{
public function index()
{
// 获取上传的Excel文件
$uploadedFile = $this->request()->getUploadedFile('file');
// 获取文件路径
$tempFilePath = $uploadedFile->getTempName();
// 读取Excel文件
$spreadsheet = IOFactory::load($tempFilePath);
// 获取工作表
$sheet = $spreadsheet->getActiveSheet();
// 获取单元格值
$name = $sheet->getCell('A2')->getValue();
$age = $sheet->getCell('B2')->getValue();
// 处理导入的数据,例如保存到数据库等
// 返回响应
$this->response()->write("导入成功");
}
}

上記の例は単なるデモンストレーションを目的としたものであり、実際のご要望に合わせて調整や最適化が必要となる可能性があります。

コメントを残す 0

Your email address will not be published. Required fields are marked *


广告
広告は10秒後に閉じます。
bannerAds