The Go language and Excel serialization and deserialization (1)

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Many times, especially in game development, planning tends to write documents, data, etc. into Excel, programs that need to parse excel in various ways so that the program can be read.

Common scenarios include the following:

1. Convert Excel to CSV, comma split, and the program is converted by a split comma in a specific format. (The function is not strong enough, the format is very strict, cannot flexibly configure many special functions)

2. Convert Excel to Lua table. This is a common way of developing C + + games. (cannot be serialized as Excel by C + + objects)

3. Convert Excel to a table in the database. Like Scenario 2, the difference is that this is a table that is converted to a database. (cannot be serialized as Excel by C + + objects)

4. Convert Excel to XML format, and then serialize and deserialize through a framework that supports XML serialization and deserialization, such as Simple_xml in Java.

5 .....



Why do you do this? Game development, the first thing to be clear, when a function to develop, the first is not to plan the table, but the program first in accordance with the approximate scheme, to create the corresponding object data, with the object, type, Serialize the type to. xml then, plan to add the configuration according to the. xml format, and whenever a new feature is added, the program adds a new type based on the original type, reads the original XML, regenerates the XML file with the new type, and then plans to simply add the new attributes, in which case the program changes very little , the point of attention, also only on the new attributes.


We write a simple example of serialization:

/** * Created by Administrator on 13-12-25. */package mainimport ("FMT" "OS" "Reflect" "Encoding/xml") var xmlhead []byte = []byte ("<?xml version=\" 1.0\ "encoding= \ "Utf-8\" standalone=\ "yes\"? ><?mso-application progid=\ "Excel.sheet\"?> ") type Workbook struct {Xmlns str ing ' xml: ' xmlns,attr ' ' xmlns_o string ' xml: ' xmlns:o,attr ' ' xmlns_x string ' xml: ' xmlns:x,attr ' ' Xmlns_ss stri    Ng ' xml: ' xmlns:ss,attr ' ' xmlns_html string ' xml: ' xmlns:html,attr ' ' Xmlns_dt string ' xml: ' xmlns:dt,attr ' ' worksheets []worksheet ' xml: "Worksheet" '}func newworkbook () *workbook {return &workbook{xmlns: "Urn:schemas-microsoft-com:o Ffice:spreadsheet ", Xmlns_o:" Urn:schemas-microsoft-com:office:office ", Xmlns_x:" Urn:schemas-microsoft-com:office : Excel ", Xmlns_ss:" Urn:schemas-microsoft-com:office:spreadsheet ", xmlns_html:" Http://www.w3.org/TR/REC-html40 ", XMLNS_DT: "uuid:c2f41010-65b3-11d1-a29f-00aa00c14882"}}type Worksheet struct {Name string ' xml: ' ss:name,attr ' ' Table Table ' xml: ' table '}type Table struct {expandedcolumncount int ' xml: "ss:expandedcolumncount,attr" '//attribute number ExpandedRowCount int ' xml: "SS: Expandedrowcount,attr "'///Data bar number fullcolumns int ' xml:" x:fullcolumns,attr "' fullrows int ' xml:" X:full Rows,attr "' Defaultcolumnwidth float32 ' xml:" ss:defaultcolumnwidth,attr "' defaultrowheight float32 ' xml:" Ss:d Efaultrowheight,attr "' Rows []row ' xml:" Row "'}func newtable (columnCount, RowCount int) *table {return &amp ; Table{expandedcolumncount:columncount,expandedrowcount:rowcount,fullcolumns:1,fullrows:1,defaultcolumnwidth:60  , Defaultrowheight:16}}type Row struct {Cells []cell ' xml: "cell" '}type cell struct {data data ' xml: ' Data ' '}type data struct  {Type string ' xml: ' ss:type,attr ' ' Value interface{} ' xml: ', Chardata '}func Newcell (_type string, _value interface{}) Cell {data: = Data{type: _type, Value: _value}cell: = Cell{data:data}return cell}func marshalexcelxml (arr []interface {} ) {var name string = "Unknow" Book: = NewworkboOk () Sheet: = Worksheet{}columncount, RowCount: = 0, Len (arr) for _, V: = range arr {if V! = Nil {t: = reflect. TypeOf (v) name = T.name () + "s" ColumnCount = T.numfield () break}}fmt. fprintf (OS. Stdout, "name%s ColumnCount%d, RowCount%d\n", name, ColumnCount, RowCount) if ColumnCount > 0 && rowCount ; 0 {table: = newtable (ColumnCount, RowCount) fmt. fprintf (OS. Stdout, "Table%v\n", table) Rows: = Make ([]row, RowCount) for index: = 0; Index < RowCount; index++ {fmt. fprintf (OS. Stdout, "index =%d v =%v\n", index, Arr[index]) if arr[index]! = Nil {val: = reflect. ValueOf (Arr[index]) Cells: = Make ([]cell, ColumnCount) for I: = 0; i < ColumnCount; i++ {fieldvalue: = val. Field (i) fmt. fprintf (OS. Stdout, "Fieldvalue%v Type%v \ n", Fieldvalue, Fieldvalue.type ()) var cell cellswitch Fieldvalue.kind () {case reflect. Int:cell = Newcell ("number", Fieldvalue.int ()) case reflect. String:cell = Newcell ("String", Fieldvalue.string ())}cells[i] = Cell}rows[index]. Cells = cells}}table. Rows = Rowssheet. Name = "Tasks" sheet. Table = *tablebook. worksheets = Make ([]worksheet, 1) book. Worksheets[0] = SHEETF, err: = OS. OpenFile ("c:/" +name+ ". xml", OS. O_wronly|os. O_create|os. O_trunc, OS. Modeappend) defer f.close () if err! = Nil {fmt. fprintf (OS. Stderr, "Error:%s", err. Error ()) return}n, err: = F.write (xmlhead) If err = = Nil && n < len (xmlhead) {fmt. fprintf (OS. Stderr, "Error:write Fail") return}buf, err: = XML. Marshal (book) if Err! = Nil {fmt. fprintf (OS. Stderr, "Error:%s", err. Error ()) return}n, err = F.write (buf) If err = = Nil && n < len (buf) {fmt. fprintf (OS. Stderr, "Error:write Fail") return}}}type Task struct{id intname stringName1 string}func Main () {T asks: = []interface{}{task{1, "T1", "T1_1"}, Task{2, "T2", "T2_1"}, Task{3, "T3", "T3_1"}}marshalexcelxml (Tasks)}




