首页 > 其他分享 >laravel将excel水平分割成多张表

laravel将excel水平分割成多张表

时间:2024-02-24 14:45:26浏览次数:29  
标签:laravel 成多 excel spreadsheet fileName newSheet data dir size

在Laravel中,可以使用PhpSpreadsheet库来读取Excel文件,并将其水平分割成多个表格。

首先,通过Composer安装了PhpSpreadsheet库:

composer require phpoffice/phpspreadsheet

使用

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class ExcelChunk extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'excel_chunk {fileName} {size}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '分割excel文件';
    protected $dir = '';
    protected $size = 1000;
    protected $excelName = '';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        set_time_limit(0);
        parent::__construct();
        $this->dir = storage_path('app/public/excel/');
        if (!file_exists($this->dir)) {
            mkdir($this->dir);
        }
    }

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $fileName = $this->argument('fileName', '');
        $index = stripos($fileName, '.');
        if ($index !== false) {
            $this->excelName = substr($fileName, 0, $index);
        } else {
            $this->error('文件名错误');
            return;
        }
        $this->size = $this->argument('size', 1000);
        $this->chunkExcelSheet($fileName);
    }

    public function chunkExcel($fileName)
    {
        // 读取 Excel 文件
        $spreadsheet = IOFactory::load($this->dir . $fileName);
        $worksheet = $spreadsheet->getActiveSheet();

        // 获取数据集
        $data = $worksheet->toArray();
        $head = $data[0];
        unset($data[0]);

        // 假设我们按照行数来分割文件,每100行为一个新文件
        $fileCount = ceil(count($data) / $this->size);

        // 遍历数据并创建新的工作簿和工作表
        for ($i = 0; $i < $fileCount; $i++) {
            // 创建一个新的 Spreadsheet 对象作为新文件的基础
            $newSpreadsheet = new Spreadsheet();

            // 创建第一个工作表
            $newSheet = $newSpreadsheet->getActiveSheet();
            $newSheet->setTitle("Sheet$i");

            // 将当前批次的数据写入新工作表
            $startIndex = $i * $this->size;
            $endIndex = min(($i + 1) * $this->size - 1, count($data) - 1);
            $dataSlice = array_slice($data, $startIndex, $endIndex - $startIndex + 1);
            array_unshift($dataSlice, $head);
            $newSheet->fromArray($dataSlice);

            // 保存为新的 Excel 文件
            $writer = IOFactory::createWriter($newSpreadsheet, 'Xlsx');
            $writer->save($this->dir . $this->excelName . '_' . ($i + 1) . '.xlsx');
        }
    }

    public function chunkExcelSheet($fileName)
    {
        // 读取 Excel 文件
        $spreadsheet = IOFactory::load($this->dir . $fileName);
        $originalWorksheet = $spreadsheet->getActiveSheet();
        $data = $originalWorksheet->toArray();
        $head = $data[0];
        unset($data[0]);
        // 假设我们按照行数来分割到不同的工作表,每100行为一个新工作表
        $sheetCount = ceil(count($data) / $this->size);

        // 在同一个工作簿中创建多个工作表
        for ($i = 0; $i < $sheetCount; $i++) {
            // 创建新工作表
            $newSheet = new Worksheet($spreadsheet);
            $spreadsheet->addSheet($newSheet, $i);
            $newSheet->setTitle("Sheet$i");

            // 将当前批次的数据写入新工作表
            $startIndex = $i * $this->size;
            $endIndex = min(($i + 1) * $this->size - 1, count($data) - 1);
            $dataSlice = array_slice($data, $startIndex, $endIndex - $startIndex + 1);
            array_unshift($dataSlice, $head);
            $newSheet->fromArray($dataSlice);
        }

        // 保存修改后的工作簿
        $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save($this->dir . $this->excelName . "_output.xlsx");
    }
}

调用

php artisan excel_chunk aaa.excel 1000

标签:laravel,成多,excel,spreadsheet,fileName,newSheet,data,dir,size
From: https://www.cnblogs.com/chengwens/p/18031056

相关文章

  • js_将excel内容先存入数据库,再将数据显示到页面
    <%--将excel数据显示到页面--%><scripttype="text/javascript">//原创来自www.luofenming.com//首先监听input框的变动,选中一个新的文件会触发change事件document.querySelector("#testFile").addEventListener("change",function(){......
  • Excel窗体控件笔记
    工作表控件分成2种表单控件(图片上面)ActiveX控件(图片下面)一,表单控件这种如果只是使用代码其实和我们直接在工作表里插入一个图形是一样的效果可以把一些参数直接设置到单元格里,不需要代码辅助,配合公式等可以实现一些自动化效果但是,设置不了一些颜色样式等等,看上去比较素......
  • 盘点一个Python自动化办公Excel数据处理的需求
    大家好,我是Python进阶者。一、前言前几天在Python白银交流群【干锅牛蛙】问了一个Python处理Excel数据的问题。问题如下:有两个问题哈:1、表头有合并单元格识别不出来,如何处理类似下图2、遇到单元格有公式自动识别成了0,如何处理,保留计算后的值,类似下图附上他自己的代码如下:目......
  • .Net Code Excel 文件导入
    第一步下载NuGetNPOI包///<summary>///将excel文教导入到订单表///</summary>///<paramname="file">excel文件</param>///<returns>:-1;返回导入文件格式不正确</returns>[HttpPost]publicIActionResultUp......
  • Python处理Word,Excel,PDF
    openpyxl模块处理Excel表安装以下命令意思是:指定D盘下的Python解释器用豆瓣的源安装openpyxl模块D:\PycharmProjects\Study\venv\Scripts\python.exe-mpipinstallopenpyxl-ihttp://pypi.douban.com/simple--trusted-host=pypi.douban.com基本概念openpyxl库有三大模......
  • laravel 发送email 七牛附件
    useIlluminate\Support\Facades\Mail;useQiniu\Auth;privatestaticfunctionsendPdfEmailAnnex($path,$user){$auth=newAuth(env('QINIU_ACCESS_KEY'),env('QINIU_SECRET_KEY'));$expiry=3600;//有效期,单位:秒......
  • golang 读取excel 保存xml
    1、首先下载第三方excel读取库gogetgithub.com/xuri/excelize/v22、读取xml库,未使用默认xml库 gogetgithub.com/beevik/etreepackagemainimport( "fmt" "github.com/beevik/etree" "github.com/xuri/excelize/v2")funcLoadExcelAndSaveXML(){ ......
  • 如何在C#中使用 Excel 动态函数生成依赖列表
    前言在Excel中,依赖列表或级联下拉列表表示两个或多个列表,其中一个列表的项根据另一个列表而变化。依赖列表通常用于Excel的业务报告,例如学术记分卡中的【班级-学生】列表、区域销售报告中的【区域-国家/地区】列表、人口仪表板中的【年份-区域】列表以及生产摘要报告中的【单位-......
  • 导出程序EXCEL OLE DOI
    *&---------------------------------------------------------------------**&ReportZLOAD*&---------------------------------------------------------------------**&*&--------------------------------------------------------------------......
  • Python 实现Excel和CSV格式之间的互转
    通过使用Python编程语言,编写脚本来自动化Excel和CSV之间的转换过程,可以批量处理大量文件,定期更新数据,并集成转换过程到自动化工作流程中。本文将介绍如何使用第三方库Spire.XLSforPython实现:使用Python将Excel转为CSV使用Python将CSV转为Excel安装PythonExcel类库:pip......