欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

CI中使用PHPExcel导出数据到Excel

程序员文章站 2022-04-19 13:08:10
...
  1. class Table_export extends CI_Controller {

  2. function __construct()

  3. {
  4. parent::__construct();
  5. // Here you should add some sort of user validation

  6. // to prevent strangers from pulling your table data
  7. }
  8. function index($table_name)

  9. {
  10. $this->load->database();
  11. $query = $this->db->query("select * from `$table_name` WHERE del= 1");
  12. // $query = mb_convert_encoding("gb2312", "UTF-8", $query);
  13. if(!$query)
  14. return false;
  15. // Starting the PHPExcel library

  16. $this->load->library('PHPExcel');
  17. $this->load->library('PHPExcel/IOFactory');
  18. $objPHPExcel = new PHPExcel();

  19. $objPHPExcel->getProperties()->setTitle("export")->setDescription("none");
  20. $objPHPExcel->setActiveSheetIndex(0)

  21. ->setCellValue('A1', iconv('gbk', 'utf-8', '中文Hello'))
  22. ->setCellValue('B2', 'world!')
  23. ->setCellValue('C1', 'Hello');
  24. // Field names in the first row
  25. $fields = $query->list_fields();
  26. $col = 0;
  27. foreach ($fields as $field)
  28. {
  29. $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, 1, $field);
  30. $col++;
  31. }
  32. // Fetching the table data

  33. $row = 2;
  34. foreach($query->result() as $data)
  35. {
  36. $col = 0;
  37. foreach ($fields as $field)
  38. {
  39. $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $data->$field);
  40. $col++;
  41. }
  42. $row++;

  43. }
  44. $objPHPExcel->setActiveSheetIndex(0);

  45. $objWriter = IOFactory::createWriter($objPHPExcel, 'Excel5');

  46. //发送标题强制用户下载文件

  47. header('Content-Type: application/vnd.ms-excel');
  48. header('Content-Disposition: attachment;filename="Products_'.date('dMy').'.xls"');
  49. header('Cache-Control: max-age=0');
  50. $objWriter->save('php://output');

  51. }
  52. }
  53. ?>
复制代码

加入数据库有表名为products,然后访问http://www.yourwebsite.com/table_export/index/products 就可以导出excel文件了。