Rumah > pembangunan bahagian belakang > tutorial php > CI中使用PHPExcel导出数据到Excel

CI中使用PHPExcel导出数据到Excel

WBOY
Lepaskan: 2016-07-25 09:10:23
asal
1149 orang telah melayarinya
  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文件了。



sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan