PHP利用PHPExcel导出数据到Excel

PHP 利用PHPExcel到处数据到Excel;还有导出数据乱码的解决方案。

直接贴代码吧!

● PHP版本5.6.38

● mysql版本5.0

  1. //连接数据库
  2. $mysql_server_name = "*.*.*.*";
  3. $mysql_username="user";
  4. $mysql_password="dbpasswd";
  5. $mysql_database="test";
  6. $conn = mysqli_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database);
  7. // 检测连接
  8. if ($conn->connect_error) {
  9. die("连接失败: " . $conn->connect_error);
  10. }
  11. //设置字符集,如果不设置的话中文可能会乱码
  12. $conn->query("set names utf8");
  13. //查询数据
  14. $sql = "SELECT * FROM testdata WHERE inserttime > '2019-09-13' AND inserttime <'2019-0916'";
  15. $result = $conn->query($sql);
  16. //遍历将数据放入数组中
  17. $data =array();
  18. while ($row = $result->fetch_assoc())
  19. {
  20. $data[] = $row;
  21. }
  22. //将查询出来的数据导入Excel中
  23. require_once('./PHPExcel/PHPExcel.php');
  24. // 创建Excel文件对象
  25. $objPHPExcel = new PHPExcel();
  26. // 设置文档信息,这个文档信息windows系统可以右键文件属性查看
  27. $objPHPExcel->getProperties()->setCreator("wnn")
  28. ->setLastModifiedBy("wnn")
  29. ->setTitle("原创文章链接");
  30. $objPHPExcel->setActiveSheetIndex(0)
  31. ->setCellValue('A1','文章ID')
  32. ->setCellValue('B1','标题')
  33. ->setCellValue('C1','链接')
  34. ->setCellValue('D1','作者')
  35. ->setCellValue('E1','发布时间');
  36. //设置excel表单根据内容大小变化
  37. $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
  38. $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
  39. $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
  40. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
  41. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
  42. //$i=1是标题行
  43. $i=2;
  44. foreach ($data as $k=>$v){
  45. $objPHPExcel->setActiveSheetIndex(0)
  46. ->setCellValue('A'.$i,$v['id'])
  47. ->setCellValue('B'.$i,$v['title'])
  48. ->setCellValue('C'.$i,$v['arcurl'])
  49. ->setCellValue('D'.$i,$v['writer'])
  50. ->setCellValue('E'.$i,$v['senddate']);
  51.    //给C列的文字加上链接
  52. $objPHPExcel->getActiveSheet()->getCell('C'.$i)->getHyperlink()->setUrl($v['arcurl']);
  53. $i++;
  54. }
  55. //给C列的超链接字体颜色变成蓝色
  56. $length = count($data)+1;
  57. $objPHPExcel->getActiveSheet()->getStyle( 'C2:C'.$length)->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_BLUE);
  58. //文件名称
  59. $filename=urlencode('原创作品').'_'.date('YmdHis');
  60. //生成xls文件
  61. ob_end_clean();//清除缓冲区,避免乱码
  62. header('Content-Type: application/vnd.ms-excel');
  63. header('Content-Disposition: attachment;filename="'.$filename.'.xls"');
  64. header('Cache-Control: max-age=0');
  65. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  66. $objWriter->save('php://output');

如果导出来的Excel文字都是乱码的话,一定要在header()前面加上ob_end_clean()!