本文實(shí)例講述了golang與PHP輸出excel的方法。分享給大家供大家參考,具體如下:
以前輸入excel的時候utf8總是亂碼還是用其他方式把utf8轉(zhuǎn)換為gbk才能顯示,呵呵,其實(shí)是輸出了csv,后來群里的朋友說需要utf8 BOM Excel才能正常識別utf8,今天測試了一下,很爽,比以前省了好幾行代碼.
golang實(shí)現(xiàn):
代碼如下:
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實(shí)現(xiàn):
代碼如下:
<?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語言程序設(shè)計有所幫助。