本文实例讲述了golang与PHP输出excel的方法。分享给大家供大家参考,具体如下:
以前输入excel的时候utf8总是乱码还是用其他方式把utf8转换为gbk才能显示,呵呵,其实是输出了csv,后来群里的朋友说需要utf8 BOM Excel才能正常识别utf8,今天测试了一下,很爽,比以前省了好几行代码.
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()
}
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实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?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 , "\xEF\xBB\xBF" ); $head = array ( "编号" , "姓名" , "年龄" ); fputcsv ( $fp , $head ); foreach ( $datas as $r ) { fputcsv ( $fp , $r ); } fclose( $fp ); |
希望本文所述对大家Go语言程序设计有所帮助。