lib.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math"
  9. "strconv"
  10. "strings"
  11. )
  12. // XLSXReaderError is the standard error type for otherwise undefined
  13. // errors in the XSLX reading process.
  14. type XLSXReaderError struct {
  15. Err string
  16. }
  17. // String() returns a string value from an XLSXReaderError struct in
  18. // order that it might comply with the os.Error interface.
  19. func (e *XLSXReaderError) Error() string {
  20. return e.Err
  21. }
  22. // Cell is a high level structure intended to provide user access to
  23. // the contents of Cell within an xlsx.Row.
  24. type Cell struct {
  25. data string
  26. }
  27. // CellInterface defines the public API of the Cell.
  28. type CellInterface interface {
  29. String() string
  30. }
  31. func (c *Cell) String() string {
  32. return c.data
  33. }
  34. // Row is a high level structure indended to provide user access to a
  35. // row within a xlsx.Sheet. An xlsx.Row contains a slice of xlsx.Cell.
  36. type Row struct {
  37. Cells []*Cell
  38. }
  39. // Sheet is a high level structure intended to provide user access to
  40. // the contents of a particular sheet within an XLSX file.
  41. type Sheet struct {
  42. Rows []*Row
  43. }
  44. // File is a high level structure providing a slice of Sheet structs
  45. // to the user.
  46. type File struct {
  47. worksheets map[string]*zip.File
  48. referenceTable []string
  49. Sheets []*Sheet
  50. }
  51. // getRangeFromString is an internal helper function that converts
  52. // XLSX internal range syntax to a pair of integers. For example,
  53. // the range string "1:3" yield the upper and lower intergers 1 and 3.
  54. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  55. var parts []string
  56. parts = strings.SplitN(rangeString, ":", 2)
  57. if parts[0] == "" {
  58. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  59. }
  60. if parts[1] == "" {
  61. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  62. }
  63. lower, error = strconv.Atoi(parts[0])
  64. if error != nil {
  65. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  66. }
  67. upper, error = strconv.Atoi(parts[1])
  68. if error != nil {
  69. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  70. }
  71. return lower, upper, error
  72. }
  73. // positionalLetterMultiplier gives an integer multiplier to use for a
  74. // position in a letter based column identifer. For example, the
  75. // column ID "AA" is equivalent to 26*1 + 1, "BA" is equivalent to
  76. // 26*2 + 1 and "ABA" is equivalent to (676 * 1)+(26 * 2)+1 or
  77. // ((26**2)*1)+((26**1)*2)+((26**0))*1
  78. func positionalLetterMultiplier(extent, pos int) int {
  79. var result float64
  80. var power float64
  81. var offset int
  82. offset = pos + 1
  83. power = float64(extent - offset)
  84. result = math.Pow(26, power)
  85. return int(result)
  86. }
  87. // lettersToNumeric is used to convert a character based column
  88. // reference to a zero based numeric column identifier.
  89. func lettersToNumeric(letters string) int {
  90. var sum int = 0
  91. var shift int
  92. extent := len(letters)
  93. for i, c := range letters {
  94. // Just to make life akward. If we think of this base
  95. // 26 notation as being like HEX or binary we hit a
  96. // nasty little problem. The issue is that we have no
  97. // 0s and therefore A can be both a 1 and a 0. The
  98. // value range of a letter is different in the most
  99. // significant position if (and only if) there is more
  100. // than one positions. For example:
  101. // "A" = 0
  102. // 676 | 26 | 0
  103. // ----+----+----
  104. // 0 | 0 | 0
  105. //
  106. // "Z" = 25
  107. // 676 | 26 | 0
  108. // ----+----+----
  109. // 0 | 0 | 25
  110. // "AA" = 26
  111. // 676 | 26 | 0
  112. // ----+----+----
  113. // 0 | 1 | 0 <--- note here - the value of "A" maps to both 1 and 0.
  114. if i == 0 && extent > 1 {
  115. shift = 1
  116. } else {
  117. shift = 0
  118. }
  119. multiplier := positionalLetterMultiplier(extent, i)
  120. switch {
  121. case 'A' <= c && c <= 'Z':
  122. sum += multiplier * (int((c - 'A')) + shift)
  123. case 'a' <= c && c <= 'z':
  124. sum += multiplier * (int((c - 'a')) + shift)
  125. }
  126. }
  127. return sum
  128. }
  129. // letterOnlyMapF is used in conjunction with strings.Map to return
  130. // only the characters A-Z and a-z in a string
  131. func letterOnlyMapF(rune rune) rune {
  132. switch {
  133. case 'A' <= rune && rune <= 'Z':
  134. return rune
  135. case 'a' <= rune && rune <= 'z':
  136. return rune - 32
  137. }
  138. return -1
  139. }
  140. // intOnlyMapF is used in conjunction with strings.Map to return only
  141. // the numeric portions of a string.
  142. func intOnlyMapF(rune rune) rune {
  143. if rune >= 48 && rune < 58 {
  144. return rune
  145. }
  146. return -1
  147. }
  148. // getCoordsFromCellIDString returns the zero based cartesian
  149. // coordinates from a cell name in Excel format, e.g. the cellIDString
  150. // "A1" returns 0, 0 and the "B3" return 1, 2.
  151. func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  152. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  153. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  154. if error != nil {
  155. return x, y, error
  156. }
  157. y -= 1 // Zero based
  158. x = lettersToNumeric(letterPart)
  159. return x, y, error
  160. }
  161. // makeRowFromSpan will, when given a span expressed as a string,
  162. // return an empty Row large enough to encompass that span and
  163. // populate it with empty cells. All rows start from cell 1 -
  164. // regardless of the lower bound of the span.
  165. func makeRowFromSpan(spans string) *Row {
  166. var error error
  167. var upper int
  168. var row *Row
  169. var cell *Cell
  170. row = new(Row)
  171. _, upper, error = getRangeFromString(spans)
  172. if error != nil {
  173. panic(error)
  174. }
  175. error = nil
  176. row.Cells = make([]*Cell, upper)
  177. for i := 0; i < upper; i++ {
  178. cell = new(Cell)
  179. cell.data = ""
  180. row.Cells[i] = cell
  181. }
  182. return row
  183. }
  184. // get the max column
  185. // return the cells of columns
  186. func makeRowFromRaw(rawrow xlsxRow) *Row {
  187. var upper int
  188. var row *Row
  189. var cell *Cell
  190. row = new(Row)
  191. upper = 0
  192. for _, rawcell := range rawrow.C {
  193. x, _, error := getCoordsFromCellIDString(rawcell.R)
  194. if error != nil {
  195. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  196. }
  197. if x > upper {
  198. upper = x
  199. }
  200. }
  201. row.Cells = make([]*Cell, upper)
  202. for i := 0; i < upper; i++ {
  203. cell = new(Cell)
  204. cell.data = ""
  205. row.Cells[i] = cell
  206. }
  207. return row
  208. }
  209. // getValueFromCellData attempts to extract a valid value, usable in CSV form from the raw cell value.
  210. // Note - this is not actually general enough - we should support retaining tabs and newlines.
  211. func getValueFromCellData(rawcell xlsxC, reftable []string) string {
  212. var value string = ""
  213. var data string = rawcell.V
  214. if len(data) > 0 {
  215. vval := strings.Trim(data, " \t\n\r")
  216. if rawcell.T == "s" {
  217. ref, error := strconv.Atoi(vval)
  218. if error != nil {
  219. panic(error)
  220. }
  221. value = reftable[ref]
  222. } else {
  223. value = vval
  224. }
  225. }
  226. return value
  227. }
  228. // readRowsFromSheet is an internal helper function that extracts the
  229. // rows from a XSLXWorksheet, poulates them with Cells and resolves
  230. // the value references from the reference table and stores them in
  231. func readRowsFromSheet(Worksheet *xlsxWorksheet, reftable []string) []*Row {
  232. var rows []*Row
  233. var row *Row
  234. rows = make([]*Row, len(Worksheet.SheetData.Row))
  235. for i, rawrow := range Worksheet.SheetData.Row {
  236. // range is not empty
  237. if len(rawrow.Spans) != 0 {
  238. row = makeRowFromSpan(rawrow.Spans)
  239. } else {
  240. row = makeRowFromRaw(rawrow)
  241. }
  242. for _, rawcell := range rawrow.C {
  243. x, _, error := getCoordsFromCellIDString(rawcell.R)
  244. if error != nil {
  245. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  246. }
  247. row.Cells[x].data = getValueFromCellData(rawcell, reftable)
  248. }
  249. rows[i] = row
  250. }
  251. return rows
  252. }
  253. // readSheetsFromZipFile is an internal helper function that loops
  254. // over the Worksheets defined in the XSLXWorkbook and loads them into
  255. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  256. func readSheetsFromZipFile(f *zip.File, file *File) ([]*Sheet, error) {
  257. var workbook *xlsxWorkbook
  258. var error error
  259. var rc io.ReadCloser
  260. var decoder *xml.Decoder
  261. workbook = new(xlsxWorkbook)
  262. rc, error = f.Open()
  263. if error != nil {
  264. return nil, error
  265. }
  266. decoder = xml.NewDecoder(rc)
  267. error = decoder.Decode(workbook)
  268. if error != nil {
  269. return nil, error
  270. }
  271. sheets := make([]*Sheet, len(workbook.Sheets.Sheet))
  272. for i, rawsheet := range workbook.Sheets.Sheet {
  273. worksheet, error := getWorksheetFromSheet(rawsheet, file.worksheets)
  274. if error != nil {
  275. return nil, error
  276. }
  277. sheet := new(Sheet)
  278. sheet.Rows = readRowsFromSheet(worksheet, file.referenceTable)
  279. sheets[i] = sheet
  280. }
  281. return sheets, nil
  282. }
  283. // readSharedStringsFromZipFile() is an internal helper function to
  284. // extract a reference table from the sharedStrings.xml file within
  285. // the XLSX zip file.
  286. func readSharedStringsFromZipFile(f *zip.File) ([]string, error) {
  287. var sst *xlsxSST
  288. var error error
  289. var rc io.ReadCloser
  290. var decoder *xml.Decoder
  291. var reftable []string
  292. rc, error = f.Open()
  293. if error != nil {
  294. return nil, error
  295. }
  296. sst = new(xlsxSST)
  297. decoder = xml.NewDecoder(rc)
  298. error = decoder.Decode(sst)
  299. if error != nil {
  300. return nil, error
  301. }
  302. reftable = MakeSharedStringRefTable(sst)
  303. return reftable, nil
  304. }
  305. // OpenFile() take the name of an XLSX file and returns a populated
  306. // xlsx.File struct for it.
  307. func OpenFile(filename string) (x *File, e error) {
  308. var f *zip.ReadCloser
  309. var error error
  310. var file *File
  311. var v *zip.File
  312. var workbook *zip.File
  313. var sharedStrings *zip.File
  314. var reftable []string
  315. var worksheets map[string]*zip.File
  316. f, error = zip.OpenReader(filename)
  317. if error != nil {
  318. return nil, error
  319. }
  320. file = new(File)
  321. worksheets = make(map[string]*zip.File, len(f.File))
  322. for _, v = range f.File {
  323. switch v.Name {
  324. case "xl/sharedStrings.xml":
  325. sharedStrings = v
  326. case "xl/workbook.xml":
  327. workbook = v
  328. default:
  329. if len(v.Name) > 12 {
  330. if v.Name[0:13] == "xl/worksheets" {
  331. worksheets[v.Name[14:len(v.Name)-4]] = v
  332. }
  333. }
  334. }
  335. }
  336. file.worksheets = worksheets
  337. reftable, error = readSharedStringsFromZipFile(sharedStrings)
  338. if error != nil {
  339. return nil, error
  340. }
  341. if reftable == nil {
  342. error := new(XLSXReaderError)
  343. error.Err = "No valid sharedStrings.xml found in XLSX file"
  344. return nil, error
  345. }
  346. file.referenceTable = reftable
  347. sheets, error := readSheetsFromZipFile(workbook, file)
  348. if error != nil {
  349. return nil, error
  350. }
  351. if sheets == nil {
  352. error := new(XLSXReaderError)
  353. error.Err = "No sheets found in XLSX File"
  354. return nil, error
  355. }
  356. file.Sheets = sheets
  357. f.Close()
  358. return file, nil
  359. }