0

I'm using LaravelExcel at my Laravel 5.8 project and it is working fine and perfect but the only problem is that, the data does not get inserted into proper columns.

Here is the result:

enter image description here

As you can see all the data are inserted into the column A However, it was supposed to insert data into separated columns like this image:

enter image description here

And here is my Export 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'));
    }
}

And here is Controller method:

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

So how to fix this issue so the csv file holds data in their proper column.

Also this is the View:

<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>

2 Answers2

1

I think there is no problem with your code. It happens because you are opened CSV file without the correct separator symbol. If you wanna get results like this:

enter image description here

then try to open your file with Separator Options Separated by comma

enter image description here

Or better yet, try to save your file in xlsx format instead of csv. Then you will not have a problem with the separator symbol.

public function export_view()
{
    return Excel::download(new StudentExportView, 'studentlist.xlsx');
}
Oleg Demkiv
  • 1,332
  • 7
  • 7
0

Since you just need to export your users to a file to be able to open it in Excel, I suggest you to do it by a simple function and without installing new packages.

Get users as a json and use this function to save it to a .csv file:

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

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

And here's the magic function:

  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

Milad
  • 119
  • 2
  • 13