PHPExcel - Create spreadsheet from HTML table?

2019-04-09 11:53发布

问题:

I'm trying to create a simple reporting system, which can output either HTML or export to Excel. I have got it to create a HTML table successfully through a Codeigniter view but I want to know if there's any way I can re-use that view to create the Excel export, rather than doing it manually, as I'll then have to update it in two places every time I want to make a change to the report.

Any advice appreciated.

Thanks.

回答1:

This seems to be working:

// Load the table view into a variable
$html = $this->load->view('table_view', $data, true);

// Put the html into a temporary file
$tmpfile = time().'.html';
file_put_contents($tmpfile, $html);

// Read the contents of the file into PHPExcel Reader class
$reader = new PHPExcel_Reader_HTML; 
$content = $reader->load($tmpfile); 

// Pass to writer and output as needed
$objWriter = PHPExcel_IOFactory::createWriter($content, 'Excel2007');
$objWriter->save('excelfile.xlsx');

// Delete temporary file
unlink($tmpfile);