php导出到Excel 或 CSV (附utf8、gbk 编码转换)

来源:互联网 发布:java调用sql存储过程 编辑:程序博客网 时间:2024/05/16 07:04

php导出到Excel 或 CSV (附utf8、gbk 编码转换)

    博客分类: 
  • Php / Mysql
ExcelPHPFPGmailXP

链接:CSV 导入mysql 数据库

 

php导入到excel-支持utf8和gbk两种编码

 

php导入到excel乱码是因为utf8编码在xp系统不支持所有utf8编码转码一下就完美解决了

utf-8编码案例

 

Php代码  收藏代码
  1. <?php   
  2. header("Content-Type: application/vnd.ms-excel; charset=UTF-8");   
  3. header("Pragma: public");   
  4. header("Expires: 0");   
  5. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");   
  6. header("Content-Type: application/force-download");   
  7. header("Content-Type: application/octet-stream");   
  8. header("Content-Type: application/download");   
  9. header("Content-Disposition: attachment;filename=11.xls ");   
  10. header("Content-Transfer-Encoding: binary ");   
  11. ?>    
 
Php代码  收藏代码
  1. <?   
  2. $filename="php导入到excel-utf-8编码";   
  3. $filename=iconv("utf-8""gb2312"$filename);   
  4. echo $filename;   
  5. ?>   
 

gbk编码案例

 

Php代码  收藏代码
  1. <?php   
  2. header("Content-Type: application/vnd.ms-excel; charset=UTF-8");   
  3. header("Pragma: public");   
  4. header("Expires: 0");   
  5. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");   
  6. header("Content-Type: application/force-download");   
  7. header("Content-Type: application/octet-stream");   
  8. header("Content-Type: application/download");   
  9. header("Content-Disposition: attachment;filename=11.xls ");   
  10. header("Content-Transfer-Encoding: binary ");   
  11. ?>    
 
Php代码  收藏代码
  1. <?   
  2. $filename="php导入到excel-utf-8编码";   
  3. echo $filename;   
  4. ?>   
 

访问网站的时候就下载到excel里面

要弄单元格区别的话

用table表格做网页的就可以了


例如:

 

Php代码  收藏代码
  1. <?php   
  2. header("Content-Type: application/vnd.ms-excel; charset=UTF-8");   
  3. header("Pragma: public");   
  4. header("Expires: 0");   
  5. header("Cache-Control: must-revalidate, post-check=0, pre-check=0");   
  6. header("Content-Type: application/force-download");   
  7. header("Content-Type: application/octet-stream");   
  8. header("Content-Type: application/download");   
  9. header("Content-Disposition: attachment;filename=11.xls ");   
  10. header("Content-Transfer-Encoding: binary ");   
  11.   
  12. $filename="<table>  
  13.             <tr>  
  14.                 <th>left_1</th>  
  15.                 <td>right_1</td>  
  16.             </tr>   
  17.             <tr>  
  18.                 <th>left_2</th>  
  19.                 <td>right_2</td>  
  20.             </tr>  
  21.         </table>";   
  22.   
  23. echo $filename;   
  24. ?>   

 

====================== 其他方法 =============================

 

 

1、制作简单 Excel

 

Php代码  收藏代码
  1. <?php  
  2. header("Content-type:application/vnd.ms-excel");  
  3. header("Content-Disposition:filename=php2excel.xls");  
  4.   
  5. echo "A1\t B1\t C1\n";  
  6. echo "A2\t B2\t C2\n";  
  7. echo "A3\t B3\t C3\n";  
  8. echo "A4\t B4\t C4\n";  
  9. ?>  
 

2、制作简单 CSV 

 

Php代码  收藏代码
  1. <?php  
  2. $action =$_GET['action'];  
  3. if ($action=='make'){  
  4.     $fp = fopen("demo_csv.csv","a"); //打开csv文件,如果不存在则创建  
  5.     $title = array("First_Name","Last_Name","Contact_Email","Telephone"); //第一行数据  
  6.   
  7.     $data_1 = array("42343","423432","4234","4234");   
  8.     $data_2 = array("4234","Last_Name","Contact_Email","Telephone");   
  9.   
  10.     $title = implode(",",$title); //用 ' 分割成字符串  
  11.     $data_1 = implode(",",$data_1); // 用 ' 分割成字符串  
  12.     $data_2 = implode(",",$data_2); // 用 ' 分割成字符串  
  13.   
  14.     $data_str =$title."\r\n".$data_1."\r\n".$data_2."\r\n"//加入换行符  
  15.     fwrite($fp,$data_str); // 写入数据  
  16.     fclose($fp); //关闭文件句柄  
  17.     echo "生成成功";  
  18. }  
  19. echo "<br>";  
  20. echo "<a href='?action=make'>生成csv文件</a>";  
  21. ?>  

 

