lib.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "strconv"
  9. "strings"
  10. )
  11. // XLSXReaderError is the standard error type for otherwise undefined
  12. // errors in the XSLX reading process.
  13. type XLSXReaderError struct {
  14. Err string
  15. }
  16. // String() returns a string value from an XLSXReaderError struct in
  17. // order that it might comply with the os.Error interface.
  18. func (e *XLSXReaderError) Error() string {
  19. return e.Err
  20. }
  21. // Cell is a high level structure intended to provide user access to
  22. // the contents of Cell within an xlsx.Row.
  23. type Cell struct {
  24. Value string
  25. styleIndex int
  26. styles *xlsxStyles
  27. }
  28. // CellInterface defines the public API of the Cell.
  29. type CellInterface interface {
  30. String() string
  31. }
  32. // String returns the value of a Cell as a string.
  33. func (c *Cell) String() string {
  34. return c.Value
  35. }
  36. // GetStyle returns the Style associated with a Cell
  37. func (c *Cell) GetStyle() *Style {
  38. style := &Style{}
  39. if c.styleIndex > 0 && c.styleIndex <= len(c.styles.CellXfs) {
  40. xf := c.styles.CellXfs[c.styleIndex-1]
  41. if xf.ApplyBorder {
  42. var border Border
  43. border.Left = c.styles.Borders[xf.BorderId].Left.Style
  44. border.Right = c.styles.Borders[xf.BorderId].Right.Style
  45. border.Top = c.styles.Borders[xf.BorderId].Top.Style
  46. border.Bottom = c.styles.Borders[xf.BorderId].Bottom.Style
  47. style.Border = border
  48. }
  49. if xf.ApplyFill {
  50. var fill Fill
  51. fill.PatternType = c.styles.Fills[xf.FillId].PatternFill.PatternType
  52. fill.BgColor = c.styles.Fills[xf.FillId].PatternFill.BgColor.RGB
  53. fill.FgColor = c.styles.Fills[xf.FillId].PatternFill.FgColor.RGB
  54. style.Fill = fill
  55. }
  56. if xf.ApplyFont {
  57. font := c.styles.Fonts[xf.FontId]
  58. style.Font = Font{}
  59. style.Font.Size, _ = strconv.Atoi(font.Sz.Val)
  60. style.Font.Name = font.Name.Val
  61. style.Font.Family, _ = strconv.Atoi(font.Family.Val)
  62. style.Font.Charset, _ = strconv.Atoi(font.Charset.Val)
  63. }
  64. }
  65. return style
  66. }
  67. // Row is a high level structure indended to provide user access to a
  68. // row within a xlsx.Sheet. An xlsx.Row contains a slice of xlsx.Cell.
  69. type Row struct {
  70. Cells []*Cell
  71. }
  72. // Sheet is a high level structure intended to provide user access to
  73. // the contents of a particular sheet within an XLSX file.
  74. type Sheet struct {
  75. Rows []*Row
  76. MaxRow int
  77. MaxCol int
  78. }
  79. // Style is a high level structure intended to provide user access to
  80. // the contents of Style within an XLSX file.
  81. type Style struct {
  82. Border Border
  83. Fill Fill
  84. Font Font
  85. }
  86. // Border is a high level structure intended to provide user access to
  87. // the contents of Border Style within an Sheet.
  88. type Border struct {
  89. Left string
  90. Right string
  91. Top string
  92. Bottom string
  93. }
  94. // Fill is a high level structure intended to provide user access to
  95. // the contents of background and foreground color index within an Sheet.
  96. type Fill struct {
  97. PatternType string
  98. BgColor string
  99. FgColor string
  100. }
  101. type Font struct {
  102. Size int
  103. Name string
  104. Family int
  105. Charset int
  106. }
  107. // File is a high level structure providing a slice of Sheet structs
  108. // to the user.
  109. type File struct {
  110. worksheets map[string]*zip.File
  111. referenceTable []string
  112. styles *xlsxStyles
  113. Sheets []*Sheet // sheet access by index
  114. Sheet map[string]*Sheet // sheet access by name
  115. }
  116. // getRangeFromString is an internal helper function that converts
  117. // XLSX internal range syntax to a pair of integers. For example,
  118. // the range string "1:3" yield the upper and lower intergers 1 and 3.
  119. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  120. var parts []string
  121. parts = strings.SplitN(rangeString, ":", 2)
  122. if parts[0] == "" {
  123. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  124. }
  125. if parts[1] == "" {
  126. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  127. }
  128. lower, error = strconv.Atoi(parts[0])
  129. if error != nil {
  130. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  131. }
  132. upper, error = strconv.Atoi(parts[1])
  133. if error != nil {
  134. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  135. }
  136. return lower, upper, error
  137. }
  138. // lettersToNumeric is used to convert a character based column
  139. // reference to a zero based numeric column identifier.
  140. func lettersToNumeric(letters string) int {
  141. sum, mul, n := 0, 1, 0
  142. for i := len(letters) - 1; i >= 0; i, mul, n = i-1, mul*26, 1 {
  143. c := letters[i]
  144. switch {
  145. case 'A' <= c && c <= 'Z':
  146. n += int(c - 'A')
  147. case 'a' <= c && c <= 'z':
  148. n += int(c - 'a')
  149. }
  150. sum += n * mul
  151. }
  152. return sum
  153. }
  154. // letterOnlyMapF is used in conjunction with strings.Map to return
  155. // only the characters A-Z and a-z in a string
  156. func letterOnlyMapF(rune rune) rune {
  157. switch {
  158. case 'A' <= rune && rune <= 'Z':
  159. return rune
  160. case 'a' <= rune && rune <= 'z':
  161. return rune - 32
  162. }
  163. return -1
  164. }
  165. // intOnlyMapF is used in conjunction with strings.Map to return only
  166. // the numeric portions of a string.
  167. func intOnlyMapF(rune rune) rune {
  168. if rune >= 48 && rune < 58 {
  169. return rune
  170. }
  171. return -1
  172. }
  173. // getCoordsFromCellIDString returns the zero based cartesian
  174. // coordinates from a cell name in Excel format, e.g. the cellIDString
  175. // "A1" returns 0, 0 and the "B3" return 1, 2.
  176. func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  177. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  178. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  179. if error != nil {
  180. return x, y, error
  181. }
  182. y -= 1 // Zero based
  183. x = lettersToNumeric(letterPart)
  184. return x, y, error
  185. }
  186. // getMaxMinFromDimensionRef return the zero based cartesian maximum
  187. // and minimum coordinates from the dimension reference embedded in a
  188. // XLSX worksheet. For example, the dimension reference "A1:B2"
  189. // returns "0,0", "1,1".
  190. func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error) {
  191. var parts []string
  192. parts = strings.Split(ref, ":")
  193. minx, miny, err = getCoordsFromCellIDString(parts[0])
  194. if err != nil {
  195. return -1, -1, -1, -1, err
  196. }
  197. if len(parts) == 1 {
  198. maxx, maxy = minx, miny
  199. return
  200. }
  201. maxx, maxy, err = getCoordsFromCellIDString(parts[1])
  202. if err != nil {
  203. return -1, -1, -1, -1, err
  204. }
  205. return
  206. }
  207. // makeRowFromSpan will, when given a span expressed as a string,
  208. // return an empty Row large enough to encompass that span and
  209. // populate it with empty cells. All rows start from cell 1 -
  210. // regardless of the lower bound of the span.
  211. func makeRowFromSpan(spans string) *Row {
  212. var error error
  213. var upper int
  214. var row *Row
  215. var cell *Cell
  216. row = new(Row)
  217. _, upper, error = getRangeFromString(spans)
  218. if error != nil {
  219. panic(error)
  220. }
  221. error = nil
  222. row.Cells = make([]*Cell, upper)
  223. for i := 0; i < upper; i++ {
  224. cell = new(Cell)
  225. cell.Value = ""
  226. row.Cells[i] = cell
  227. }
  228. return row
  229. }
  230. // makeRowFromRaw returns the Row representation of the xlsxRow.
  231. func makeRowFromRaw(rawrow xlsxRow) *Row {
  232. var upper int
  233. var row *Row
  234. var cell *Cell
  235. row = new(Row)
  236. upper = -1
  237. for _, rawcell := range rawrow.C {
  238. x, _, error := getCoordsFromCellIDString(rawcell.R)
  239. if error != nil {
  240. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  241. }
  242. if x > upper {
  243. upper = x
  244. }
  245. }
  246. upper++
  247. row.Cells = make([]*Cell, upper)
  248. for i := 0; i < upper; i++ {
  249. cell = new(Cell)
  250. cell.Value = ""
  251. row.Cells[i] = cell
  252. }
  253. return row
  254. }
  255. // getValueFromCellData attempts to extract a valid value, usable in CSV form from the raw cell value.
  256. // Note - this is not actually general enough - we should support retaining tabs and newlines.
  257. func getValueFromCellData(rawcell xlsxC, reftable []string) string {
  258. var value string = ""
  259. var data string = rawcell.V
  260. if len(data) > 0 {
  261. vval := strings.Trim(data, " \t\n\r")
  262. if rawcell.T == "s" {
  263. ref, error := strconv.Atoi(vval)
  264. if error != nil {
  265. panic(error)
  266. }
  267. value = reftable[ref]
  268. } else {
  269. value = vval
  270. }
  271. }
  272. return value
  273. }
  274. // readRowsFromSheet is an internal helper function that extracts the
  275. // rows from a XSLXWorksheet, poulates them with Cells and resolves
  276. // the value references from the reference table and stores them in
  277. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File) ([]*Row, int, int) {
  278. var rows []*Row
  279. var row *Row
  280. var minCol, maxCol, minRow, maxRow, colCount, rowCount int
  281. var reftable []string
  282. var err error
  283. var insertRowIndex, insertColIndex int
  284. if len(Worksheet.SheetData.Row) == 0 {
  285. return nil, 0, 0
  286. }
  287. reftable = file.referenceTable
  288. minCol, minRow, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref)
  289. if err != nil {
  290. panic(err.Error())
  291. }
  292. rowCount = (maxRow - minRow) + 1
  293. colCount = (maxCol - minCol) + 1
  294. rows = make([]*Row, rowCount)
  295. insertRowIndex = minRow
  296. for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ {
  297. rawrow := Worksheet.SheetData.Row[rowIndex]
  298. // Some spreadsheets will omit blank rows from the
  299. // stored data
  300. for rawrow.R > (insertRowIndex + 1) {
  301. // Put an empty Row into the array
  302. rows[insertRowIndex-minRow] = new(Row)
  303. insertRowIndex++
  304. }
  305. // range is not empty
  306. if len(rawrow.Spans) != 0 {
  307. row = makeRowFromSpan(rawrow.Spans)
  308. } else {
  309. row = makeRowFromRaw(rawrow)
  310. }
  311. insertColIndex = minCol
  312. for _, rawcell := range rawrow.C {
  313. x, _, _ := getCoordsFromCellIDString(rawcell.R)
  314. // Some spreadsheets will omit blank cells
  315. // from the data.
  316. for x > insertColIndex {
  317. // Put an empty Cell into the array
  318. row.Cells[insertColIndex-minCol] = new(Cell)
  319. insertColIndex++
  320. }
  321. cellX := insertColIndex - minCol
  322. row.Cells[cellX].Value = getValueFromCellData(rawcell, reftable)
  323. row.Cells[cellX].styleIndex = rawcell.S
  324. row.Cells[cellX].styles = file.styles
  325. insertColIndex++
  326. }
  327. rows[insertRowIndex-minRow] = row
  328. insertRowIndex++
  329. }
  330. return rows, colCount, rowCount
  331. }
  332. type indexedSheet struct {
  333. Index int
  334. Sheet *Sheet
  335. Error error
  336. }
  337. // readSheetFromFile is the logic of converting a xlsxSheet struct
  338. // into a Sheet struct. This work can be done in parallel and so
  339. // readSheetsFromZipFile will spawn an instance of this function per
  340. // sheet and get the results back on the provided channel.
  341. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string) {
  342. result := &indexedSheet{Index: index, Sheet: nil, Error: nil}
  343. worksheet, error := getWorksheetFromSheet(rsheet, fi.worksheets, sheetXMLMap)
  344. if error != nil {
  345. result.Error = error
  346. sc <- result
  347. return
  348. }
  349. sheet := new(Sheet)
  350. sheet.Rows, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi)
  351. result.Sheet = sheet
  352. sc <- result
  353. }
  354. // readSheetsFromZipFile is an internal helper function that loops
  355. // over the Worksheets defined in the XSLXWorkbook and loads them into
  356. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  357. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string) ([]*Sheet, []string, error) {
  358. var workbook *xlsxWorkbook
  359. var error error
  360. var rc io.ReadCloser
  361. var decoder *xml.Decoder
  362. var sheetCount int
  363. workbook = new(xlsxWorkbook)
  364. rc, error = f.Open()
  365. if error != nil {
  366. return nil, nil, error
  367. }
  368. decoder = xml.NewDecoder(rc)
  369. error = decoder.Decode(workbook)
  370. if error != nil {
  371. return nil, nil, error
  372. }
  373. sheetCount = len(workbook.Sheets.Sheet)
  374. sheets := make([]*Sheet, sheetCount)
  375. names := make([]string, sheetCount)
  376. sheetChan := make(chan *indexedSheet, sheetCount)
  377. for i, rawsheet := range workbook.Sheets.Sheet {
  378. go readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap)
  379. }
  380. for j := 0; j < sheetCount; j++ {
  381. sheet := <-sheetChan
  382. if sheet.Error != nil {
  383. return nil, nil, sheet.Error
  384. }
  385. sheets[sheet.Index] = sheet.Sheet
  386. names[sheet.Index] = workbook.Sheets.Sheet[sheet.Index].Name
  387. }
  388. return sheets, names, nil
  389. }
  390. // readSharedStringsFromZipFile() is an internal helper function to
  391. // extract a reference table from the sharedStrings.xml file within
  392. // the XLSX zip file.
  393. func readSharedStringsFromZipFile(f *zip.File) ([]string, error) {
  394. var sst *xlsxSST
  395. var error error
  396. var rc io.ReadCloser
  397. var decoder *xml.Decoder
  398. var reftable []string
  399. rc, error = f.Open()
  400. if error != nil {
  401. return nil, error
  402. }
  403. sst = new(xlsxSST)
  404. decoder = xml.NewDecoder(rc)
  405. error = decoder.Decode(sst)
  406. if error != nil {
  407. return nil, error
  408. }
  409. reftable = MakeSharedStringRefTable(sst)
  410. return reftable, nil
  411. }
  412. // readStylesFromZipFile() is an internal helper function to
  413. // extract a style table from the style.xml file within
  414. // the XLSX zip file.
  415. func readStylesFromZipFile(f *zip.File) (*xlsxStyles, error) {
  416. var style *xlsxStyles
  417. var error error
  418. var rc io.ReadCloser
  419. var decoder *xml.Decoder
  420. rc, error = f.Open()
  421. if error != nil {
  422. return nil, error
  423. }
  424. style = new(xlsxStyles)
  425. decoder = xml.NewDecoder(rc)
  426. error = decoder.Decode(style)
  427. if error != nil {
  428. return nil, error
  429. }
  430. return style, nil
  431. }
  432. // readWorkbookRelationsFromZipFile is an internal helper function to
  433. // extract a map of relationship ID strings to the name of the
  434. // worksheet.xml file they refer to. The resulting map can be used to
  435. // reliably derefence the worksheets in the XLSX file.
  436. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (map[string]string, error) {
  437. var sheetXMLMap map[string]string
  438. var wbRelationships *xlsxWorkbookRels
  439. var rc io.ReadCloser
  440. var decoder *xml.Decoder
  441. var err error
  442. rc, err = workbookRels.Open()
  443. if err != nil {
  444. return nil, err
  445. }
  446. decoder = xml.NewDecoder(rc)
  447. wbRelationships = new(xlsxWorkbookRels)
  448. err = decoder.Decode(wbRelationships)
  449. if err != nil {
  450. return nil, err
  451. }
  452. sheetXMLMap = make(map[string]string)
  453. for _, rel := range wbRelationships.Relationships {
  454. if strings.HasSuffix(rel.Target, ".xml") && strings.HasPrefix(rel.Target, "worksheets/") {
  455. sheetXMLMap[rel.Id] = strings.Replace(rel.Target[len("worksheets/"):], ".xml", "", 1)
  456. }
  457. }
  458. return sheetXMLMap, nil
  459. }
  460. // OpenFile() take the name of an XLSX file and returns a populated
  461. // xlsx.File struct for it.
  462. func OpenFile(filename string) (*File, error) {
  463. var f *zip.ReadCloser
  464. f, err := zip.OpenReader(filename)
  465. if err != nil {
  466. return nil, err
  467. }
  468. return ReadZip(f)
  469. }
  470. // ReadZip() takes a pointer to a zip.ReadCloser and returns a
  471. // xlsx.File struct populated with its contents. In most cases
  472. // ReadZip is not used directly, but is called internally by OpenFile.
  473. func ReadZip(f *zip.ReadCloser) (*File, error) {
  474. defer f.Close()
  475. return ReadZipReader(&f.Reader)
  476. }
  477. // ReadZipReader() can be used to read xlsx in memory without touch filesystem.
  478. func ReadZipReader(r *zip.Reader) (*File, error) {
  479. var err error
  480. var file *File
  481. var names []string
  482. var reftable []string
  483. var sharedStrings *zip.File
  484. var sheetMap map[string]*Sheet
  485. var sheetXMLMap map[string]string
  486. var sheets []*Sheet
  487. var style *xlsxStyles
  488. var styles *zip.File
  489. var v *zip.File
  490. var workbook *zip.File
  491. var workbookRels *zip.File
  492. var worksheets map[string]*zip.File
  493. file = new(File)
  494. worksheets = make(map[string]*zip.File, len(r.File))
  495. for _, v = range r.File {
  496. switch v.Name {
  497. case "xl/sharedStrings.xml":
  498. sharedStrings = v
  499. case "xl/workbook.xml":
  500. workbook = v
  501. case "xl/_rels/workbook.xml.rels":
  502. workbookRels = v
  503. case "xl/styles.xml":
  504. styles = v
  505. default:
  506. if len(v.Name) > 14 {
  507. if v.Name[0:13] == "xl/worksheets" {
  508. worksheets[v.Name[14:len(v.Name)-4]] = v
  509. }
  510. }
  511. }
  512. }
  513. sheetXMLMap, err = readWorkbookRelationsFromZipFile(workbookRels)
  514. if err != nil {
  515. return nil, err
  516. }
  517. file.worksheets = worksheets
  518. reftable, err = readSharedStringsFromZipFile(sharedStrings)
  519. if err != nil {
  520. return nil, err
  521. }
  522. if reftable == nil {
  523. readerErr := new(XLSXReaderError)
  524. readerErr.Err = "No valid sharedStrings.xml found in XLSX file"
  525. return nil, readerErr
  526. }
  527. file.referenceTable = reftable
  528. style, err = readStylesFromZipFile(styles)
  529. if err != nil {
  530. return nil, err
  531. }
  532. file.styles = style
  533. sheets, names, err = readSheetsFromZipFile(workbook, file, sheetXMLMap)
  534. if err != nil {
  535. return nil, err
  536. }
  537. if sheets == nil {
  538. readerErr := new(XLSXReaderError)
  539. readerErr.Err = "No sheets found in XLSX File"
  540. return nil, readerErr
  541. }
  542. file.Sheets = sheets
  543. sheetMap = make(map[string]*Sheet, len(names))
  544. for i := 0; i < len(names); i++ {
  545. sheetMap[names[i]] = sheets[i]
  546. }
  547. file.Sheet = sheetMap
  548. return file, nil
  549. }