php语法如何生成excel表格并导出

  

如何利用php语法从数据库中查询数据并生成excel表格并导出下载到本地,下面编程教程网小编给大家简单介绍一下具体实现代码!

代码如下:

//连接数据库
$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');
以上是编程学习网小编为您介绍的“php语法如何生成excel表格并导出”的全面内容,想了解更多关于 php入门 内容,请继续关注编程基础学习网。

相关文章