也可以做一个封闭函数:

 

封闭函数一:

 

Php代码  收藏代码
  1. function exportToCsv($csv_data$filename = 'export.csv') {  
  2.     $csv_terminated = "\n";  
  3.     $csv_separator = ",";  
  4.     $csv_enclosed = '"';  
  5.     $csv_escaped = "\\";  
  6.   
  7.     // Gets the data from the database  
  8.     $schema_insert = '';  
  9.   
  10.     $out = '';  
  11.   
  12.     // Format the data  
  13.     foreach ($csv_data as $row)  
  14.     {  
  15.         $schema_insert = '';  
  16.         $fields_cnt = count($row);  
  17.         //printr($row);  
  18.         $tmp_str = '';  
  19.         foreach($row as $v)  
  20.         {  
  21.             $tmp_str .= $csv_enclosed.str_replace($csv_enclosed$csv_escaped . $csv_enclosed$v).$csv_enclosed.$csv_separator;  
  22.         } // end for  
  23.           
  24.         $tmp_str = substr($tmp_str, 0, -1);  
  25.         $schema_insert .= $tmp_str;  
  26.   
  27.         $out .= $schema_insert;  
  28.         $out .= $csv_terminated;  
  29.     } // end while  
  30.   
  31.     header("Cache-Control: must-revalidate, post-check=0, pre-check=0");  
  32.     header("Content-Length: " . strlen($out));  
  33.     header("Content-type: text/x-csv");  
  34.     header("Content-Disposition:filename=$filename");  
  35.   
  36.     echo $out;  
  37. }  
  38.   
  39. /* 
  40. $csv_data = array(array('Name', 'Address')); 
  41. array_push($csv_data, array($row['name'],$row['address'])); 
  42. ... 
  43.  
  44. exportToCsv($csv_data,'new_file.csv'); 
  45. */  
 

 

封闭函数二:

 

Php代码  收藏代码
  1. <?  
  2. /** 
  3.  * Simple class to properly output CSV data to clients. PHP 5 has a built 
  4.  * in method to do the same for writing to files (fputcsv()), but many times 
  5.  * going right to the client is beneficial. 
  6.  * 
  7.  * @author Jon Gales 
  8.  */  
  9.   
  10. class CSV_Writer {  
  11.   
  12.     public $data = array();  
  13.     public $deliminator;  
  14.   
  15.     /** 
  16.      * Loads data and optionally a deliminator. Data is assumed to be an array 
  17.      * of associative arrays. 
  18.      * 
  19.      * @param array $data 
  20.      * @param string $deliminator 
  21.      */  
  22.     function __construct($data$deliminator = ",")  
  23.     {  
  24.         if (!is_array($data))  
  25.         {  
  26.             throw new Exception('CSV_Writer only accepts data as arrays');  
  27.         }  
  28.   
  29.         $this->data = $data;  
  30.         $this->deliminator = $deliminator;  
  31.     }  
  32.   
  33.     private function wrap_with_quotes($data)  
  34.     {  
  35.         $data = preg_replace('/"(.+)"/''""$1""'$data);  
  36.         return sprintf('"%s"'$data);  
  37.     }  
  38.   
  39.     /** 
  40.      * Echos the escaped CSV file with chosen delimeter 
  41.      * 
  42.      * @return void 
  43.      */  
  44.     public function output()  
  45.     {  
  46.         foreach ($this->data as $row)  
  47.         {  
  48.             $quoted_data = array_map(array('CSV_Writer''wrap_with_quotes'), $row);  
  49.             echo sprintf("%s\n", implode($this->deliminator, $quoted_data));  
  50.         }  
  51.     }  
  52.   
  53.     /** 
  54.      * Sets proper Content-Type header and attachment for the CSV outpu 
  55.      * 
  56.      * @param string $name 
  57.      * @return void 
  58.      */  
  59.     public function headers($name)  
  60.     {  
  61.         header('Content-Type: application/csv');  
  62.         header("Content-disposition: attachment; filename={$name}.csv");  
  63.     }  
  64. }  
  65.   
  66. /* 
  67. //$data = array(array("one","two","three"), array(4,5,6)); 
  68.  
  69. $data[] = array("one","two","three"); 
  70. $data[] = array(4,5,6); 
  71.  
  72. $csv = new CSV_Writer($data); 
  73. $csv->headers('test'); 
  74. $csv->output(); 
  75. */  
 

 

 

