PHP:处理Excel表

在 PHP 中,可以使用以下几种方式来处理 Excel 表格:

一、使用 PHPExcel 库

1. 安装 PHPExcel:

可以通过 Composer 安装 PHPExcel。在项目目录下运行以下命令:

composer require phpoffice/phpexcel

2. 读取 Excel 文件:

以下是一个读取 Excel 文件的示例代码:

require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
$inputFileName = 'path/to/your/excel/file.xlsx';
$spreadsheet = IOFactory::load($inputFileName);
$worksheet = $spreadsheet->getActiveSheet();
foreach ($worksheet->getRowIterator() as $row) {
    $cellIterator = $row->getCellIterator();
    $cellIterator->setIterateOnlyExistingCells(false);
    foreach ($cellIterator as $cell) {
        echo $cell->getValue(). "\t";
    }
    echo "<br>";
}

3. 写入 Excel 文件:

以下是一个创建并写入 Excel 文件的示例代码:

require_once 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'Hello');
$sheet->setCellValue('B1', 'World');
$writer = new Xlsx($spreadsheet);
$writer->save('path/to/output/file.xlsx');

二、使用 CSV 格式间接处理

1. 读取 Excel 文件另存为 CSV,然后用 PHP 读取 CSV:

可以将 Excel 文件另存为 CSV 格式,然后使用 PHP 的文件操作函数来读取 CSV 文件。

$file = fopen('path/to/your/csv/file.csv', 'r');
while (($data = fgetcsv($file))!== false) {
    print_r($data);
}
fclose($file);

2. 生成 CSV 文件,可被 Excel 打开:

可以使用 PHP 生成 CSV 文件,该文件可以被 Excel 打开。

$data = [
            ['Name', 'Age', 'Email'],
            ['John', '30', 'john@example.com'],
            ['Jane', '25', 'jane@example.com']
        ];
$file = fopen('path/to/output/file.csv', 'w');
foreach ($data as $row) {
    fputcsv($file, $row);
}
fclose($file);

处理 Excel 表格时,要注意文件的格式、编码以及可能出现的错误。同时,根据实际需求选择合适的方法来处理 Excel 数据。

PHP编程语言基础