vue.js Laravel excel export works just 1 time

anauzrmj  于 2023-06-24  发布在  Vue.js
关注(0)|答案(1)|浏览(76)

我已经在我的laravel/vue js项目中安装了maatwebsite/excel。它工作正常,但它只导出1次,根本没有更多。我不知道为什么,我做了一切喜欢在教程如何出口,我发现在谷歌搜索。有许多类似的教程。它的工作只是1次。也许有人知道为什么它一次工作?Vue

axios.get(`api/export/${this.type}`, {responseType: 'arraybuffer'})
    .then(response => {          
      this.url = window.URL.createObjectURL(new Blob([response.data]));
      this.link = document.createElement('a');
      this.link.href = this.url;
      this.date = new Date()
      this.day = this.date.toISOString().split('T')[0];

      const digits = '0123456789';
      const numDigits = 6;
      
      for (let i = 0; i < numDigits; i++) {
        const randomIndex = Math.floor(Math.random() * digits.length);
        const digit = digits.charAt(randomIndex);
        this.uniqueNumber += digit;
      }

      this.link.setAttribute('download', `users-${this.uniqueNumber}.xlsx`);
      document.body.appendChild(this.link);
      this.link.click();        
      const data = response.data;
      console.log(data);
    })

laravel用户导出
类UsersExport实现FromCollection,WithHeadings {

protected $users;

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

public function collection()
{
    return $this->users;
}

public function headings(): array
{
    return [
        'ID',
        'farmer_name',
        'oblast',
        'Created At',
        'Updated At',
    ];
}

}在控制器中

public function exportToExcel(Request $request, $type)
{
    if($type === 'All') {
        $users = BioFarm::all(); // Get all users from the database
    } else {
        $users = BioFarm::where('oblast', $type)->get(); 
    }

    $fileName = 'users.xlsx';       

    $export = new UsersExport($users);

    return Excel::download($export, $fileName); // Download the Excel file

}
inkz8wg9

inkz8wg91#

您可以选择PHP文件处理程序来导出CSV而不是maatwebsite/excel。
代码片段:

$fileDirectory = 'path';
    $fileName   = 'filename.csv';
    $file       = $fileDirectory . '/'. $fileName;
    $columns    = [
        "column1",
        "column2",
    ];
    $fp         = fopen($file, 'w');
    fputcsv($fp, $columns);
    foreach ($array as $data) {
        $row   = [];
        $row[] = $data->column1;
        $row[] = $data->column2;
        fputcsv($fp, $row);
    }
    fclose($fp);
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="' . $fileName);
    header('Content-Length: ' . filesize($file));
    readfile($file);
    unlink($file);
    exit;

修改代码以满足您的要求。

相关问题