PhpSpreadsheet 安装及单元格操作

1.安装

composer require phpoffice/phpspreadsheet

2.读取xls文件

$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx');
$reader->setReadDataOnly(TRUE);
$spreadsheet = $reader->load("test.xlsx");

$worksheet = $spreadsheet->getActiveSheet();
// 获取工作表中引用的最高行号和列号
$highestRow = $worksheet->getHighestRow(); // e.g. 10
$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
//增加最高列字母
$highestColumn++;
echo '<table>' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
    echo '<tr>' . PHP_EOL;
    for ($col = 'A'; $col != $highestColumn; ++$col) {
        echo '<td>' .
             $worksheet->getCell($col . $row)
                 ->getValue() .
             '</td>' . PHP_EOL;
    }
    echo '</tr>' . PHP_EOL;
}
echo '</table>' . PHP_EOL;

 

public function test(){
        $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xls');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load("public/csv/2024.xls");
        $worksheet = $spreadsheet->getActiveSheet();
        echo '<table>' . PHP_EOL;
        foreach ($worksheet->getRowIterator() as $row) {
            echo '<tr>' . PHP_EOL;
            $cellIterator = $row->getCellIterator();
            $cellIterator->setIterateOnlyExistingCells(FALSE); //这在所有单元格中循环,
            //即使没有设置单元值。
            //对于“TRUE”,我们在单元格中循环
            //只有当它们的值被设置时。
            //如果不调用该方法,
            //默认值为“false”
            foreach ($cellIterator as $cell) {
                echo '<td>' .
                    $cell->getValue() .
                    '</td>' . PHP_EOL;
            }
            echo '</tr>' . PHP_EOL;
        }
        echo '</table>' . PHP_EOL;
    }

3.写入文件

require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$activeWorksheet = $spreadsheet->getActiveSheet();
$activeWorksheet->setCellValue('A1', 'Hello World !');#注A1  A表示列 1表示行
$writer = new Xlsx($spreadsheet);
$writer->save('hello world.xlsx');

 

参考文章:https://www.jianshu.com/p/2e26fdf47b94

posted @ 2024-11-15 09:18  流浪2024  阅读(15)  评论(0编辑  收藏  举报