Use PHPExcel in CI to export data to Excel

WBOY
Release: 2016-07-25 09:10:23
Original
1132 people have browsed it
  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文件了。



source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template