我正在try 导入一个包含150多张工作表的EXCEL文件,然后通过判断EXCEL表名,我想要替换其中的数据或添加新行.

最初,我想使用视图来手动制作所有的设计,只是导出它们,但这将是耗时的.

这就是我目前所拥有的.


<?php

namespace App\Http\Controllers;

use App\Imports\FirstSheetImport;
use App\Imports\WorkingPaperImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class WorkingPaperExportController extends Controller
{
    public function getExcelAndRewrite(Request $request)
    {
        $import = new FirstSheetImport('EA1');

        $modifiedData = $import->getModifiedData();

        return $modifiedData;
    }
}
<?php

namespace App\Imports;

use App\Exports\TestExportEA1;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithStartRow;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Events\AfterImport;
use PhpOffice\PhpSpreadsheet\IOFactory;

class FirstSheetImport implements ToCollection, WithHeadingRow
{
    protected $sheetName;
    protected $sheetIndex;
    protected $modifiedData = [];

    public function __construct($sheetName)
    {
        $this->sheetName = $sheetName;
    }

    public function collection(Collection $collection)
    {
        //
    }

    protected function getFilePath()
    {
        // Provide the path to your Excel file
        return storage_path('/import/uptodateworkingpaper.xlsx');
    }

    protected function hasHeadingRow()
    {
        // Return true or false based on your needs
        return true;
    }

    public function getModifiedData()
    {
        $spreadsheet = IOFactory::load($this->getFilePath());
        $sheetNames = $spreadsheet->getSheetNames();

        $sheetIndex = array_search($this->sheetName, $sheetNames);

        $this->sheetIndex = $sheetIndex;
        if ($sheetIndex !== false) {
            $worksheet = $spreadsheet->getSheet($sheetIndex);
            $rows = $worksheet->toArray();

            return $rows;
        }
        // return $this->sheetIndex;
    }
}

使用我现在拥有的功能,我能够获得正确的工作表数据,但我不确定从那里到哪里go .甚至不确定这是不是一个好办法.

如有任何帮助或建议,我们不胜感激.

PHP 7.3.33 Laravel框架8.75.0

推荐答案

如果还有其他人需要帮助,这对我很管用.

<?php

namespace App\Http\Controllers;

use App\Imports\FirstSheetImport;
use App\Imports\WorkingPaperImport;
use App\Models\Project;
use App\Models\WorkSheet;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Maatwebsite\Excel\Facades\Excel;

use PhpOffice\PhpSpreadsheet\Reader\Xlsx as ReaderXlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx as WriterXlsx;

class WorkingPaperExportController extends Controller
{
    public function projectWorkingPaper(Request $request)
    {
        $data = $request->only('project_id');

        $rules = [
            'project_id' => 'required|exists:project_has_schedules,project_id',
        ];

        $validator = Validator::make($data, $rules);

        if ($validator->fails()) {
            return response()->json(['message' => $validator->errors()], 400);
        }

        $project = Project::with('masterSchedules')->find($data['project_id']);

        $activeSchedules = [];

        foreach ($project['masterSchedules'] as $schedule) {
            $activeSchedules[] = $schedule['id'];
        }

        $workSheetSymbols = [];

        foreach ($activeSchedules as $schedule_id) {
            $groupedSchedules = WorkSheet::where('schedule_id', $schedule_id)->get();

            foreach ($groupedSchedules as $individialSchedule) {
                $workSheetSymbols[] = $individialSchedule['symbol'];
            }
        }

        if ($workSheetSymbols) {

            // read the excel file here
            $templatePath = storage_path('app/template/workingpaper.xlsx');

            $reader = new ReaderXlsx();

            $spreadsheet = $reader->load($templatePath);

            $sheetNames = $spreadsheet->getSheetNames();

            $sheetIndex = array_search($workSheetSymbols[0], $sheetNames);                                                                                                                                                                                                                                           

            if ($sheetIndex !== false) {
                // get the desired worksheet
                $worksheet = $spreadsheet->getSheetByName($workSheetSymbols[0]);
                // add/change values accordingly
                $worksheet->setCellValue('Q10', '500250');

                $writer = new WriterXlsx($spreadsheet);

                $newFileName = 'hello.xlsx';
                $savePath = storage_path("app/workingpaper/{$newFileName}");
                $writer->save($savePath);

                return response()->download($savePath);
            }
        } else {
            return response()->json(['message' => 'No schedules found!'], 500);
        }
    }
}

Laravel相关问答推荐

如何更改LIVE上的Filament占位符内容?

CKEditor在laravel中的p标记之前和之后添加额外的p标记

Laravel 9 中使用 WHERE 子句的列的 SUM

laravel 如何验证跨越午夜的两个值之间的时间(15:00 > 时间 > 01:00)

如何为 CMP 横幅安装谷歌同意脚本?

Laravel 5.3:语法错误或访问冲突:1463 HAVING 子句中使用了非分组字段距离

Laravel transformer vs resource

Laravel 5 迁移:Schema::table 方法中不同类型的默认长度

你如何在自定义 Laravel Nova 工具中使用确认对话?

Laravel 使用 Storage::put 生成唯一 ID

导入文件时如何跳过第一行

如何在 AWS Elastic Beanstalk 上设置和使用 Laravel 调度?

Laravel 应用程序中应用程序键的意义是什么?

Laravel 全部返回 ID 变为 0

如何清理 Laravel Bootstrap 缓存配置文件?

Laravel hasManyThrough

是否可以在 Laravel 的不同数据库中引用外键?

Laravel binding绑定的用途和目的是什么?

Laravel 更新查询

限制自己重载外部 API 的速率