简体   繁体   中英

PHPExcel, Copy sheet from one to another xls document with style

I need to create an xls file using lists of other files

I do something like this:

    $objReader = PHPExcel_IOFactory::createReader('Excel5');
    $file_tmpl = $objReader->load('doc10.xls');

$file_tmpl - the resulting file

    $file1 = $objReader->load('doc11.xls');

$file1 - file that is copied sheet

    $file1->setActiveSheetIndex(1);
    $sheet = $file1->getActiveSheet();          
    $file_tmpl->addSheet($sheet,1);

As a result, the sheet is copied, except for the style of the cell: the borders, fonts, text size, text color. How to move all together with style?

Thank you.

There is a method built into PHPExcel for this: addExternalSheet() which copies the styling as well as the content from one workbook to another.

There is a script ( 43mergeWorkbooks.php ) to demonstrate its use in the /Examples folder of PHPExcel

$objPHPExcel = PHPExcel_IOFactory::load("x.xlsx");
$objPHPExcel1 = PHPExcel_IOFactory::load("y.xlsx");
foreach($objPHPExcel1->getSheetNames() as $sheetName)
{
    $sheet = $objPHPExcel1->getSheetByName($sheetName);
    $sheet->setTitle('Sheet'.$k);
    $objPHPExcel->addExternalSheet($sheet);
    unset($sheet);

}
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objPHPExcel->setActiveSheetIndex(0);
$file='x';

$filename = $file."_".@date("Y-m-d_H-i",time()).'.xlsx';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');
$objWriter->save('php://output');  //send it to user, of course you can save it to disk also!
exit; //done.. exiting!

The PHPExcel library is DEPRECATED. They suggest that all users should migrate to its direct successor PhpSpreadsheet.

In the following link you will find an example of how to copy a worksheet from one workbook to another.

https://github.com/PHPOffice/PhpSpreadsheet/blob/develop/samples/Basic/43_Merge_workbooks.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM