Skip to content

Commit a9d3ee2

Browse files
committed
Init commit.
0 parents  commit a9d3ee2

12 files changed

+1237
-0
lines changed

README.md

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
* Excelize
2+
3+
![Excelize](./excelize.png "Excelize")
4+
5+
** Introduction
6+
Excelize is a library written in pure Golang and providing a set of function that allow you to write to and read from XLSX files.
7+
8+
9+
10+
** Basic Usage
11+
12+
*** Installation
13+
14+
```
15+
go get github.com/luxurioust/excelize
16+
```
17+
18+
*** Create XLSX files
19+
20+
Here is a minimal example usage that will create XLSX file.
21+
22+
```
23+
package main
24+
25+
import (
26+
"fmt"
27+
"github.com/luxurioust/excelize"
28+
)
29+
30+
func main() {
31+
xlsx := excelize.CreateFile()
32+
xlsx = excelize.NewSheet(xlsx, 2, "Sheet2")
33+
xlsx = excelize.NewSheet(xlsx, 3, "Sheet3")
34+
xlsx = excelize.SetCellInt(xlsx, "Sheet2", "A23", 10)
35+
xlsx = excelize.SetCellStr(xlsx, "Sheet3", "B20", "Hello")
36+
err := excelize.Save(xlsx, "~/Workbook.xlsx")
37+
if err != nil {
38+
fmt.Println(err)
39+
}
40+
}
41+
```
42+
43+
*** Writing XLSX files
44+
45+
The following constitutes the bare minimum required to write an XLSX document.
46+
47+
```
48+
package main
49+
50+
import (
51+
"fmt"
52+
"github.com/luxurioust/excelize"
53+
)
54+
55+
func main() {
56+
xlsx, err := excelize.Openxlsx("~/Workbook.xlsx")
57+
if err != nil {
58+
fmt.Println(err)
59+
}
60+
xlsx = excelize.SetCellInt(xlsx, "Sheet2", "B2", 100)
61+
xlsx = excelize.SetCellStr(xlsx, "Sheet2", "C11", "Hello")
62+
xlsx = excelize.NewSheet(xlsx, 3, "TestSheet")
63+
xlsx = excelize.SetCellInt(xlsx, "Sheet3", "A23", 10)
64+
xlsx = excelize.SetCellStr(xlsx, "Sheet3", "b230", "World")
65+
xlsx = excelize.SetActiveSheet(xlsx, 2)
66+
if err != nil {
67+
fmt.Println(err)
68+
}
69+
err = excelize.Save(xlsx, "~/Workbook.xlsx")
70+
}
71+
```
72+
73+
** Contributing
74+
75+
Contributions are welcome! Open a pull request to fix a bug, or open an issue to discuss a new feature or change.
76+
77+
** Licenses
78+
79+
This program is under the terms of the BSD 3-Clause License. See <https://opensource.org/licenses/BSD-3-Clause>.

excelize.go