The generated. xml file:

<?xml version= "1.0" encoding= "UTF-8" standalone= "yes"? ><?mso-application progid= "Excel.Sheet"?>< Workbook xmlns= "Urn:schemas-microsoft-com:office:spreadsheet" xmlns:o= "Urn:schemas-microsoft-com:office:office" x mlns:x= "Urn:schemas-microsoft-com:office:excel" xmlns:ss= "Urn:schemas-microsoft-com:office:spreadsheet" xmlns:ht Ml= "Http://www.w3.org/TR/REC-html40" xmlns:dt= "uuid:c2f41010-65b3-11d1-a29f-00aa00c14882" > <worksheet SS:               Name= "Tasks" > <table ss:expandedcolumncount= "3" ss:expandedrowcount= "3" x:fullcolumns= "1" x:fullrows= "1"                    Ss:defaultcolumnwidth= "ss:defaultrowheight=" > <Row> <Cell>                    <data ss:type= "number" >1</Data> </Cell> <Cell>                    <data ss:type= "String" >t1</Data> </Cell> <Cell> <data ss:type= "String" >t1_1</Data> </Cell> </Row> <Row> <Cell>                    <data ss:type= "number" >2</Data> </Cell> <Cell>                    <data ss:type= "String" >t2</Data> </Cell> <Cell>            <data ss:type= "String" >t2_1</Data> </Cell> </Row> <Row> <Cell> <data ss:type= "number" >3</Data> &lt ;/cell> <Cell> <data ss:type= "String" >t3</Data> < /cell> <Cell> <data ss:type= "String" >t3_1</Data> &lt ;/cell> </Row> </Table> </Worksheet></Workbook>

Open directly from Excel:

1 T1 T1_1
2 T2 T2_1
3 T3 T3_1

Reprint please specify the source:

http://blog.csdn.net/eclipser1987/article/details/17691745


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.