找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 262|回复: 0

[composer组件] 使用PHP组件PhpSpreadsheet/phpOffice对excel插入数据

  [复制链接]
发表于 2023-2-23 16:45 | 显示全部楼层 |阅读模式

通常情况下,我们操作excel都是从上向下写数据,画表头,然后写数据。是没有表尾要画。最近领导给我出了一个难题,给定一个excel模板,要向中间部分插入数据。按照通常思路操作后,想着如果能将表尾复制上去,岂不妙哉?于是找到官方网站,找到接口:https://phpoffice.github.io/PhpSpreadsheet/master/PhpOffice/PhpSpreadsheet/Spreadsheet.html#method_addExternalSheet  。心想,这就简单多了。

 

于是改动程序,立马实现了,但结果不是我要的:

image.png

它是复制成为一个新的sheet,并不是复制在当前sheet上。

一个同事觉得我JJYY的,决定给我写一个,使用PhpSpreadsheet插入数据。咦?我一直没有听说过phpoffice操作excel插入数据的。结果第二天,他真的给我写好了。

 

赶快记录下来,其实也挺简单的:

加载对应的类名:

use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Exception;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;

先将中间部分的样式画出来:

$style = [
    'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['argb' => '666666']]],//边框
    'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],//上下左右居中
    'font' => ['name' => '宋体', 'size' => 10, 'bold' => false],//字体
    'fill' => ['fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFFFFF']]//背景填充
];

画中间数据:

$row_start = 10;
$worksheet->insertNewRowBefore($row_start, $datapagesize);//插入数据:从第几行插入数据,共多少数据
$rows = array_slice($goods_list, $part,$datapagesize);
foreach($rows as $i=>$gs){
    $row = $row_start + $i;
    $worksheet->getCell("A$row")->setValue($part+$i+1);//设置数据
    $total_goods_price_cost = $gs['goods_price_cost'] * $gs['purchasing_num'];
    $worksheet->getCell("J$row")->setValue($total_goods_price_cost);//设置数据
    for($i = 'A'; $i<='K'; $i++)
    {
        $pCoordinate = $i.$row;
        $worksheet->getStyle($pCoordinate)->applyFromArray($style);//画中间数据样式
    }
    foreach (array_values($gs) as $j=>$v)
    {
        $worksheet->getCellByColumnAndRow($j+2, $row)->setValue($v);
    }
    $totalamount += $total_goods_price_cost;
}

大功告成。

 

insertNewRowBefore接口地址:

https://phpoffice.github.io/PhpSpreadsheet/master/PhpOffice/PhpSpreadsheet/Worksheet/Worksheet.html#method_insertNewRowBefore

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|学习笔记

GMT+8, 2024-5-18 11:46 , Processed in 0.021328 second(s), 14 queries , APCu On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

快速回复 返回顶部 返回列表