This repository has been archived by the owner on Nov 27, 2019. It is now read-only.
forked from psmithuk/xlsx
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathxlsx.go
529 lines (437 loc) · 10.7 KB
/
xlsx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Package implements creation of XLSX simple spreadsheet files
package xlsx
import (
"archive/zip"
"bufio"
"fmt"
"html"
"io"
"os"
"strconv"
"time"
)
type CellType uint
// Basic spreadsheet cell types
const (
CellTypeNumber CellType = iota
CellTypeString
CellTypeDate
CellTypeDatetime
CellTypeInlineString
)
// XLSX Spreadsheet Cell
type Cell struct {
Type CellType
Value string
Colspan uint64
Rowspan uint64
}
// XLSX Spreadsheet Row
type Row struct {
Cells []Cell
}
// XLSX Spreadsheet Column
type Column struct {
Name string
Width uint64
}
// XLSX Workbook Document Properties
type DocumentInfo struct {
CreatedBy string
ModifiedBy string
CreatedAt time.Time
ModifiedAt time.Time
}
// XLSX Spreadsheet
type Sheet struct {
Title string
columns []Column
rows []Row
sharedStringMap map[string]int
sharedStrings []string
DocumentInfo DocumentInfo
}
// Create a sheet with no dimensions
func NewSheet() Sheet {
c := make([]Column, 0)
r := make([]Row, 0)
ssm := make(map[string]int)
sst := make([]string, 0)
s := Sheet{
Title: "Data",
columns: c,
rows: r,
sharedStringMap: ssm,
sharedStrings: sst,
}
return s
}
// Create a sheet with dimensions derived from the given columns
func NewSheetWithColumns(c []Column) Sheet {
r := make([]Row, 0)
ssm := make(map[string]int)
sst := make([]string, 0)
s := Sheet{
Title: "Data",
columns: c,
rows: r,
sharedStringMap: ssm,
sharedStrings: sst,
}
s.DocumentInfo.CreatedBy = "xlsx.go"
s.DocumentInfo.CreatedAt = time.Now()
s.DocumentInfo.ModifiedBy = s.DocumentInfo.CreatedBy
s.DocumentInfo.ModifiedAt = s.DocumentInfo.CreatedAt
return s
}
// Create a new row with a length caculated by the sheets known column count
func (s *Sheet) NewRow() Row {
c := make([]Cell, len(s.columns))
r := Row{
Cells: c,
}
return r
}
// Append a row to the sheet
func (s *Sheet) AppendRow(r Row) error {
if len(r.Cells) != len(s.columns) {
return fmt.Errorf("the given row has %d cells and %d were expected", len(r.Cells), len(s.columns))
}
cells := make([]Cell, len(s.columns))
for n, c := range r.Cells {
cells[n].Type = c.Type
cells[n].Value = c.Value
if cells[n].Type == CellTypeString {
// calculate string reference
cells[n].Value = html.EscapeString(cells[n].Value)
i, exists := s.sharedStringMap[cells[n].Value]
if !exists {
i = len(s.sharedStrings)
s.sharedStringMap[cells[n].Value] = i
s.sharedStrings = append(s.sharedStrings, cells[n].Value)
}
cells[n].Value = strconv.Itoa(i)
}
}
row := s.NewRow()
row.Cells = cells
s.rows = append(s.rows, row)
return nil
}
// Get the Shared Strings in the order they were added to the map
func (s *Sheet) SharedStrings() []string {
return s.sharedStrings
}
// Given zero-based array indices output the Excel cell reference. For
// example (0,0) => "A1"; (2,2) => "C3"; (26,45) => "AA46"
func CellIndex(x, y uint64) (string, uint64) {
return colName(x), (y + 1)
}
// From a zero-based column number return the Excel column name.
// For example: 0 => "A"; 2 => "C"; 26 => "AA"
func colName(n uint64) string {
var s string
n += 1
for n > 0 {
n -= 1
s = string(65+(n%26)) + s
n /= 26
}
return s
}
// Convert time to the OLE Automation format.
func OADate(d time.Time) string {
epoch := time.Date(1899, 12, 30, 0, 0, 0, 0, time.UTC)
nsPerDay := 24 * time.Hour
v := -1 * float64(epoch.Sub(d)) / float64(nsPerDay)
// TODO: deal with dates before epoch
// e.g. http://stackoverflow.com/questions/15549823/oadate-to-milliseconds-timestamp-in-javascript/15550284#15550284
if d.Hour() == 0 && d.Minute() == 0 && d.Second() == 0 {
return fmt.Sprintf("%d", int64(v))
} else {
return fmt.Sprintf("%f", v)
}
}
// Create filename and save the XLSX file
func (s *Sheet) SaveToFile(filename string) error {
outputfile, err := os.Create(filename)
if err != nil {
return err
}
w := bufio.NewWriter(outputfile)
err = s.SaveToWriter(w)
defer w.Flush()
return err
}
// Save the XLSX file to the given writer
func (s *Sheet) SaveToWriter(w io.Writer) error {
ww := NewWorkbookWriter(w)
sw, err := ww.NewSheetWriter(s)
if err != nil {
return err
}
err = sw.WriteRows(s.rows)
if err != nil {
return err
}
ww.SharedStrings = s.sharedStrings
err = ww.Close()
return err
}
// Write the header files of the workbook
func (ww *WorkbookWriter) WriteHeader() error {
if ww.headerWritten {
panic("Workbook header already written")
}
z := ww.zipWriter
f, err := z.Create("[Content_Types].xml")
if err != nil {
return err
}
err = TemplateContentTypes.Execute(f, ww.sheetNames)
if err != nil {
return err
}
f, err = z.Create("docProps/app.xml")
if err != nil {
return err
}
err = TemplateApp.Execute(f, ww.sheetNames)
if err != nil {
return err
}
f, err = z.Create("docProps/core.xml")
if err != nil {
return err
}
err = TemplateCore.Execute(f, ww.documentInfo)
if err != nil {
return err
}
f, err = z.Create("_rels/.rels")
if err != nil {
return err
}
err = TemplateRelationships.Execute(f, nil)
if err != nil {
return err
}
f, err = z.Create("xl/workbook.xml")
if err != nil {
return err
}
err = TemplateWorkbook.Execute(f, ww.sheetNames)
if err != nil {
return err
}
f, err = z.Create("xl/_rels/workbook.xml.rels")
if err != nil {
return err
}
err = TemplateWorkbookRelationships.Execute(f, ww.sheetNames)
if err != nil {
return err
}
f, err = z.Create("xl/styles.xml")
if err != nil {
return err
}
err = TemplateStyles.Execute(f, nil)
if err != nil {
return err
}
f, err = z.Create("xl/sharedStrings.xml")
if err != nil {
return err
}
err = TemplateStringLookups.Execute(f, ww.SharedStrings)
if err != nil {
return err
}
return err
}
// Handles the writing of an XLSX workbook
type WorkbookWriter struct {
zipWriter *zip.Writer
sheetWriter *SheetWriter
headerWritten bool
closed bool
sheetNames []string
SharedStrings []string
documentInfo *DocumentInfo
}
// Creates a new WorkbookWriter
func NewWorkbookWriter(w io.Writer) *WorkbookWriter {
return &WorkbookWriter{zip.NewWriter(w), nil, false, false, []string{}, nil, nil}
}
// Closes the WorkbookWriter
func (ww *WorkbookWriter) Close() error {
if ww.closed {
panic("WorkbookWriter already closed")
}
ww.closed = true
if ww.sheetWriter != nil {
err := ww.sheetWriter.Close()
ww.sheetWriter = nil
if err != nil {
return err
}
}
if !ww.headerWritten {
err := ww.WriteHeader()
if err != nil {
return err
}
}
return ww.zipWriter.Close()
}
// NewSheetWriter creates a new SheetWriter in this workbook using the given sheet.
// It returns a SheetWriter to which rows can be written.
// All rows must be written to the SheetWriter before the next call to NewSheetWriter,
// as this will automatically close the previous SheetWriter.
func (ww *WorkbookWriter) NewSheetWriter(s *Sheet) (*SheetWriter, error) {
if ww.closed {
panic("Can not write to closed WorkbookWriter")
}
if ww.sheetWriter != nil {
err := ww.sheetWriter.Close()
ww.sheetWriter = nil
if err != nil {
return nil, err
}
}
f, err := ww.zipWriter.Create("xl/worksheets/" + fmt.Sprintf("sheet%s", strconv.Itoa(len(ww.sheetNames)+1)) + ".xml")
if err != nil {
return nil, err
}
sw := &SheetWriter{f, err, 0, 0, false, []string{}, 0}
ww.documentInfo = &s.DocumentInfo
ww.sheetWriter = sw
err = sw.WriteHeader(s)
ww.sheetNames = append(ww.sheetNames, s.Title)
return sw, err
}
// Handles the writing of a sheet
type SheetWriter struct {
f io.Writer
err error
currentIndex uint64
maxNCols uint64
closed bool
mergeCells []string
mergeCellsCount int
}
// Write the given rows to this SheetWriter
func (sw *SheetWriter) WriteRows(rows []Row) error {
if sw.closed {
panic("Can not write to closed SheetWriter")
}
var err error
for i, r := range rows {
_, err = fmt.Fprintf(sw.f, `<row r="%d">`, uint64(i)+sw.currentIndex+1)
if err != nil {
return err
}
if sw.maxNCols < uint64(len(r.Cells)) {
sw.maxNCols = uint64(len(r.Cells))
}
for j, c := range r.Cells {
cellX, cellY := CellIndex(uint64(j), uint64(i)+sw.currentIndex)
switch c.Type {
case CellTypeDate, CellTypeDatetime:
d, err := time.Parse(time.RFC3339, c.Value)
if err == nil {
c.Value = OADate(d)
} else {
return err
}
case CellTypeInlineString:
c.Value = html.EscapeString(c.Value)
}
var cellString string
switch c.Type {
case CellTypeString:
cellString = `<c r="%s%d" t="s" s="1"><v>%s</v></c>`
case CellTypeInlineString:
cellString = `<c r="%s%d" t="inlineStr"><is><t>%s</t></is></c>`
case CellTypeNumber:
cellString = `<c r="%s%d" t="n" s="1"><v>%s</v></c>`
case CellTypeDatetime:
cellString = `<c r="%s%d" s="2"><v>%s</v></c>`
case CellTypeDate:
cellString = `<c r="%s%d" s="3"><v>%s</v></c>`
}
if c.Colspan < 0 || c.Rowspan < 0 {
panic(fmt.Sprintf("%v is not a valid colspan", c.Colspan))
} else if c.Colspan > 1 || c.Rowspan > 1 {
if c.Colspan < 1 {
c.Colspan = 1
}
if c.Rowspan < 1 {
c.Rowspan = 1
}
mergeCellX, mergeCellY := CellIndex(uint64(j)+c.Colspan-1, uint64(i)+sw.currentIndex+c.Rowspan-1)
sw.mergeCells = append(sw.mergeCells, fmt.Sprintf(`<mergeCell ref="%[1]s%[2]d:%[3]s%[4]d"/>`, cellX, cellY, mergeCellX, mergeCellY))
if err != nil {
return err
}
sw.mergeCellsCount += 1
}
_, err = fmt.Fprintf(sw.f, cellString, cellX, cellY, c.Value)
if err != nil {
return err
}
}
_, err = fmt.Fprint(sw.f, `</row>`)
if err != nil {
return err
}
}
sw.currentIndex += uint64(len(rows))
return nil
}
// Closes the SheetWriter
func (sw *SheetWriter) Close() error {
if sw.closed {
panic("SheetWriter already closed")
}
sw.closed = true
cellEndX, cellEndY := CellIndex(sw.maxNCols-1, sw.currentIndex-1)
_, err := fmt.Fprintf(sw.f, `<dimension ref="A1:%s%d"/></sheetData>`, cellEndX, cellEndY)
if err != nil {
return err
}
if sw.mergeCellsCount > 0 {
_, err = fmt.Fprintf(sw.f, `<mergeCells count="%v">`, sw.mergeCellsCount)
if err != nil {
return err
}
for _, mergeCell := range sw.mergeCells {
_, err = fmt.Fprint(sw.f, mergeCell)
if err != nil {
return err
}
}
_, err = fmt.Fprint(sw.f, `</mergeCells>`)
if err != nil {
return err
}
}
_, err = fmt.Fprintf(sw.f, `</worksheet>`)
if err != nil {
return err
}
return nil
}
// Writes the header of a sheet
func (sw *SheetWriter) WriteHeader(s *Sheet) error {
if sw.closed {
panic("Can not write to closed SheetWriter")
}
sheet := struct {
Cols []Column
}{
Cols: s.columns,
}
return TemplateSheetStart.Execute(sw.f, sheet)
}