gpt4 book ai didi

php - 使用 phpSpreadSheet 在 excel 中合并

转载 作者:行者123 更新时间:2023-12-04 19:49:03 32 4
gpt4 key购买 nike

我想合并 2 个或更多 excel 与 PhpSpreadsheet。我试图保留每张纸的样式,这是我的代码:

<?php

require 'vendor/autoload.php';


use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$inputFileType = 'Xlsx';
$inputFileNames = [
'a.xlsx',
'b.xlsx',
'c.xlsx'
];
$sheetnames = [
'Worksheet',
'Worksheet1',
'Worksheet2'
];
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$inputFileName = array_shift($inputFileNames);
$spreadsheetMain = $reader->load($inputFileName);
$spreadsheetMain->getActiveSheet()->setTitle('page0');
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getActiveSheet()->setTitle($inputFileName[0]);
$clonedWorksheet->setTitle('page' . $contador);
$spreadsheetMain->addSheet($clonedWorksheet);
$contador++;
}
$writer = new Xlsx($spreadsheetMain);
$writer->save('prueba1.xlsx');

为了做我想做的事,我需要改变这个$spreadsheetMain->addSheet($clonedWorksheet);

对于 $spreadsheetMain->addExternalSheet($clonedWorksheet);

但是当我执行该代码时出现错误:“工作表不存在”

我想它还没有实现,但在文档页面中:https://phpspreadsheet.readthedocs.io/en/develop/topics/worksheets/#copying-worksheets

如果你愿意,你可以在这里下载我的excel和代码来试试: https://drive.google.com/open?id=1qkI8jdYDuA6e5CW6z3k0r_7j1pTvW_6D

最佳答案

addExternalSheet 的问题是我需要用相同的名称命名两个工作表(我加载的原始工作表和克隆的工作表)。 (所有文件都在这里:https://drive.google.com/open?id=1qkI8jdYDuA6e5CW6z3k0r_7j1pTvW_6D,mergeSolved 是正确的文件)这是带有解决方案的代码:

require 'vendor/autoload.php';

use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

$inputFileType = 'Xlsx';
$inputFileNames = [
'a.xlsx',
'b.xlsx',
'c.xlsx'
];
$sheetnames = [
'Worksheet',
'Worksheet1',
'Worksheet2'
];
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$reader->setLoadSheetsOnly($sheetnames);
$inputFileName = array_shift($inputFileNames);
$spreadsheetMain = $reader->load($inputFileName);
$spreadsheetMain->getActiveSheet()->setTitle('page0');
$contador = 1;
foreach ($inputFileNames as $book => $inputFileName) {
echo ('$inputFileName: ' . $inputFileName) . '</br>';
$spreadsheet = $reader->load($inputFileName);
$clonedWorksheet = clone $spreadsheet->getSheetByName('Worksheet'.$contador);
$clonedWorksheet->setTitle('Worksheet'.$contador);
$spreadsheetMain->addExternalSheet($clonedWorksheet);
$contador++;
}
$writer = new Xlsx($spreadsheetMain);
$writer->save('prueba1.xlsx');`

关于php - 使用 phpSpreadSheet 在 excel 中合并,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50250387/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com