0

我正在尝试复制整个列或将值复制到另一列。我的脚本可以确定需要复制的列,然后是最高行值。有什么建议么。

4

1 回答 1

3

我遇到了同样的问题,经过几天的搜索,到目前为止我得到的只是这个主题[在 PHPExcel 中复制样式和数据]。代码完美而清晰地理解,但就像你一样,我需要从列复制到列,而不是行到行。然后,我发现复制一列基本上只是“将一个单元格连续复制到另一个单元格索引”。所以这是代码,经过测试,它对我有用。希望这能有所帮助。

/**
 * Copy excel column to column
 * @param $sheet:current active sheet
 * @param $srcRow: source row
 * @param $dstRow: destination row
 * @param $height: rows number want to copy
 * @param $width: column number want to copy
 **/
private function selfCopyRow(\PHPExcel_Worksheet $sheet, $srcRow, $dstRow, $height, $width)
{
    for ($row = 0; $row < $height; $row++) {
        for ($col = 0; $col < $width; $col++) {
            $cell = $sheet->getCellByColumnAndRow($col, $srcRow + $row);
            $style = $sheet->getStyleByColumnAndRow($col, $srcRow + $row);
            $dstCell = \PHPExcel_Cell::stringFromColumnIndex(($width + $col)) . (string)($dstRow + $row);
            $sheet->setCellValue($dstCell, $cell->getValue());
            $sheet->duplicateStyle($style, $dstCell);
        }

        $h = $sheet->getRowDimension($srcRow + $row)->getRowHeight();
        $sheet->getRowDimension($dstRow + $row)->setRowHeight($h);
    }

    // EN : Copy format
    foreach ($sheet->getMergeCells() as $mergeCell) {
        $mc = explode(":", $mergeCell);
        $col_s = preg_replace("/[0-9]*/", "", $mc[0]);
        $col_e = preg_replace("/[0-9]*/", "", $mc[1]);
        $row_s = ((int)preg_replace("/[A-Z]*/", "", $mc[0])) - $srcRow;
        $row_e = ((int)preg_replace("/[A-Z]*/", "", $mc[1])) - $srcRow;

        if (0 <= $row_s && $row_s < $height) {
            $merge = $col_s . (string)($dstRow + $row_s) . ":" . $col_e . (string)($dstRow + $row_e);
            $sheet->mergeCells($merge);
        }
    }

}
于 2017-10-09T04:48:03.120 回答