+196
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
package excelize
2+
3+
import (
4+
"archive/zip"
5+
"encoding/xml"
6+
"fmt"
7+
"strconv"
8+
"strings"
9+
)
10+
11+
type FileList struct {
12+
Key string
13+
Value string
14+
}
15+
16+
// OpenFile() take the name of an XLSX file and returns a populated
17+
// xlsx.File struct for it.
18+
func OpenFile(filename string) (file []FileList, err error) {
19+
var f *zip.ReadCloser
20+
f, err = zip.OpenReader(filename)
21+
if err != nil {
22+
return nil, err
23+
}
24+
file, err = ReadZip(f)
25+
return
26+
}
27+
28+
// Set int type value of a cell
29+
func SetCellInt(file []FileList, sheet string, axis string, value int) []FileList {
30+
axis = strings.ToUpper(axis)
31+
var xlsx xlsxWorksheet
32+
col := getColIndex(axis)
33+
row := getRowIndex(axis)
34+
xAxis := row - 1
35+
yAxis := titleToNumber(col)
36+
37+
name := fmt.Sprintf("xl/worksheets/%s.xml", strings.ToLower(sheet))
38+
xml.Unmarshal([]byte(readXml(file, name)), &xlsx)
39+
40+
rows := xAxis + 1
41+
cell := yAxis + 1
42+
43+
xlsx = checkRow(xlsx)
44+
45+
xlsx = completeRow(xlsx, rows, cell)
46+
xlsx = completeCol(xlsx, rows, cell)
47+
48+
xlsx.SheetData.Row[xAxis].C[yAxis].T = ""
49+
xlsx.SheetData.Row[xAxis].C[yAxis].V = strconv.Itoa(value)
50+
51+
output, err := xml.MarshalIndent(xlsx, "", "")
52+
if err != nil {
53+
fmt.Println(err)
54+
}
55+
saveFileList(file, name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
56+
return file
57+
}
58+
59+
// Set string type value of a cell
60+
func SetCellStr(file []FileList, sheet string, axis string, value string) []FileList {
61+
axis = strings.ToUpper(axis)
62+
var xlsx xlsxWorksheet
63+
col := getColIndex(axis)
64+
row := getRowIndex(axis)
65+
xAxis := row - 1
66+
yAxis := titleToNumber(col)
67+
68+
name := fmt.Sprintf("xl/worksheets/%s.xml", strings.ToLower(sheet))
69+
xml.Unmarshal([]byte(readXml(file, name)), &xlsx)
70+
71+
rows := xAxis + 1
72+
cell := yAxis + 1
73+
74+
xlsx = checkRow(xlsx)
75+
xlsx = completeRow(xlsx, rows, cell)
76+
xlsx = completeCol(xlsx, rows, cell)
77+
78+
xlsx.SheetData.Row[xAxis].C[yAxis].T = "str"
79+
xlsx.SheetData.Row[xAxis].C[yAxis].V = value
80+
81+
output, err := xml.MarshalIndent(xlsx, "", "")
82+
if err != nil {
83+
fmt.Println(err)
84+
}
85+
saveFileList(file, name, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
86+
return file
87+
}
88+
89+
// Completion column element tags of XML in a sheet
90+
func completeCol(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
91+
if len(xlsx.SheetData.Row) < cell {
92+
for i := len(xlsx.SheetData.Row); i < cell; i++ {
93+
xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
94+
R: i + 1,
95+
})
96+
}
97+
}
98+
for k, v := range xlsx.SheetData.Row {
99+
if len(v.C) < cell {
100+
start := len(v.C)
101+
for iii := start; iii < cell; iii++ {
102+
xlsx.SheetData.Row[k].C = append(xlsx.SheetData.Row[k].C, xlsxC{
103+
R: toAlphaString(iii+1) + strconv.Itoa(k+1),
104+
})
105+
}
106+
}
107+
}
108+
return xlsx
109+
}
110+
111+
// Completion row element tags of XML in a sheet
112+
func completeRow(xlsx xlsxWorksheet, row int, cell int) xlsxWorksheet {
113+
if len(xlsx.SheetData.Row) < row {
114+
for i := len(xlsx.SheetData.Row); i < row; i++ {
115+
xlsx.SheetData.Row = append(xlsx.SheetData.Row, xlsxRow{
116+
R: i + 1,
117+
})
118+
}
119+
120+
for ii := 0; ii < row; ii++ {
121+
start := len(xlsx.SheetData.Row[ii].C)
122+
if start == 0 {
123+
for iii := start; iii < cell; iii++ {
124+
xlsx.SheetData.Row[ii].C = append(xlsx.SheetData.Row[ii].C, xlsxC{
125+
R: toAlphaString(iii+1) + strconv.Itoa(ii+1),
126+
})
127+
}
128+
}
129+
}
130+
}
131+
return xlsx
132+
}
133+
134+
// Replace xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Office Excel 2007
135+
func replaceWorkSheetsRelationshipsNameSpace(workbookMarshal string) string {
136+
oldXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
137+
newXmlns := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" xmlns:xm="http://schemas.microsoft.com/office/excel/2006/main">`
138+
workbookMarshal = strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
139+
workbookMarshal = strings.Replace(workbookMarshal, `></sheetPr>`, ` />`, -1)
140+
workbookMarshal = strings.Replace(workbookMarshal, `></dimension>`, ` />`, -1)
141+
workbookMarshal = strings.Replace(workbookMarshal, `></selection>`, ` />`, -1)
142+
workbookMarshal = strings.Replace(workbookMarshal, `></sheetFormatPr>`, ` />`, -1)
143+
workbookMarshal = strings.Replace(workbookMarshal, `></printOptions>`, ` />`, -1)
144+
workbookMarshal = strings.Replace(workbookMarshal, `></pageSetup>`, ` />`, -1)
145+
workbookMarshal = strings.Replace(workbookMarshal, `></pageMargins>`, ` />`, -1)
146+
workbookMarshal = strings.Replace(workbookMarshal, `></headerFooter>`, ` />`, -1)
147+
workbookMarshal = strings.Replace(workbookMarshal, `></drawing>`, ` />`, -1)
148+
return workbookMarshal
149+
}
150+
151+
// Check XML tags and fix discontinuous case, for example:
152+
//
153+
// <row r="15" spans="1:22" x14ac:dyDescent="0.2">
154+
// <c r="A15" s="2" />
155+
// <c r="B15" s="2" />
156+
// <c r="F15" s="1" />
157+
// <c r="G15" s="1" />
158+
// </row>
159+
//
160+
// in this case, we should to change it to
161+
//
162+
// <row r="15" spans="1:22" x14ac:dyDescent="0.2">
163+
// <c r="A15" s="2" />
164+
// <c r="B15" s="2" />
165+
// <c r="C15" s="2" />
166+
// <c r="D15" s="2" />
167+
// <c r="E15" s="2" />
168+
// <c r="F15" s="1" />
169+
// <c r="G15" s="1" />
170+
// </row>
171+
//
172+
func checkRow(xlsx xlsxWorksheet) xlsxWorksheet {
173+
for k, v := range xlsx.SheetData.Row {
174+
lenCol := len(v.C)
175+
endR := getColIndex(v.C[lenCol-1].R)
176+
endRow := getRowIndex(v.C[lenCol-1].R)
177+
endCol := titleToNumber(endR)
178+
if lenCol < endCol {
179+
oldRow := xlsx.SheetData.Row[k].C
180+
xlsx.SheetData.Row[k].C = xlsx.SheetData.Row[k].C[:0]
181+
tmp := []xlsxC{}
182+
for i := 0; i <= endCol; i++ {
183+
fixAxis := toAlphaString(i+1) + strconv.Itoa(endRow)
184+
tmp = append(tmp, xlsxC{
185+
R: fixAxis,
186+
})
187+
}
188+
xlsx.SheetData.Row[k].C = tmp
189+
for _, y := range oldRow {
190+
colAxis := titleToNumber(getColIndex(y.R))
191+
xlsx.SheetData.Row[k].C[colAxis] = y
192+
}
193+
}
194+
}
195+
return xlsx
196+
}

