You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP/Laravel下处理Laravel-Excel导出CSV去除首尾行多余逗号的方法

Laravel-Excel导出CSV去除首尾行多余逗号实现方案

实现逻辑

完全遵循你规划的处理流程,核心逻辑为导出文件存储后,对首尾行执行尾部逗号移除操作再返回下载。

代码实现

常规大小文件处理方案(内存占用适中)

适用于导出文件大小在100M以内的场景,代码简单易维护:

<?php

namespace App\Http\Controllers;

use Maatwebsite\Excel\Facades\Excel;
use App\Exports\CustomCsvExport; // 替换为你自己的导出类

class CsvExportController extends Controller
{
    public function export()
    {
        // 1、2步:生成导出文件并存储到服务器
        $savePath = 'reports/export_' . date('YmdHis') . '.csv';
        Excel::store(new CustomCsvExport(), $savePath, 'local');
        
        // 3-6步:处理首尾行多余逗号
        $fullFilePath = storage_path('app/' . $savePath);
        // 读取所有行内容,忽略原有换行符
        $fileLines = file($fullFilePath, FILE_IGNORE_NEW_LINES);

        if (!empty($fileLines)) {
            // 移除首行尾部逗号
            $fileLines[0] = rtrim($fileLines[0], ',');
            // 移除尾行尾部逗号
            $lastLineIndex = count($fileLines) - 1;
            $fileLines[$lastLineIndex] = rtrim($fileLines[$lastLineIndex], ',');
        }

        // 重写文件
        $newContent = implode(PHP_EOL, $fileLines);
        file_put_contents($fullFilePath, $newContent);
        
        // 返回下载,下载完成后自动删除服务器文件,无需保留可删除deleteFileAfterSend方法
        return response()->download($fullFilePath)->deleteFileAfterSend(true);
    }
}

大文件处理方案(低内存占用)

适用于导出文件超过100M的场景,采用逐行读写避免内存溢出:

// 接上面存储文件后的逻辑
$fullFilePath = storage_path('app/' . $savePath);
$tempFilePath = storage_path('app/reports/temp_' . uniqid() . '.csv');

// 计算文件总行数
$totalLines = count(file($fullFilePath));
$readFp = fopen($fullFilePath, 'r');
$writeFp = fopen($tempFilePath, 'w');
$currentLine = 0;

while (($line = fgets($readFp)) !== false) {
    $currentLine++;
    // 仅处理首行和尾行
    if ($currentLine === 1 || $currentLine === $totalLines) {
        // 先去除尾部逗号和原有换行
        $processedLine = rtrim($line, ",\n\r") . PHP_EOL;
        fwrite($writeFp, $processedLine);
    } else {
        // 正文行直接写入不修改
        fwrite($writeFp, $line);
    }
}

fclose($readFp);
fclose($writeFp);

// 替换原文件
unlink($fullFilePath);
rename($tempFilePath, $fullFilePath);

注意事项

  • 若CSV单元格内容包含被引号包裹的合法逗号,rtrim仅会移除行尾无意义的连续逗号,不会影响正文内容
  • 确保你使用的存储磁盘目录配置了正确的读写权限
  • 若需要保留服务器上的导出文件,删除deleteFileAfterSend(true)方法调用即可

内容的提问来源于stack exchange,提问作者stankobrin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 17:06:08