使用phpexcel复制整个列

时间:2012-11-12 07:43:26

标签: php excel

我试图复制整个列或将值复制到另一列。我们的脚本可以确定需要复制的列,然后是高值。任何建议。

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题,经过几天的搜索,到目前为止,我所有的话题都是[copy style and data in 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);
        }
    }

}