在PHP中使用PHPExcel庫(現在已經被PhpSpreadsheet取代)進行Excel文件操作時,你可以使用以下方法進行數據篩選:
composer require phpoffice/phpspreadsheet
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$data = [
['Name', 'Age', 'City'],
['Alice', 30, 'New York'],
['Bob', 25, 'San Francisco'],
['Charlie', 22, 'Los Angeles'],
];
foreach ($data as $row) {
$sheet->fromArray($row, null, 'A' . ($sheet->getHighestRow() + 1));
}
$writer = new Xlsx($spreadsheet);
$writer->save('example.xlsx');
function filterData($sheet, $column, $value)
{
$filteredData = [];
for ($row = 1; $row <= $sheet->getHighestRow(); $row++) {
$cellValue = $sheet->getCell($column . $row)->getValue();
if ($cellValue === $value) {
$filteredData[] = $sheet->rangeToArray('A' . $row . ':' . $column . $row, null, true, true, false);
}
}
return $filteredData;
}
$column = 'B'; // 要篩選的列,例如:'B' 代表年齡列
$value = 25; // 要篩選的值,例如:25
$filteredData = filterData($sheet, $column, $value);
$filteredSpreadsheet = new Spreadsheet();
$filteredSheet = $filteredSpreadsheet->getActiveSheet();
$rowNumber = 1;
foreach ($filteredData as $data) {
foreach ($data as $cell) {
$filteredSheet->setCellValue('A' . $rowNumber, $cell);
$rowNumber++;
}
}
$filteredWriter = new Xlsx($filteredSpreadsheet);
$filteredWriter->save('filtered_example.xlsx');
這個示例將篩選出年齡為25的行,并將結果保存到名為"filtered_example.xlsx"的新Excel文件中。你可以根據需要修改$column
和$value
變量來篩選不同的列和值。