Laravel Excel 没有将数据插入到正确的列中

LaravelExcel Does Not Insert Data Into Proper Columns

我在我的 Laravel 5.8 项目中使用 LaravelExcel,它运行良好且完美,但唯一的问题是,数据没有插入到正确的列中。

结果如下:

如您所见,所有数据都插入到列 A 但是,应该将数据插入到单独的列中,如下图所示:

这是我的导出 Class:

class StudentExportView implements FromView
{
    public function view(): View
    {
        set_time_limit(0);
        $student = new Student();
        $students = $student->searchStudents()->get();
        $custom = new Student();
        $customs = $custom->all();
        return view('admin.students.custom', compact('students','customs'));
    }
}

这里是控制器方法:

public function export_view()
    {
        return Excel::download(new StudentExportView, 'studentlist.csv');
    }

那么如何解决这个问题,使 csv 文件将数据保存在正确的列中。

这也是视图:

<table class="table table-sm table-bordered">
    <thead>
        <tr class="thead-dark">
            <th>Row</th>
            <th>Name</th>
            <th>Family Name</th>
            <th>National Code</th>
            <th>Mobile Number</th>
            <th>Province</th>
            <th>City</th>
            <th>Degree</th>
            <th>Grade</th>
            <th>Registered Time</th>
        </tr>
    </thead>
    <tbody>
    @if($students->count() != 0)
        @foreach($students as $student)
            <tr data-id="{{ $student->mbr_id }}"
                data-mobile="{{ $student->mbr_mobile }}"
                data-post-code="{{ $student->mbr_post_code }}"
                data-address="{{ $student->mbr_address }}"
            >
                <td>{{ $student->mbr_name }}</td>
                <td>
                    {{ $student->mbr_family }}
                    <a class="information text-danger float-left"><i class="fa fa-info-circle"></i></a>
                </td>
                <td>{{ $student->mbr_national_code }}</td>
                <td>{{ $student->mbr_mobile }}</td>
                <td>{{ $student->province }}</td>
                <td>{{ $student->city }}</td>
                <td>{{ $student->degree }}</td>
                <td>{{ $student->grade }}</td>
                <td>
                @if($customs->find($student->mbr_id))
                    {{ jdate($customs->find($student->mbr_id)->created_at) }}
                @endif
                </td>
            </tr>
        @endforeach
    @else
        <tr>
            <td colspan="12" style="text-align: center">No data for showing
            </td>
        </tr>
    @endif
    </tbody>
</table>

因为您只需要将您的用户导出到一个文件就可以在 Excel 中打开它,我建议您通过一个简单的函数来完成它,而不需要安装新的包。

获取用户 json 并使用此函数将其保存到 .csv 文件:

$students = Student::all();
$students_json = $students->toJson();

jsonToCsv($students_json, '/path/to/file.csv', true);

这是神奇的功能:

  function jsonToCsv ($json, $csvFilePath = false, $boolOutputFile = false) {
    
    // See if the string contains something
    if (empty($json)) { 
      die("The JSON string is empty!");
    }
    
    // If passed a string, turn it into an array
    if (is_array($json) === false) {
      $json = json_decode($json, true);
    }
    
    // If a path is included, open that file for handling. Otherwise, use a temp file (for echoing CSV string)
    if ($csvFilePath !== false) {
      $f = fopen($csvFilePath,'w+');
      if ($f === false) {
        die("Couldn't create the file to store the CSV, or the path is invalid. Make sure you're including the full path, INCLUDING the name of the output file (e.g. '../save/path/csvOutput.csv')");
      }
    }
    else {
      $boolEchoCsv = true;
      if ($boolOutputFile === true) {
        $boolEchoCsv = false;
      }
      $strTempFile = 'csvOutput' . date("U") . ".csv";
      $f = fopen($strTempFile,"w+");
    }
    
    $firstLineKeys = false;
    foreach ($json as $line) {
      if (empty($firstLineKeys)) {
        $firstLineKeys = array_keys($line);
        fputcsv($f, $firstLineKeys);
        $firstLineKeys = array_flip($firstLineKeys);
      }
      
      // Using array_merge is important to maintain the order of keys acording to the first element
      fputcsv($f, array_merge($firstLineKeys, $line));
    }
    fclose($f);
    
    // Take the file and put it to a string/file for output (if no save path was included in function arguments)
    if ($boolOutputFile === true) {
      if ($csvFilePath !== false) {
        $file = $csvFilePath;
      }
      else {
        $file = $strTempFile;
      }
      
      // Output the file to the browser (for open/save)
      if (file_exists($file)) {
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Length: ' . filesize($file));
        readfile($file);
      }
    }
    elseif ($boolEchoCsv === true) {
      if (($handle = fopen($strTempFile, "r")) !== FALSE) {
        while (($data = fgetcsv($handle)) !== FALSE) {
          echo implode(",",$data);
          echo "<br />";
        }
        fclose($handle);
      }
    }
    
    // Delete the temp file
    unlink($strTempFile);
    
  }

jsonToCsv() Source

我觉得你的代码没有问题。发生这种情况是因为您打开的 CSV 文件没有正确的分隔符。 如果你想得到这样的结果:

然后尝试使用 Separator Options Separated by comma

打开您的文件

或者更好的是,尝试以 xlsx 格式而不是 csv 格式保存文件。那么你的分隔符号就不会有问题了。

public function export_view()
{
    return Excel::download(new StudentExportView, 'studentlist.xlsx');
}