[英]Set column cell value as formula in dynamic range Maatwebsite/Excel 2.1.0
I'm stumped here and hoping someone out there has an answer or can point me in the right direction! 我被困在这里,希望有人在那里给出答案,或者可以指出正确的方向!
Using: Laravel 5.7 | 使用: Laravel 5.7 | Maatwebsite/Excel 2.1.0
Maatwebsite / Excel 2.1.0
What I'm trying to accomplish: 我要完成的工作:
I want to insert a basic formula into a column across a dynamic number of rows when exporting. 我想在导出时将基本公式插入动态行数的列中。 I know I can use
我知道我可以用
$sheet->setCellValue('H2','=SUM(G2*F2)');
to set a specific cell value. 设置特定的单元格值。 I'm assuming the answer lies somewhere here
我假设答案就在这里
$sheet->cells('H2:H'.$numRows, function($cells) {
// manipulate the range of cells
});
but we all know what happens when you assume something. 但是我们都知道当您假设某事时会发生什么。 Does anyone have any insight on this at all?
有没有人对此有任何见识? Thank you in advance!
先感谢您!
You can iterate over each cell in the range that you have found and set it's value to the formula that you want. 您可以遍历找到的范围中的每个单元格,并将其值设置为所需的公式。
$sheet->cells('H2:H'.$numRows, function($cells) {
foreach($cells as $cell) {
$cell->setValue('=SUM(G2*F2)');
}
});
Or if you have custom formula for some cells in the range based on the documentation for PhpSpreadSheet which Maatwebsite uses, you can see how to set range of cells here from an array. 或者,如果您根据Maatwebsite使用的PhpSpreadSheet的文档对范围内的某些单元格具有自定义公式,则可以在此处查看如何从数组设置单元格范围的方法。
So for your case you can build a 1-d array and place it as columns like this: 因此,对于您的情况,您可以构建一维数组并将其放置为如下所示的列:
$rowArray = [];
for($i = 0; $i <= $numOfRows; $i++) {
$rowArray[] = '=SUM(G2*F2)'; // customize the formula if needed for specific row
}
$columnArray = array_chunk($rowArray, 1);
$sheet->fromArray(
$columnArray, // The data to set
NULL, // Array values with this value will not be set
'H2' // Top left coordinate of the worksheet range where
// we want to set these values (default is A1)
);
This may help you 这可能对您有帮助
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
Class ExportData implements FromCollection, WithHeadings, ShouldAutoSize, WithEvents
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$event->sheet->setCellValue('E'. ($event->sheet->getHighestRow()+1), '=SUM(E2:E'.$event->sheet->getHighestRow().')');
}
];
}
...
"Your code to export"
...
"Note:
1.in my case the data I want to get the SUM is in "E" Column you can change it as you want
2.You only need to implement "WithEvents" and use "AfterSheet" other things that I implemented is for other purposes
"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.