0

i am using laravel5.6. i want to export database table data into excel file. here is my controller code

    use Exporter;

    $business = Approvedemand::all();
    $values ='';
    foreach($business as $item)
    {
        $values.='<tr>
            <td>'.$item['id'].'</td>
            <td>'.$item['name'].'</td>
            </tr>';   
    }
    header('Content-type: application/excel');
    $filename = date('Y-m-d').'-approveList'.'.xls';
    header('Content-Disposition: attachment; filename='.$filename);

    $data = '<html xmlns:x="urn:schemas-microsoft-com:office:excel">
    <head>
       <!--[if gte mso 9]>
       <xml>
         <x:ExcelWorkbook>
             <x:ExcelWorksheets>
               <x:ExcelWorksheet>
                  <x:Name>Sheet 1</x:Name>
                      <x:WorksheetOptions>
                          <x:Print>
                             <x:ValidPrinterInfo/>
                          </x:Print>
                      </x:WorksheetOptions>
               </x:ExcelWorksheet>
            </x:ExcelWorksheets>
        </x:ExcelWorkbook>
    </xml>
    <![endif]-->
</head>
<body>
   <table>
      <tr>
        <td>ID</td>
        <td>Name</td>
     </tr>'
    .$values.
  '</table>
 </body>
 </html>';

 echo $data;

When i run this, excel file download but it display html tag in excel. i am not sure this method is correct or not.

1 Answer 1

2

When i run this, excel file..

I'm assuming you mean call a controller function with a web route. Something like..

Route::get('/your/path', 'BusinessController@export')->name('export');

i want to export database table data into excel file.

You can use Maatwebsite/Excel 2.1.0 for this.

BusinessController:

use App\Approvedemand;

public function export()
{
    $data = App\Approvedemand::all();

    return Excel::create('Approve Demand'), function($excel) use ($data) {
        $excel->sheet('Sheetname', function($sheet) use ($data)
        {
            $sheet->fromArray($data);
        });
    })->export('xls');
}

This is just a basic example. You'd obviously want to include some validation here.

Sign up to request clarification or add additional context in comments.

1 Comment

@user3406350 how did you make out with this? Able to resolve your issue?

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.