lib.go 15 KB

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