使用的phpoffice进行表格的输出
下面为使用方法:
public function excel(Request $request)
$behaviorDetail = 所查数据;
$newExcel = new Spreadsheet(); //创建一个新的excel文档
$objSheet = $newExcel->getActiveSheet(); //获取当前操作sheet的对象
$objSheet->setTitle(''); //设置当前sheet的标题
//设置宽度为true,不然太窄了
$newExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$newExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$newExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$newExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$objSheet->setCellValue('A1', '列名')
->setCellValue('B1', '列名')
->setCellValue('C1', '列名')
->setCellValue('D1', '列名');
foreach ($behaviorDetail as $k => $val) {
$k = $k + 2;
$objSheet->setCellValue('A' . $k, $val[''])
->setCellValue('B' . $k, $val[''])
->setCellValue('C' . $k, $val['']);
}
$this->downloadExcel($newExcel, '表名', 'Xls');
}
function downloadExcel($newExcel, $filename, $format)
{
// $format只能为 Xlsx 或 Xls
if ($format == 'Xlsx') {
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
} elseif ($format == 'Xls') {
header('Content-Type: application/vnd.ms-excel');
}
header('Content-Disposition: attachment;filename="'
. $filename . date('Y-m-d', strtotime('-1 day')) . '.' . strtolower($format).'"');
header('Cache-Control: max-age=0');
$objWriter = IOFactory::createWriter($newExcel, $format);
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header('Pragma: public'); // HTTP/1.0
$objWriter->save('php://output');
exit;
}
网友评论