lib.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  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 := new(Style)
  38. if c.styleIndex > 0 && c.styleIndex < len(c.styles.CellXfs) {
  39. xf := c.styles.CellXfs[c.styleIndex]
  40. if xf.ApplyBorder != "0" {
  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.Boders = border
  47. }
  48. if xf.ApplyFill != "0" {
  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.Fills = fill
  54. }
  55. }
  56. return style
  57. }
  58. // Row is a high level structure indended to provide user access to a
  59. // row within a xlsx.Sheet. An xlsx.Row contains a slice of xlsx.Cell.
  60. type Row struct {
  61. Cells []*Cell
  62. }
  63. // Sheet is a high level structure intended to provide user access to
  64. // the contents of a particular sheet within an XLSX file.
  65. type Sheet struct {
  66. Rows []*Row
  67. MaxRow int
  68. MaxCol int
  69. }
  70. // Style is a high level structure intended to provide user access to
  71. // the contents of Style within an XLSX file.
  72. type Style struct {
  73. Boders Border
  74. Fills Fill
  75. }
  76. // Border is a high level structure intended to provide user access to
  77. // the contents of Border Style within an Sheet.
  78. type Border struct {
  79. Left string
  80. Right string
  81. Top string
  82. Bottom string
  83. }
  84. // Fill is a high level structure intended to provide user access to
  85. // the contents of background and foreground color index within an Sheet.
  86. type Fill struct {
  87. PatternType string
  88. BgColor string
  89. FgColor string
  90. }
  91. // File is a high level structure providing a slice of Sheet structs
  92. // to the user.
  93. type File struct {
  94. worksheets map[string]*zip.File
  95. referenceTable []string
  96. styles *xlsxStyles
  97. Sheets []*Sheet // sheet access by index
  98. Sheet map[string]*Sheet // sheet access by name
  99. }
  100. // getRangeFromString is an internal helper function that converts
  101. // XLSX internal range syntax to a pair of integers. For example,
  102. // the range string "1:3" yield the upper and lower intergers 1 and 3.
  103. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  104. var parts []string
  105. parts = strings.SplitN(rangeString, ":", 2)
  106. if parts[0] == "" {
  107. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  108. }
  109. if parts[1] == "" {
  110. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  111. }
  112. lower, error = strconv.Atoi(parts[0])
  113. if error != nil {
  114. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  115. }
  116. upper, error = strconv.Atoi(parts[1])
  117. if error != nil {
  118. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  119. }
  120. return lower, upper, error
  121. }
  122. // lettersToNumeric is used to convert a character based column
  123. // reference to a zero based numeric column identifier.
  124. func lettersToNumeric(letters string) int {
  125. sum, mul, n := 0, 1, 0
  126. for i := len(letters) - 1; i >= 0; i, mul, n = i-1, mul*26, 1 {
  127. c := letters[i]
  128. switch {
  129. case 'A' <= c && c <= 'Z':
  130. n += int(c - 'A')
  131. case 'a' <= c && c <= 'z':
  132. n += int(c - 'a')
  133. }
  134. sum += n * mul
  135. }
  136. return sum
  137. }
  138. // letterOnlyMapF is used in conjunction with strings.Map to return
  139. // only the characters A-Z and a-z in a string
  140. func letterOnlyMapF(rune rune) rune {
  141. switch {
  142. case 'A' <= rune && rune <= 'Z':
  143. return rune
  144. case 'a' <= rune && rune <= 'z':
  145. return rune - 32
  146. }
  147. return -1
  148. }
  149. // intOnlyMapF is used in conjunction with strings.Map to return only
  150. // the numeric portions of a string.
  151. func intOnlyMapF(rune rune) rune {
  152. if rune >= 48 && rune < 58 {
  153. return rune
  154. }
  155. return -1
  156. }
  157. // getCoordsFromCellIDString returns the zero based cartesian
  158. // coordinates from a cell name in Excel format, e.g. the cellIDString
  159. // "A1" returns 0, 0 and the "B3" return 1, 2.
  160. func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  161. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  162. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  163. if error != nil {
  164. return x, y, error
  165. }
  166. y -= 1 // Zero based
  167. x = lettersToNumeric(letterPart)
  168. return x, y, error
  169. }
  170. // makeRowFromSpan will, when given a span expressed as a string,
  171. // return an empty Row large enough to encompass that span and
  172. // populate it with empty cells. All rows start from cell 1 -
  173. // regardless of the lower bound of the span.
  174. func makeRowFromSpan(spans string) *Row {
  175. var error error
  176. var upper int
  177. var row *Row
  178. var cell *Cell
  179. row = new(Row)
  180. _, upper, error = getRangeFromString(spans)
  181. if error != nil {
  182. panic(error)
  183. }
  184. error = nil
  185. row.Cells = make([]*Cell, upper)
  186. for i := 0; i < upper; i++ {
  187. cell = new(Cell)
  188. cell.Value = ""
  189. row.Cells[i] = cell
  190. }
  191. return row
  192. }
  193. // get the max column
  194. // return the cells of columns
  195. func makeRowFromRaw(rawrow xlsxRow) *Row {
  196. var upper int
  197. var row *Row
  198. var cell *Cell
  199. row = new(Row)
  200. upper = -1
  201. for _, rawcell := range rawrow.C {
  202. x, _, error := getCoordsFromCellIDString(rawcell.R)
  203. if error != nil {
  204. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  205. }
  206. if x > upper {
  207. upper = x
  208. }
  209. }
  210. upper++
  211. row.Cells = make([]*Cell, upper)
  212. for i := 0; i < upper; i++ {
  213. cell = new(Cell)
  214. cell.Value = ""
  215. row.Cells[i] = cell
  216. }
  217. return row
  218. }
  219. // getValueFromCellData attempts to extract a valid value, usable in CSV form from the raw cell value.
  220. // Note - this is not actually general enough - we should support retaining tabs and newlines.
  221. func getValueFromCellData(rawcell xlsxC, reftable []string) string {
  222. var value string = ""
  223. var data string = rawcell.V
  224. if len(data) > 0 {
  225. vval := strings.Trim(data, " \t\n\r")
  226. if rawcell.T == "s" {
  227. ref, error := strconv.Atoi(vval)
  228. if error != nil {
  229. panic(error)
  230. }
  231. value = reftable[ref]
  232. } else {
  233. value = vval
  234. }
  235. }
  236. return value
  237. }
  238. // readRowsFromSheet is an internal helper function that extracts the
  239. // rows from a XSLXWorksheet, poulates them with Cells and resolves
  240. // the value references from the reference table and stores them in
  241. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File) ([]*Row, int, int) {
  242. var rows []*Row
  243. var row *Row
  244. var maxCol int
  245. var maxRow int
  246. var reftable []string
  247. reftable = file.referenceTable
  248. maxCol = 0
  249. maxRow = 0
  250. for _, rawrow := range Worksheet.SheetData.Row {
  251. for _, rawcell := range rawrow.C {
  252. x, y, error := getCoordsFromCellIDString(rawcell.R)
  253. if error != nil {
  254. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  255. }
  256. if x > maxCol {
  257. maxCol = x
  258. }
  259. if y > maxRow {
  260. maxRow = y
  261. }
  262. }
  263. }
  264. maxCol += 1
  265. maxRow += 1
  266. rows = make([]*Row, maxRow)
  267. for _, rawrow := range Worksheet.SheetData.Row {
  268. // range is not empty
  269. if len(rawrow.Spans) != 0 {
  270. row = makeRowFromSpan(rawrow.Spans)
  271. } else {
  272. row = makeRowFromRaw(rawrow)
  273. }
  274. rowno := 0
  275. for _, rawcell := range rawrow.C {
  276. x, y, _ := getCoordsFromCellIDString(rawcell.R)
  277. if y != 0 && rowno == 0 {
  278. rowno = y
  279. }
  280. if x < len(row.Cells) {
  281. row.Cells[x].Value = getValueFromCellData(rawcell, reftable)
  282. row.Cells[x].styleIndex = rawcell.S
  283. row.Cells[x].styles = file.styles
  284. }
  285. }
  286. rows[rowno] = row
  287. }
  288. return rows, maxCol, maxRow
  289. }
  290. // readSheetsFromZipFile is an internal helper function that loops
  291. // over the Worksheets defined in the XSLXWorkbook and loads them into
  292. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  293. func readSheetsFromZipFile(f *zip.File, file *File) ([]*Sheet, []string, error) {
  294. var workbook *xlsxWorkbook
  295. var error error
  296. var rc io.ReadCloser
  297. var decoder *xml.Decoder
  298. workbook = new(xlsxWorkbook)
  299. rc, error = f.Open()
  300. if error != nil {
  301. return nil, nil, error
  302. }
  303. decoder = xml.NewDecoder(rc)
  304. error = decoder.Decode(workbook)
  305. if error != nil {
  306. return nil, nil, error
  307. }
  308. sheets := make([]*Sheet, len(workbook.Sheets.Sheet))
  309. names := make([]string, len(workbook.Sheets.Sheet))
  310. for i, rawsheet := range workbook.Sheets.Sheet {
  311. worksheet, error := getWorksheetFromSheet(rawsheet, file.worksheets)
  312. if error != nil {
  313. return nil, nil, error
  314. }
  315. sheet := new(Sheet)
  316. sheet.Rows, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, file)
  317. sheets[i] = sheet
  318. names[i] = rawsheet.Name
  319. }
  320. return sheets, names, nil
  321. }
  322. // readSharedStringsFromZipFile() is an internal helper function to
  323. // extract a reference table from the sharedStrings.xml file within
  324. // the XLSX zip file.
  325. func readSharedStringsFromZipFile(f *zip.File) ([]string, error) {
  326. var sst *xlsxSST
  327. var error error
  328. var rc io.ReadCloser
  329. var decoder *xml.Decoder
  330. var reftable []string
  331. rc, error = f.Open()
  332. if error != nil {
  333. return nil, error
  334. }
  335. sst = new(xlsxSST)
  336. decoder = xml.NewDecoder(rc)
  337. error = decoder.Decode(sst)
  338. if error != nil {
  339. return nil, error
  340. }
  341. reftable = MakeSharedStringRefTable(sst)
  342. return reftable, nil
  343. }
  344. // readStylesFromZipFile() is an internal helper function to
  345. // extract a style table from the style.xml file within
  346. // the XLSX zip file.
  347. func readStylesFromZipFile(f *zip.File) (*xlsxStyles, error) {
  348. var style *xlsxStyles
  349. var error error
  350. var rc io.ReadCloser
  351. var decoder *xml.Decoder
  352. rc, error = f.Open()
  353. if error != nil {
  354. return nil, error
  355. }
  356. style = new(xlsxStyles)
  357. decoder = xml.NewDecoder(rc)
  358. error = decoder.Decode(style)
  359. if error != nil {
  360. return nil, error
  361. }
  362. return style, nil
  363. }
  364. // OpenFile() take the name of an XLSX file and returns a populated
  365. // xlsx.File struct for it.
  366. func OpenFile(filename string) (*File, error) {
  367. var f *zip.ReadCloser
  368. f, err := zip.OpenReader(filename)
  369. if err != nil {
  370. return nil, err
  371. }
  372. return ReadZip(f)
  373. }
  374. func ReadZip(f *zip.ReadCloser) (*File, error) {
  375. var error error
  376. var file *File
  377. var v *zip.File
  378. var workbook *zip.File
  379. var styles *zip.File
  380. var sharedStrings *zip.File
  381. var reftable []string
  382. var worksheets map[string]*zip.File
  383. var sheetMap map[string]*Sheet
  384. file = new(File)
  385. worksheets = make(map[string]*zip.File, len(f.File))
  386. for _, v = range f.File {
  387. switch v.Name {
  388. case "xl/sharedStrings.xml":
  389. sharedStrings = v
  390. case "xl/workbook.xml":
  391. workbook = v
  392. case "xl/styles.xml":
  393. styles = v
  394. default:
  395. if len(v.Name) > 12 {
  396. if v.Name[0:13] == "xl/worksheets" {
  397. worksheets[v.Name[14:len(v.Name)-4]] = v
  398. }
  399. }
  400. }
  401. }
  402. file.worksheets = worksheets
  403. reftable, error = readSharedStringsFromZipFile(sharedStrings)
  404. if error != nil {
  405. return nil, error
  406. }
  407. if reftable == nil {
  408. error := new(XLSXReaderError)
  409. error.Err = "No valid sharedStrings.xml found in XLSX file"
  410. return nil, error
  411. }
  412. file.referenceTable = reftable
  413. style, error := readStylesFromZipFile(styles)
  414. if error != nil {
  415. return nil, error
  416. }
  417. file.styles = style
  418. sheets, names, error := readSheetsFromZipFile(workbook, file)
  419. if error != nil {
  420. return nil, error
  421. }
  422. if sheets == nil {
  423. error := new(XLSXReaderError)
  424. error.Err = "No sheets found in XLSX File"
  425. return nil, error
  426. }
  427. file.Sheets = sheets
  428. sheetMap = make(map[string]*Sheet, len(names))
  429. for i := 0; i < len(names); i++ {
  430. sheetMap[names[i]] = sheets[i]
  431. }
  432. file.Sheet = sheetMap
  433. f.Close()
  434. return file, nil
  435. }