Copy range of cells to new worksheets

May 19, 2011 at 8:18 PM

 I'm working with anywhere from 2 to about 10 different workbooks, all with 1 worksheet that are getting copied into a single workbook. Got the code to do so from another post here and it works great...

$filenames = $phpFileRead;

$bigExcel = new PHPExcel();
$bigExcel->removeSheetByIndex(0);

$reader = new PHPExcel_Reader_Excel2007();

foreach ($filenames as $filename) {
    $excel = $reader->load($filename);
   
    foreach ($excel->getAllSheets() as $sheet) {
        $bigExcel->addExternalSheet($sheet);
    }
   
    foreach ($excel->getNamedRanges() as $namedRange) {
        $bigExcel->addNamedRange($namedRange);
    }
}

$writer = new PHPExcel_Writer_Excel2007($bigExcel);
$newBookName = "temp\sites".$newDate.".xlsx";
$writer->save($newBookName);

Well, I don't need the entire sheet copied to the new workbook, just a range of cells which are the same from each worksheet. How would I be able to adjust the code above so that it only copies the cells K1:N30 into the new workbook instead of all the columns and rows?

Thanks in advance.

Coordinator
May 22, 2011 at 1:57 PM

I'd use the worksheet's rangeToArray() or namedRangeToArray() methods to retrieve the data from cells K1:N30, then just feed that array to the new workbook's worksheet using fromArray().