excelize.png

42.5 KB
Loading

excelize_test.go

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package excelize
2+
3+
import (
4+
"fmt"
5+
"math/rand"
6+
"sync"
7+
"testing"
8+
"time"
9+
)
10+
11+
var (
12+
once sync.Once
13+
)
14+
15+
func testSetup() {
16+
rand.Seed(time.Now().UnixNano())
17+
}
18+
19+
func TestExcelize(t *testing.T) {
20+
// Test update a XLSX file
21+
file, err := OpenFile("./test/Workbook1.xlsx")
22+
if err != nil {
23+
fmt.Println(err)
24+
}
25+
file = SetCellInt(file, "SHEET2", "B2", 100)
26+
file = SetCellStr(file, "SHEET2", "C11", "Knowns")
27+
file = NewSheet(file, 3, "TestSheet")
28+
file = SetCellInt(file, "Sheet3", "A23", 10)
29+
file = SetCellStr(file, "SHEET3", "b230", "10")
30+
file = SetActiveSheet(file, 2)
31+
if err != nil {
32+
fmt.Println(err)
33+
}
34+
for i := 1; i <= 300; i++ {
35+
file = SetCellStr(file, "SHEET3", fmt.Sprintf("c%d", i), randToken(5))
36+
}
37+
err = Save(file, "./test/Workbook_2.xlsx")
38+
39+
// Test create a XLSX file
40+
file2 := CreateFile()
41+
file2 = NewSheet(file2, 2, "SHEETxxx")
42+
file2 = NewSheet(file2, 3, "asd")
43+
file2 = SetCellInt(file2, "Sheet2", "A23", 10)
44+
file2 = SetCellStr(file2, "SHEET1", "B20", "10")
45+
err = Save(file2, "./test/Workbook_3.xlsx")
46+
if err != nil {
47+
fmt.Println(err)
48+
}
49+
}
50+
51+
func randToken(length int) string {
52+
b := make([]byte, length)
53+
rand.Read(b)
54+
return fmt.Sprintf("%x", b)
55+
}

file.go

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
package excelize
2+
3+
import (
4+
"archive/zip"
5+
"bytes"
6+
"fmt"
7+
"os"
8+
)
9+
10+
// Create a new xlsx file
11+
//
12+
// For example:
13+
//
14+
// xlsx := CreateFile()
15+
//
16+
func CreateFile() []FileList {
17+
var file []FileList
18+
file = saveFileList(file, `_rels/.rels`, TEMPLATE_RELS)
19+
file = saveFileList(file, `docProps/app.xml`, TEMPLATE_DOCPROPS_APP)
20+
file = saveFileList(file, `docProps/core.xml`, TEMPLATE_DOCPROPS_CORE)
21+
file = saveFileList(file, `xl/_rels/workbook.xml.rels`, TEMPLATE_WORKBOOK_RELS)
22+
file = saveFileList(file, `xl/theme/theme1.xml`, TEMPLATE_THEME)
23+
file = saveFileList(file, `xl/worksheets/sheet1.xml`, TEMPLATE_SHEET)
24+
file = saveFileList(file, `xl/styles.xml`, TEMPLATE_STYLES)
25+
file = saveFileList(file, `xl/workbook.xml`, TEMPLATE_WORKBOOK)
26+
file = saveFileList(file, `[Content_Types].xml`, TEMPLATE_CONTENT_TYPES)
27+
return file
28+
}
29+
30+
// Save after create or update to an xlsx file at the provided path.
31+
func Save(files []FileList, name string) error {
32+
buf := new(bytes.Buffer)
33+
w := zip.NewWriter(buf)
34+
for _, file := range files {
35+
f, err := w.Create(file.Key)
36+
if err != nil {
37+
fmt.Println(err)
38+
}
39+
_, err = f.Write([]byte(file.Value))
40+
if err != nil {
41+
return err
42+
}
43+
}
44+
err := w.Close()
45+
if err != nil {
46+
return err
47+
}
48+
f, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
49+
if err != nil {
50+
return err
51+
}
52+
buf.WriteTo(f)
53+
return err
54+
}

0 commit comments

Comments
 (0)