空列A和B成功删除,但C和D未移动到A和B,只有D移动到A单元格中未显示的单元格C值

时间:2015-12-08 08:45:54

标签: php phpexcel

这是我的代码

$ objPHPExcel = new PHPExcel(); $ objPHPExcel-> setActiveSheetIndex(0) - > setCellValue('C1','Hello') - > setCellValue('C2','world!') - > setCellValue('C3','Hello') - > setCellValue('D1','test') - > setCellValue('D2','world!') - > setCellValue('D3','Hello');

$ 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(empty($ err)){         $ objPHPExcel-> getActiveSheet() - > removeColumn( 'A');
        $ objPHPExcel-> getActiveSheet() - > removeColumn( 'B');
        }}

1 个答案:

答案 0 :(得分:0)

$objPHPExcel->getActiveSheet()
    ->removeColumn('D');

删除列D

$objPHPExcel->getActiveSheet()
    ->removeColumn('D', 3);

从列D开始删除3个连续列(即D - F

但是你需要自己编写逻辑来识别列是否为空

修改

$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
    }
}