This is a creation in Article, where the information may have evolved or changed.
There is a small requirement in the recent project to export the query results to Excel. Before the Java is easier, using the POI can be easily implemented, check the next Golang document, found Golang below and did not export the Excel package, but there is a encoding/csv package, looked under the discovery can export CSV file, As you know, a CSV file is actually a text-formatted Excel file that you can open or import directly from Excel.
It looks good, the problem is resolved, but it turns out that it is better to have an immature language or a library first. Excitedly unloading the test example, the successful export of a text.csv file, everything looks pretty good, but opened after the dumbfounded: Chinese garbled, this problem is actually better understanding, Golang only support Utf-8, and win Chinese version of the default character set is GB2312 (GBK), so it seems that the direct transcoding on the line.
as a result of the loss before, this time we report directly to the file to the code test: directly save the previously exported text.csv as ASCII format, opened and found that the carriage return newline character lost, all become a line. This is depressed, first look at the source bar:
//Writer writes a single CSV record to w along with any necessary quoting.A Record isa slice of strings with each string being one field.func (w*Writer) Write (Record []string) (err error) { forN, field: =Range Record {ifn >0 {if_, Err = W.w.writerune (W.comma); Err! =Nil {return } } If we don'T has to has a quoted field then justWrite out the field and ContinueTo the next field. if!w.fieldneedsquotes (field) {if_, Err = w.w.writestring (field); Err! =Nil {return } Continue } ifErr = W.w.writebyte ('"'); Err! =Nil {return } for_, R1: =Range Field {switch R1 { case'"': _, Err= W.w.writestring ('""') case'\ r': if!w.usecrlf {Err= W.w.writebyte ('\ r')} case'\ n': ifW.usecrlf {_, Err= W.w.writestring ("\ r \ n") } Else{Err= W.w.writebyte ('\ n')} Default: _, Err=W.w.writerune (R1)}ifErr! =Nil {return } } ifErr = W.w.writebyte ('"'); Err! =Nil {return } } ifW.usecrlf {_, Err= W.w.writestring ("\ r \ n") } Else{Err= W.w.writebyte ('\ n') } return}
You can see that the code is simple, and each line is written to the file in CSV format. Note that there is a USERCRLF in writer to specify whether to adapt the carriage return newline character, the default is false, the problem should be here, but after the USERCRLF is set to true, the problem is still, it seems that there is a problem with transcoding.
Since the code is so simple, then it is not as straightforward to implement it yourself, then transcoding the output, here using Iconv-go for transcoding, the implementation of the following:
Package ComponentsImport ( "bytes" "Errors"Iconv"github.com/djimenez/iconv-go")/** *Export Processing*/Const (out_encoding="GBK"//output Encoding)/** *Export CSV format file, output byte array*output encoding specified by out_encoding*/func exportcsv (head []string, data [][]string) (Out []byte, err error) {ifLen (head) = =0 {Err= errors. New ("exportcsv Head is nil") return} columnCount:=Len (head) Datastr:= bytes. Newbufferstring ("") //Add Header forIndex, Headelem: =Range Head {separate:="," ifindex = = ColumnCount-1{Separate="\ n"} datastr.writestring (Headelem+separate)} //Adding data rows for_, DataArray: =Range Data {ifLen (dataarray)! = ColumnCount {//number of data items less than number of columns err= errors. New ("exportcsv data format is error.") } forIndex, Dataelem: =Range DataArray {separate:="," ifindex = = ColumnCount-1{Separate="\ n"} datastr.writestring (Dataelem+separate)} } //processing encoding out=Make ([]byte, Len (Datastr.bytes ())) Iconv. Convert (Datastr.bytes (), Out,"Utf-8", out_encoding)return}
Test it, the export is successful, and there is no garbled problem.
For this project, the CSV that exports the simple format will be sufficient, but not if you want to export complex Excel files. Consider the following several ways to think about it:
- Using CGO, C to achieve the export, this is golang to deal with similar problems of the consistent style, but it is not very good to export Excel, because C export complex format of Excel itself is very troublesome
- Call other language implementation of the module, as to how the tune does not matter, if for a large number of exports, in fact, quite good, you can generate Excel such a time-consuming and laborious operation to separate out
- according to the Excel file format directly into the corresponding binary files, this implementation may be more laborious, but really once and for all, here is attached to an Excel format link , interested can be implemented.