3. 使用excel类

 

Php代码  收藏代码
  1. <?php  
  2. require_once 'Spreadsheet/Writer.php';  
  3.   
  4. $workbook = new Spreadsheet_Excel_Writer();  
  5.   
  6. /* 生成 CSV 
  7. $filename = date('YmdHis').'.csv'; 
  8. $workbook->send($filename); // 发送 Excel 文件名供下载 
  9. */  
  10.   
  11. // 生成 Excel  
  12. $filename = date('YmdHis').'.xls';  
  13. $workbook->send($filename); // 发送 Excel 文件名供下载  
  14.   
  15.   
  16. $workbook->setVersion(8);  
  17. $workbook->setBIFF8InputEncoding('UTF-8');  
  18.   
  19. $worksheet =& $workbook->addWorksheet("Sheet-1");  
  20.   
  21. $data[]= array('id','username','company','email','mob','daytime','intent');  
  22. $data[] = array(1,'老梁','**工作室','myemail@gmail.com','1363137966*',time(),'y');  
  23.   
  24.   
  25. $total_row = count($data);  
  26. $total_col = count($data[0]);  
  27. for ($row = 0; $row < $total_row$row ++) {  
  28.    for ($col = 0; $col < $total_col$col ++) {  
  29.         $worksheet->writeString($row$col$data[$row][$col]); // 在 sheet-1 中写入数据  
  30.    }  
  31. }  
  32.   
  33. /* 
  34. $worksheet =& $workbook->addWorksheet("Sheet-2"); 
  35.  
  36. $data[]= array('id','username','company','email','mob','daytime','intent'); 
  37. $data[] = array(1,'老梁','**工作室','myemail@gmail.com','1363137966*',time(),'y'); 
  38.  
  39.  
  40. $total_row = count($data); 
  41. $total_col = count($data[0]); 
  42. for ($row = 0; $row < $total_row; $row ++) { 
  43.    for ($col = 0; $col < $total_col; $col ++) { 
  44.         $worksheet->writeString($row, $col, $data[$row][$col]); // 在 sheet-2 中写入数据 
  45.    } 
  46. } 
  47.  
  48. */  
  49.   
  50. $workbook->close(); // 完成下载  
  51.   
  52. ?>  
 

 

类二

 

-----函数说明
读取Excel文件 
function Read_Excel_File($ExcelFile,$Result) 

$ExcelFile    Excel文件名
$Result        返回的结果
函数返回值    正常返回0,否则返回错误信息

返回的值数组 
    $result[sheet名][行][列] 的值为相应Excel Cell的值
    
建立Excel文件    
function Create_Excel_File($ExcelFile,$Data) 

$ExcelFile    Excel文件名
$Data        Excel表格数据
请把函数写在PHP脚本的开头

例1:

 

Php代码  收藏代码
  1. <?  
  2. require "excel_class.php";  
  3.   
  4. Read_Excel_File("Book1.xls",$return);  
  5.   
  6. for ($i=0;$i<count($return[Sheet1]);$i++)  
  7. {  
  8.     for ($j=0;$j<count($return[Sheet1][$i]);$j++)  
  9.     {  
  10.         echo $return[Sheet1][$i][$j]."|";  
  11.     }  
  12.     echo "<br>";  
  13. }  
  14. ?>  
 

例2:

 

Php代码  收藏代码
  1. <?  
  2. require "excel_class.php";  
  3.   
  4. Read_Excel_File("Book1.xls",$return);  
  5. Create_Excel_File("ddd.xls",$return[Sheet1]);  
  6. ?>  
 

 

 

 

 

 

 

  • excel_class.zip (10.6 KB)
  • 下载次数: 133
  • spreadsheet_excel.rar (283.7 KB)
  • 下载次数: 186
原创粉丝点击