Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

php 使用 PhpSpreadsheet 导入导出操作

作者:潇洒一醉   发布日期:2024-12-01   浏览:271

使用 PhpSpreadsheet 导入导出操作可以实现将 Excel 文件导入到 PHP 中进行处理,或将 PHP 数据导出为 Excel 文件。

导入操作:

  1. 首先,确保已经安装了 PhpSpreadsheet 库。可以通过 Composer 进行安装,使用以下命令:
composer require phpoffice/phpspreadsheet
  1. 创建一个 PHP 文件,导入所需的类和命名空间:
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
  1. 使用 IOFactory 类的 load 方法加载 Excel 文件:
$spreadsheet = IOFactory::load('path/to/excel/file.xlsx');
  1. 获取 Excel 文件中的工作表:
$worksheet = $spreadsheet->getActiveSheet();
  1. 遍历工作表中的行和列,获取单元格的值:
foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);

    foreach ($cellIterator as $cell) {
        $value = $cell->getValue();
        // 处理单元格的值
    }
}

导出操作:

  1. 创建一个新的 Spreadsheet 对象:
$spreadsheet = new Spreadsheet();
  1. 获取工作表对象:
$worksheet = $spreadsheet->getActiveSheet();
  1. 设置单元格的值:
$worksheet->setCellValue('A1', 'Hello');
$worksheet->setCellValue('B1', 'World');
  1. 导出 Excel 文件:
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('path/to/save/file.xlsx');

以上就是使用 PhpSpreadsheet 导入导出操作的基本步骤。根据具体需求,可以进一步扩展和调整代码。

上一篇:PHP 测验

下一篇:PhpOffice——PhpSpreadsheet导入导出

大家都在看

php文件加密

php 拆分字符串

php ||

php str_repeat

php mongodb

php __invoke

php imagecopyresample

php数组随机抽取

php时间格式转时间戳

php 对象

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站