要是导出乱码,加上iconv("UTF-8", "GBK", "你好,中国")这一句就可以啦。
整体代码如下:

  1. $arr = [
  2. 0 => ['get_num' => 12, 'num' => 12, 'update_time' => 20180209],
  3. ];
  4. $totalArr = [
  5. 'total' => 144,
  6. 'people' => 1,
  7. 'time' => 20180209,
  8. ];
  9. function outerExcel($arr, $totalArr)
  10. {
  11. $file_name = "redPack_{$totalArr['time']}.xls";
  12. header('Cache-Control: no-cache, must-revalidate');
  13. header('Pragma: no-cache');
  14. header('Content-type:application/vnd.ms-excel');
  15. header('Content-Disposition:filename=' . $file_name);
  16. $excel
  17. = '<table width="100%" border="1" cellspacing="1" cellpadding="3" class="tableOutborder">
  18. <tr class="tableHeader">
  19. <td>' . iconv("UTF-8", "GBK", "发出的金币总数") . '</td>
  20. <td> ' . iconv("UTF-8", "GBK", "领取总人数") . '</td>
  21. <td> ' . iconv("UTF-8", "GBK", "日期") . '</td>
  22. </tr>
  23. <tr class="tableHeader">
  24. <td>' . $totalArr['total'] . '</td>
  25. <td>' . $totalArr['people'] . '</td>
  26. <td>' . $totalArr['time'] . '</td>
  27. </tr>
  28. <tr class="tableHeader">
  29. <td>' . iconv("UTF-8", "GBK", "发出的金币数") . '</td>
  30. <td> ' . iconv("UTF-8", "GBK", "领取人数") . '</td>
  31. <td> ' . iconv("UTF-8", "GBK", "日期") . '</td>
  32. </tr>';
  33. foreach ($arr as $value) {
  34. $excel
  35. .= '<tr>
  36. <td>' . $value['get_num'] . '</td>
  37. <td>' . $value['num'] . '</td>
  38. <td>' . $value['update_time'] . '</td>
  39. </tr>';
  40. }
  41. $excel .= '</table>';
  42. echo $excel;
  43. exit;
  44. }

方法二:
当然也可以加上bom头,不过有些系统不支持,好奇怪。
这里我们只要在文件的开始输出BOM头,告诉windows CSV文件的编码方式,从而让Excel打开CSV时采用正确的编码。

第1种:在所有内容之前输出

  1. print(chr(0xEF).chr(0xBB).chr(0xBF));

第2种:也可以直接写入到csv文件最前端:

  1. $csv_file = chr(0xEF).chr(0xBB).chr(0xBF).$csv_content;

方法二的代码如下:

  1. function outerExcel($arr, $totalArr)
  2. {
  3. print(chr(0xEF).chr(0xBB).chr(0xBF));
  4. $file_name = "redPack_{$totalArr['time']}.xls";
  5. header('Cache-Control: no-cache, must-revalidate');
  6. header('Pragma: no-cache');
  7. header('Content-type:application/vnd.ms-excel');
  8. header('Content-Disposition:filename=' . $file_name);
  9. $excel
  10. = '<table width="100%" border="1" cellspacing="1" cellpadding="3" class="tableOutborder">
  11. <tr class="tableHeader">
  12. <td>发出的金币总数</td>
  13. <td>领取总人数</td>
  14. <td>日期</td>
  15. </tr>
  16. <tr class="tableHeader">
  17. <td>' . $totalArr['total'] . '</td>
  18. <td>' . $totalArr['people'] . '</td>
  19. <td>' . $totalArr['time'] . '</td>
  20. </tr>
  21. <tr class="tableHeader">
  22. <td>发出的金币数</td>
  23. <td>领取人数</td>
  24. <td>日期</td>
  25. </tr>';
  26. foreach ($arr as $value) {
  27. $excel
  28. .= '<tr>
  29. <td>' . $value['get_num'] . '</td>
  30. <td>' . $value['num'] . '</td>
  31. <td>' . $value['update_time'] . '</td>
  32. </tr>';
  33. }
  34. $excel .= '</table>';
  35. echo $excel;
  36. exit;
  37. }

个人推荐有第一个方法。

分类: web

标签:   php   excel