0

I have done import in laravel 5 but facing some problem while exporting file. code is not proper and doesnot give any logic. I have tried similiar to documentation

public function exportData(Test $test,Excel $excel){
  $test=$test->all();
    Excel::create('Test excel', function($test) {

    $test->sheet('sheet1', function($sheet) {

        $sheet->setOrientation('landscape');

    });

})->export('xls');
    }

how to export csv file from mysql? I am using "maatwebsite/excel": "~2.0.0" package

2 Answers 2

2

You can use INTO OUTFILE in Laravel

public function exportData($file_name) {

          $file = public_path()."/downloads/".$file_name; //CSV file is store this path

          $query = sprintf("select * from tests INTO OUTFILE '%s' FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n'",$file);

         \DB::connection()->getpdo()->exec($query);
    }
Sign up to request clarification or add additional context in comments.

2 Comments

i am using maatwebsite/excel package
This solution does not require ANY external libraries. It can implemented in Laravel "as is."
0

You might consider using the league/csv package. They have an example of exporting a database query to CSV. In your case, it would look something like:

public function exportData() {
    // get the data
    $data = Test::all();

    // get a Writer object for writing to CSV
    $csv = League\Csv\Writer::createFromFileObject(new SplTempFileObject());

    // add the data to the writer
    $csv->insertAll($data);

    // output the file
    $csv->output('testdata.csv');
}

2 Comments

i am using maatwebsite/excel package
I see that you have edited your original post to include this information. That being said, is it absolutely necessary that you use that specific package? Both my answer and the answer by @jay-dhameliya will solve your problem rather easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.