lib.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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. func (c *Cell) String() string {
  33. return c.Value
  34. }
  35. // TODO: TestMe!
  36. func (c *Cell) GetStyle() *Style {
  37. style := &Style{}
  38. if c.styleIndex > 0 && c.styleIndex <= len(c.styles.CellXfs) {
  39. xf := c.styles.CellXfs[c.styleIndex-1]
  40. if xf.ApplyBorder {
  41. var border Border
  42. border.Left = c.styles.Borders[xf.BorderId].Left.Style
  43. border.Right = c.styles.Borders[xf.BorderId].Right.Style
  44. border.Top = c.styles.Borders[xf.BorderId].Top.Style
  45. border.Bottom = c.styles.Borders[xf.BorderId].Bottom.Style
  46. style.Border = border
  47. }
  48. if xf.ApplyFill {
  49. var fill Fill
  50. fill.PatternType = c.styles.Fills[xf.FillId].PatternFill.PatternType
  51. fill.BgColor = c.styles.Fills[xf.FillId].PatternFill.BgColor.RGB
  52. fill.FgColor = c.styles.Fills[xf.FillId].PatternFill.FgColor.RGB
  53. style.Fill = fill
  54. }
  55. if xf.ApplyFont {
  56. font := c.styles.Fonts[xf.FontId]
  57. style.Font = Font{}
  58. style.Font.Size, _ = strconv.Atoi(font.Sz.Val)
  59. style.Font.Name = font.Name.Val
  60. style.Font.Family, _ = strconv.Atoi(font.Family.Val)
  61. style.Font.Charset, _ = strconv.Atoi(font.Charset.Val)
  62. }
  63. }
  64. return style
  65. }
  66. // Row is a high level structure indended to provide user access to a
  67. // row within a xlsx.Sheet. An xlsx.Row contains a slice of xlsx.Cell.
  68. type Row struct {
  69. Cells []*Cell
  70. }
  71. // Sheet is a high level structure intended to provide user access to
  72. // the contents of a particular sheet within an XLSX file.
  73. type Sheet struct {
  74. Rows []*Row
  75. MaxRow int
  76. MaxCol int
  77. }
  78. // Style is a high level structure intended to provide user access to
  79. // the contents of Style within an XLSX file.
  80. type Style struct {
  81. Border Border
  82. Fill Fill
  83. Font Font
  84. }
  85. // Border is a high level structure intended to provide user access to
  86. // the contents of Border Style within an Sheet.
  87. type Border struct {
  88. Left string
  89. Right string
  90. Top string
  91. Bottom string
  92. }
  93. // Fill is a high level structure intended to provide user access to
  94. // the contents of background and foreground color index within an Sheet.
  95. type Fill struct {
  96. PatternType string
  97. BgColor string
  98. FgColor string
  99. }
  100. type Font struct {
  101. Size int
  102. Name string
  103. Family int
  104. Charset int
  105. }
  106. // File is a high level structure providing a slice of Sheet structs
  107. // to the user.
  108. type File struct {
  109. worksheets map[string]*zip.File
  110. referenceTable []string
  111. styles *xlsxStyles
  112. Sheets []*Sheet // sheet access by index
  113. Sheet map[string]*Sheet // sheet access by name
  114. }
  115. // getRangeFromString is an internal helper function that converts
  116. // XLSX internal range syntax to a pair of integers. For example,
  117. // the range string "1:3" yield the upper and lower intergers 1 and 3.
  118. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  119. var parts []string
  120. parts = strings.SplitN(rangeString, ":", 2)
  121. if parts[0] == "" {
  122. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  123. }
  124. if parts[1] == "" {
  125. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  126. }
  127. lower, error = strconv.Atoi(parts[0])
  128. if error != nil {
  129. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  130. }
  131. upper, error = strconv.Atoi(parts[1])
  132. if error != nil {
  133. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  134. }
  135. return lower, upper, error
  136. }
  137. // lettersToNumeric is used to convert a character based column
  138. // reference to a zero based numeric column identifier.
  139. func lettersToNumeric(letters string) int {
  140. sum, mul, n := 0, 1, 0
  141. for i := len(letters) - 1; i >= 0; i, mul, n = i-1, mul*26, 1 {
  142. c := letters[i]
  143. switch {
  144. case 'A' <= c && c <= 'Z':
  145. n += int(c - 'A')
  146. case 'a' <= c && c <= 'z':
  147. n += int(c - 'a')
  148. }
  149. sum += n * mul
  150. }
  151. return sum
  152. }
  153. // letterOnlyMapF is used in conjunction with strings.Map to return
  154. // only the characters A-Z and a-z in a string
  155. func letterOnlyMapF(rune rune) rune {
  156. switch {
  157. case 'A' <= rune && rune <= 'Z':
  158. return rune
  159. case 'a' <= rune && rune <= 'z':
  160. return rune - 32
  161. }
  162. return -1
  163. }
  164. // intOnlyMapF is used in conjunction with strings.Map to return only
  165. // the numeric portions of a string.
  166. func intOnlyMapF(rune rune) rune {
  167. if rune >= 48 && rune < 58 {
  168. return rune
  169. }
  170. return -1
  171. }
  172. // getCoordsFromCellIDString returns the zero based cartesian
  173. // coordinates from a cell name in Excel format, e.g. the cellIDString
  174. // "A1" returns 0, 0 and the "B3" return 1, 2.
  175. func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  176. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  177. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  178. if error != nil {
  179. return x, y, error
  180. }
  181. y -= 1 // Zero based
  182. x = lettersToNumeric(letterPart)
  183. return x, y, error
  184. }
  185. // getMaxMinFromDimensionRef return the zero based cartesian maximum
  186. // and minimum coordinates from the dimension reference embedded in a
  187. // XLSX worksheet. For example, the dimension reference "A1:B2"
  188. // returns "0,0", "1,1".
  189. func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error) {
  190. var parts []string
  191. parts = strings.Split(ref, ":")
  192. minx, miny, err = getCoordsFromCellIDString(parts[0])
  193. if err != nil {
  194. return -1, -1, -1, -1, err
  195. }
  196. if len(parts) == 1 {
  197. maxx, maxy = minx, miny
  198. return
  199. }
  200. maxx, maxy, err = getCoordsFromCellIDString(parts[1])
  201. if err != nil {
  202. return -1, -1, -1, -1, err
  203. }
  204. return
  205. }
  206. // makeRowFromSpan will, when given a span expressed as a string,
  207. // return an empty Row large enough to encompass that span and
  208. // populate it with empty cells. All rows start from cell 1 -
  209. // regardless of the lower bound of the span.
  210. func makeRowFromSpan(spans string) *Row {
  211. var error error
  212. var upper int
  213. var row *Row
  214. var cell *Cell
  215. row = new(Row)
  216. _, upper, error = getRangeFromString(spans)
  217. if error != nil {
  218. panic(error)
  219. }
  220. error = nil
  221. row.Cells = make([]*Cell, upper)
  222. for i := 0; i < upper; i++ {
  223. cell = new(Cell)
  224. cell.Value = ""
  225. row.Cells[i] = cell
  226. }
  227. return row
  228. }
  229. // get the max column
  230. // return the cells of columns
  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. if len(Worksheet.SheetData.Row) == 0 {
  284. return nil, 0, 0
  285. }
  286. reftable = file.referenceTable
  287. minCol, minRow, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref)
  288. if err != nil {
  289. panic(err.Error())
  290. }
  291. rowCount = (maxRow - minRow) + 1
  292. colCount = (maxCol - minCol) + 1
  293. rows = make([]*Row, rowCount)
  294. for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ {
  295. rawrow := Worksheet.SheetData.Row[rowIndex]
  296. // range is not empty
  297. if len(rawrow.Spans) != 0 {
  298. row = makeRowFromSpan(rawrow.Spans)
  299. } else {
  300. row = makeRowFromRaw(rawrow)
  301. }
  302. for _, rawcell := range rawrow.C {
  303. x, _, _ := getCoordsFromCellIDString(rawcell.R)
  304. if x < len(row.Cells) {
  305. row.Cells[x].Value = getValueFromCellData(rawcell, reftable)
  306. row.Cells[x].styleIndex = rawcell.S
  307. row.Cells[x].styles = file.styles
  308. }
  309. }
  310. rows[rawrow.R-1] = row
  311. }
  312. return rows, colCount, rowCount
  313. }
  314. type indexedSheet struct {
  315. Index int
  316. Sheet *Sheet
  317. Error error
  318. }
  319. // readSheetFromFile is the logic of converting a xlsxSheet struct
  320. // into a Sheet struct. This work can be done in parallel and so
  321. // readSheetsFromZipFile will spawn an instance of this function per
  322. // sheet and get the results back on the provided channel.
  323. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File) {
  324. result := &indexedSheet{Index: index, Sheet: nil, Error: nil}
  325. worksheet, error := getWorksheetFromSheet(rsheet, fi.worksheets)
  326. if error != nil {
  327. result.Error = error
  328. sc <- result
  329. return
  330. }
  331. sheet := new(Sheet)
  332. sheet.Rows, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi)
  333. result.Sheet = sheet
  334. sc <- result
  335. }
  336. // readSheetsFromZipFile is an internal helper function that loops
  337. // over the Worksheets defined in the XSLXWorkbook and loads them into
  338. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  339. func readSheetsFromZipFile(f *zip.File, file *File) ([]*Sheet, []string, error) {
  340. var workbook *xlsxWorkbook
  341. var error error
  342. var rc io.ReadCloser
  343. var decoder *xml.Decoder
  344. var sheetCount int
  345. workbook = new(xlsxWorkbook)
  346. rc, error = f.Open()
  347. if error != nil {
  348. return nil, nil, error
  349. }
  350. decoder = xml.NewDecoder(rc)
  351. error = decoder.Decode(workbook)
  352. if error != nil {
  353. return nil, nil, error
  354. }
  355. sheetCount = len(workbook.Sheets.Sheet)
  356. sheets := make([]*Sheet, sheetCount)
  357. names := make([]string, sheetCount)
  358. sheetChan := make(chan *indexedSheet, sheetCount)
  359. for i, rawsheet := range workbook.Sheets.Sheet {
  360. go readSheetFromFile(sheetChan, i, rawsheet, file)
  361. }
  362. for j := 0; j < sheetCount; j++ {
  363. sheet := <-sheetChan
  364. if sheet.Error != nil {
  365. return nil, nil, sheet.Error
  366. }
  367. sheets[sheet.Index] = sheet.Sheet
  368. names[sheet.Index] = workbook.Sheets.Sheet[sheet.Index].Name
  369. }
  370. return sheets, names, nil
  371. }
  372. // readSharedStringsFromZipFile() is an internal helper function to
  373. // extract a reference table from the sharedStrings.xml file within
  374. // the XLSX zip file.
  375. func readSharedStringsFromZipFile(f *zip.File) ([]string, error) {
  376. var sst *xlsxSST
  377. var error error
  378. var rc io.ReadCloser
  379. var decoder *xml.Decoder
  380. var reftable []string
  381. rc, error = f.Open()
  382. if error != nil {
  383. return nil, error
  384. }
  385. sst = new(xlsxSST)
  386. decoder = xml.NewDecoder(rc)
  387. error = decoder.Decode(sst)
  388. if error != nil {
  389. return nil, error
  390. }
  391. reftable = MakeSharedStringRefTable(sst)
  392. return reftable, nil
  393. }
  394. // readStylesFromZipFile() is an internal helper function to
  395. // extract a style table from the style.xml file within
  396. // the XLSX zip file.
  397. func readStylesFromZipFile(f *zip.File) (*xlsxStyles, error) {
  398. var style *xlsxStyles
  399. var error error
  400. var rc io.ReadCloser
  401. var decoder *xml.Decoder
  402. rc, error = f.Open()
  403. if error != nil {
  404. return nil, error
  405. }
  406. style = new(xlsxStyles)
  407. decoder = xml.NewDecoder(rc)
  408. error = decoder.Decode(style)
  409. if error != nil {
  410. return nil, error
  411. }
  412. return style, nil
  413. }
  414. // OpenFile() take the name of an XLSX file and returns a populated
  415. // xlsx.File struct for it.
  416. func OpenFile(filename string) (*File, error) {
  417. var f *zip.ReadCloser
  418. f, err := zip.OpenReader(filename)
  419. if err != nil {
  420. return nil, err
  421. }
  422. return ReadZip(f)
  423. }
  424. func ReadZip(f *zip.ReadCloser) (*File, error) {
  425. var error error
  426. var file *File
  427. var v *zip.File
  428. var workbook *zip.File
  429. var styles *zip.File
  430. var sharedStrings *zip.File
  431. var reftable []string
  432. var worksheets map[string]*zip.File
  433. var sheetMap map[string]*Sheet
  434. file = new(File)
  435. worksheets = make(map[string]*zip.File, len(f.File))
  436. for _, v = range f.File {
  437. switch v.Name {
  438. case "xl/sharedStrings.xml":
  439. sharedStrings = v
  440. case "xl/workbook.xml":
  441. workbook = v
  442. case "xl/styles.xml":
  443. styles = v
  444. default:
  445. if len(v.Name) > 12 {
  446. if v.Name[0:13] == "xl/worksheets" {
  447. worksheets[v.Name[14:len(v.Name)-4]] = v
  448. }
  449. }
  450. }
  451. }
  452. file.worksheets = worksheets
  453. reftable, error = readSharedStringsFromZipFile(sharedStrings)
  454. if error != nil {
  455. return nil, error
  456. }
  457. if reftable == nil {
  458. error := new(XLSXReaderError)
  459. error.Err = "No valid sharedStrings.xml found in XLSX file"
  460. return nil, error
  461. }
  462. file.referenceTable = reftable
  463. style, error := readStylesFromZipFile(styles)
  464. if error != nil {
  465. return nil, error
  466. }
  467. file.styles = style
  468. sheets, names, error := readSheetsFromZipFile(workbook, file)
  469. if error != nil {
  470. return nil, error
  471. }
  472. if sheets == nil {
  473. error := new(XLSXReaderError)
  474. error.Err = "No sheets found in XLSX File"
  475. return nil, error
  476. }
  477. file.Sheets = sheets
  478. sheetMap = make(map[string]*Sheet, len(names))
  479. for i := 0; i < len(names); i++ {
  480. sheetMap[names[i]] = sheets[i]
  481. }
  482. file.Sheet = sheetMap
  483. f.Close()
  484. return file, nil
  485. }