2025年01月20日 建站教程
如何利用php语法从数据库中查询数据并生成excel表格并导出下载到本地,下面web建站小编给大家简单介绍一下具体实现代码!
代码如下:
//连接数据库 $conn = mysqli_connect($servername, $username, $password, $dbname); if (!$conn) { die("连接失败: " . mysqli_connect_error()); } //查询数据库 $sql = "SELECT * FROM `table_name`"; $result = mysqli_query($conn, $sql); //利用PHPExcel类库生成Excel表格 $objPHPExcel = new PHPExcel(); $objPHPExcel->getProperties() ->setCreator("your name") ->setLastModifiedBy("your name") ->setTitle("title") ->setSubject("subject") ->setDescription("description") ->setKeywords("keywords") ->setCategory("category"); $objPHPExcel->setActiveSheetIndex(0); $i = 1; while ($row = mysqli_fetch_array($result)) { $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $row['column1']); $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $row['column2']); $i++; } //输出Excel文件 header('Content-Type: application/vnd.ms-excel'); header('Content-Disposition: attachment;filename="filename.xls"'); header('Cache-Control: max-age=0'); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('php://output'); //下载Excel文件 $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save('file_path/filename.xls');
本文链接:http://so.lmcjl.com/news/21717/