这是我的代码
$objPHPExcel=新的PHPExcel();$objPHPExcel->setActiveSheetIndex(0)->setCellValue('C1','Hello')->setCellValue('C2','world!';
$worksheet=$objPHPExcel->setActiveSheetIndex(0)$highestColumn=$worksheet->getHighestColumn()$highestColumn=PHPExcel_Cell::columnIndexFromString($highestColumn)-1$highestRow=$worksheet->getHighestRow();for($column=$highestColumn;$column>=0;--$column){for($row=1;$row<=$highestRow;++$row){$cell=$worksheet->getCellByColumnAndRow($column,$row)$err=$cell->getValue();if(!empty($err)){打破}if(空($err)){$objPHPExcel->getActiveSheet()->removeColumn('A')
$objPHPExcel->getActiveSheet()->removeColumn('B')
}}}
$objPHPExcel->getActiveSheet()
->removeColumn('D');
删除列D
$objPHPExcel->getActiveSheet()
->removeColumn('D', 3);
删除从列D
(即D
-F
)开始的3个连续列
但是您需要自己编写逻辑来确定列是否为空
编辑
$objPHPExcel = new PHPExcel();
$data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
$objPHPExcel->getActiveSheet()->fromArray($data);
$objPHPExcel->getActiveSheet()
->removeColumn('B');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('removeColumnTest.xlsx');
上面的代码有效,并创建了一个包含以下内容的电子表格:
A B
1 1 3
2 4 6
3 7 9
这是删除列的预期结果。。。。列B已被删除,所有后续列(本例中只有C)都被重新排列,使列C成为新的列B。
编辑#2
如何检查为空的列
$worksheet = $objPHPExcel->getActiveSheet();
$highestColumn = $worksheet->getHighestDataColumn();
$highestColumn = PHPExcel_Cell::columnIndexFromString($highestColumn) - 1;
$highestRow = $worksheet->getHighestDataRow();
// Check columns in reverse order if you want to delete empty columns
// because the removeColumn() has less work to do if we're deleting backwards
for($column = $highestColumn; $column >= 0; --$column) {
// Loop through the rows in the current column
for ($row = 1; $row <= $highestRow; ++$row) {
// check the cell in each row
$cell = $worksheet->getCellByColumnAndRow($column,$row);
if (!empty($cell->getValue())) {
// Don't bother checking any more cells in this column if a cell isn't empty
// Just move on to the previous column
break;
}
// column is empty, so do whatever you want here.... e.g. delete or whatever
}
}