·设为首页收藏本站📧邮箱修改🎁免费下载专区🔐设置/修改密码👽群雄群聊
返回列表 发布新帖

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

219 0
发表于 2023-4-21 20:53:44 | 显示全部楼层 阅读模式

马上注册,免费下载更多dz插件网资源。

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

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

于是改动程序,立马实现了,但结果不是我要的:
使用PHP组件PhpSpreadsheet/phpOffice对excel插入数据 使用,php,组件,excel,插入
它是复制成为一个新的sheet,并不是复制在当前sheet上。
一个同事觉得我JJYY的,决定给我写一个,使用PhpSpreadsheet插入数据。咦?我一直没有听说过phpoffice操作excel插入数据的。结果第二天,他真的给我写好了。

赶快记录下来,其实也挺简单的:
加载对应的类名:
  1. use PhpOffice\PhpSpreadsheet\Cell\DataType;
  2. use PhpOffice\PhpSpreadsheet\Exception;
  3. use PhpOffice\PhpSpreadsheet\IOFactory;
  4. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  5. use PhpOffice\PhpSpreadsheet\Style\Fill;
  6. use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
  7. use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
复制代码
先将中间部分的样式画出来:
  1. $style = [
  2.     'borders' => ['allBorders' => ['borderStyle' => 'thin', 'color' => ['argb' => '666666']]],//边框
  3.     'alignment' => ['horizontal' => 'center', 'vertical' => 'center'],//上下左右居中
  4.     'font' => ['name' => '宋体', 'size' => 10, 'bold' => false],//字体
  5.     'fill' => ['fillType' => Fill::FILL_SOLID, 'color' => ['argb' => 'FFFFFF']]//背景填充
  6. ];
复制代码
画中间数据:
  1. $row_start = 10;
  2. $worksheet->insertNewRowBefore($row_start, $datapagesize);//插入数据:从第几行插入数据,共多少数据
  3. $rows = array_slice($goods_list, $part,$datapagesize);
  4. foreach($rows as $i=>$gs){
  5.     $row = $row_start + $i;
  6.     $worksheet->getCell("A$row")->setValue($part+$i+1);//设置数据
  7.     $total_goods_price_cost = $gs['goods_price_cost'] * $gs['purchasing_num'];
  8.     $worksheet->getCell("J$row")->setValue($total_goods_price_cost);//设置数据
  9.     for($i = 'A'; $i<='K'; $i++)
  10.     {
  11.         $pCoordinate = $i.$row;
  12.         $worksheet->getStyle($pCoordinate)->applyFromArray($style);//画中间数据样式
  13.     }
  14.     foreach (array_values($gs) as $j=>$v)
  15.     {
  16.         $worksheet->getCellByColumnAndRow($j+2, $row)->setValue($v);
  17.     }
  18.     $totalamount += $total_goods_price_cost;
  19. }
复制代码
大功告成。

insertNewRowBefore接口地址:
https://phpoffice.github.io/PhpSpreadsheet/master/PhpOffice/PhpSpreadsheet/Worksheet/Worksheet.html#method_insertNewRowBefore
我要说一句 收起回复

回复

 懒得打字嘛,点击右侧快捷回复【查看最新发布】   【应用商城享更多资源】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

投诉/建议联系

discuzaddons@vip.qq.com

未经授权禁止转载,复制和建立镜像,
如有违反,按照公告处理!!!
  • 联系QQ客服
  • 添加微信客服

联系DZ插件网微信客服|最近更新|Archiver|手机版|小黑屋|DZ插件网! ( 鄂ICP备20010621号-1 )|网站地图

您的IP:3.138.141.202,220.169.152.77,GMT+8, 2024-4-29 09:55 , Processed in 0.220211 second(s), 68 queries , Gzip On, Redis On.

Based on Discuz! W1.0 Licensed

© 2001-2024 Discuz! Team.

关灯 在本版发帖
扫一扫添加微信客服
QQ客服返回顶部
快速回复 返回顶部 返回列表