以前输入excel的时候utf8总是乱码还是用其他方式把utf8转换为gbk才能显示,呵呵,其实是输出了csv,后来群里的朋友说需要utf8 BOM Excel才能正常识别utf8,今天测试了一下,很爽,比以前省了好几行代码.呼呼
BOM信息参考:
http://zh.wikipedia.org/wiki/位元組順序記號
golang实现:
package main import ( "os" "encoding/csv" ) func main() { f, err := os.Create("haha2.xls") if err != nil { panic(err) } defer f.Close() f.WriteString("\xEF\xBB\xBF") // 写入UTF-8 BOM w := csv.NewWriter(f) w.Write([]string{"编号","姓名","年龄"}) w.Write([]string{"1","张三","23"}) w.Write([]string{"2","李四","24"}) w.Write([]string{"3","王五","25"}) w.Write([]string{"4","赵六","26"}) w.Flush() }
php实现:
<?php $datas = array( array(1, "张三", 23), array(2, "李四", 24), array(3, "王五", 25), array(4, "赵六", 26), ); header("Content-type:application/vnd.ms-excel"); header("Content-Disposition:filename=".date('YmdHis').".xls"); $fp = fopen('php://output', 'w'); fwrite($fp, pack("H6", "EFBBBF")); $head = array("编号", "姓名", "年龄"); fputcsv($fp, $head); foreach ($datas as $r) { fputcsv($fp, $r); } fclose($fp);
有疑问加站长微信联系(非本文作者)