在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
变量来筛选不同的列和值。