本文實例講述了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()
}
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, "\xEF\xBB\xBF"); $head = array("編號", "姓名", "年齡"); fputcsv($fp, $head); foreach ($datas as $r) { fputcsv($fp, $r); } fclose($fp);
希望本文所述對大家Go語言程序設計有所幫助。