lib.go 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "bytes"
  5. "encoding/xml"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "path"
  10. "strconv"
  11. "strings"
  12. )
  13. const (
  14. sheetEnding = `</sheetData></worksheet>`
  15. )
  16. // XLSXReaderError is the standard error type for otherwise undefined
  17. // errors in the XSLX reading process.
  18. type XLSXReaderError struct {
  19. Err string
  20. }
  21. // Error returns a string value from an XLSXReaderError struct in order
  22. // that it might comply with the builtin.error interface.
  23. func (e *XLSXReaderError) Error() string {
  24. return e.Err
  25. }
  26. // getRangeFromString is an internal helper function that converts
  27. // XLSX internal range syntax to a pair of integers. For example,
  28. // the range string "1:3" yield the upper and lower integers 1 and 3.
  29. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  30. var parts []string
  31. parts = strings.SplitN(rangeString, ":", 2)
  32. if parts[0] == "" {
  33. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  34. }
  35. if parts[1] == "" {
  36. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  37. }
  38. lower, error = strconv.Atoi(parts[0])
  39. if error != nil {
  40. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  41. }
  42. upper, error = strconv.Atoi(parts[1])
  43. if error != nil {
  44. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  45. }
  46. return lower, upper, error
  47. }
  48. // ColLettersToIndex is used to convert a character based column
  49. // reference to a zero based numeric column identifier.
  50. func ColLettersToIndex(letters string) int {
  51. sum, mul, n := 0, 1, 0
  52. for i := len(letters) - 1; i >= 0; i, mul, n = i-1, mul*26, 1 {
  53. c := letters[i]
  54. switch {
  55. case 'A' <= c && c <= 'Z':
  56. n += int(c - 'A')
  57. case 'a' <= c && c <= 'z':
  58. n += int(c - 'a')
  59. }
  60. sum += n * mul
  61. }
  62. return sum
  63. }
  64. // Get the largestDenominator that is a multiple of a basedDenominator
  65. // and fits at least once into a given numerator.
  66. func getLargestDenominator(numerator, multiple, baseDenominator, power int) (int, int) {
  67. if numerator/multiple == 0 {
  68. return 1, power
  69. }
  70. next, nextPower := getLargestDenominator(
  71. numerator, multiple*baseDenominator, baseDenominator, power+1)
  72. if next > multiple {
  73. return next, nextPower
  74. }
  75. return multiple, power
  76. }
  77. // Convers a list of numbers representing a column into a alphabetic
  78. // representation, as used in the spreadsheet.
  79. func formatColumnName(colId []int) string {
  80. lastPart := len(colId) - 1
  81. result := ""
  82. for n, part := range colId {
  83. if n == lastPart {
  84. // The least significant number is in the
  85. // range 0-25, all other numbers are 1-26,
  86. // hence we use a differente offset for the
  87. // last part.
  88. result += string(part + 65)
  89. } else {
  90. // Don't output leading 0s, as there is no
  91. // representation of 0 in this format.
  92. if part > 0 {
  93. result += string(part + 64)
  94. }
  95. }
  96. }
  97. return result
  98. }
  99. func smooshBase26Slice(b26 []int) []int {
  100. // Smoosh values together, eliminating 0s from all but the
  101. // least significant part.
  102. lastButOnePart := len(b26) - 2
  103. for i := lastButOnePart; i > 0; i-- {
  104. part := b26[i]
  105. if part == 0 {
  106. greaterPart := b26[i-1]
  107. if greaterPart > 0 {
  108. b26[i-1] = greaterPart - 1
  109. b26[i] = 26
  110. }
  111. }
  112. }
  113. return b26
  114. }
  115. func intToBase26(x int) (parts []int) {
  116. // Excel column codes are pure evil - in essence they're just
  117. // base26, but they don't represent the number 0.
  118. b26Denominator, _ := getLargestDenominator(x, 1, 26, 0)
  119. // This loop terminates because integer division of 1 / 26
  120. // returns 0.
  121. for d := b26Denominator; d > 0; d = d / 26 {
  122. value := x / d
  123. remainder := x % d
  124. parts = append(parts, value)
  125. x = remainder
  126. }
  127. return parts
  128. }
  129. // ColIndexToLetters is used to convert a zero based, numeric column
  130. // indentifier into a character code.
  131. func ColIndexToLetters(colRef int) string {
  132. parts := intToBase26(colRef)
  133. return formatColumnName(smooshBase26Slice(parts))
  134. }
  135. // letterOnlyMapF is used in conjunction with strings.Map to return
  136. // only the characters A-Z and a-z in a string
  137. func letterOnlyMapF(rune rune) rune {
  138. switch {
  139. case 'A' <= rune && rune <= 'Z':
  140. return rune
  141. case 'a' <= rune && rune <= 'z':
  142. return rune - 32
  143. }
  144. return -1
  145. }
  146. // intOnlyMapF is used in conjunction with strings.Map to return only
  147. // the numeric portions of a string.
  148. func intOnlyMapF(rune rune) rune {
  149. if rune >= 48 && rune < 58 {
  150. return rune
  151. }
  152. return -1
  153. }
  154. // GetCoordsFromCellIDString returns the zero based cartesian
  155. // coordinates from a cell name in Excel format, e.g. the cellIDString
  156. // "A1" returns 0, 0 and the "B3" return 1, 2.
  157. func GetCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  158. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  159. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  160. if error != nil {
  161. return x, y, error
  162. }
  163. y -= 1 // Zero based
  164. x = ColLettersToIndex(letterPart)
  165. return x, y, error
  166. }
  167. // GetCellIDStringFromCoords returns the Excel format cell name that
  168. // represents a pair of zero based cartesian coordinates.
  169. func GetCellIDStringFromCoords(x, y int) string {
  170. letterPart := ColIndexToLetters(x)
  171. numericPart := y + 1
  172. return fmt.Sprintf("%s%d", letterPart, numericPart)
  173. }
  174. // getMaxMinFromDimensionRef return the zero based cartesian maximum
  175. // and minimum coordinates from the dimension reference embedded in a
  176. // XLSX worksheet. For example, the dimension reference "A1:B2"
  177. // returns "0,0", "1,1".
  178. func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error) {
  179. var parts []string
  180. parts = strings.Split(ref, ":")
  181. minx, miny, err = GetCoordsFromCellIDString(parts[0])
  182. if err != nil {
  183. return -1, -1, -1, -1, err
  184. }
  185. maxx, maxy, err = GetCoordsFromCellIDString(parts[1])
  186. if err != nil {
  187. return -1, -1, -1, -1, err
  188. }
  189. return
  190. }
  191. // calculateMaxMinFromWorkSheet works out the dimensions of a spreadsheet
  192. // that doesn't have a DimensionRef set. The only case currently
  193. // known where this is true is with XLSX exported from Google Docs.
  194. // This is also true for XLSX files created through the streaming APIs.
  195. func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) {
  196. // Note, this method could be very slow for large spreadsheets.
  197. var x, y int
  198. var maxVal int
  199. maxVal = int(^uint(0) >> 1)
  200. minx = maxVal
  201. miny = maxVal
  202. maxy = 0
  203. maxx = 0
  204. for _, row := range worksheet.SheetData.Row {
  205. for _, cell := range row.C {
  206. x, y, err = GetCoordsFromCellIDString(cell.R)
  207. if err != nil {
  208. return -1, -1, -1, -1, err
  209. }
  210. if x < minx {
  211. minx = x
  212. }
  213. if x > maxx {
  214. maxx = x
  215. }
  216. if y < miny {
  217. miny = y
  218. }
  219. if y > maxy {
  220. maxy = y
  221. }
  222. }
  223. }
  224. if minx == maxVal {
  225. minx = 0
  226. }
  227. if miny == maxVal {
  228. miny = 0
  229. }
  230. return
  231. }
  232. // makeRowFromSpan will, when given a span expressed as a string,
  233. // return an empty Row large enough to encompass that span and
  234. // populate it with empty cells. All rows start from cell 1 -
  235. // regardless of the lower bound of the span.
  236. func makeRowFromSpan(spans string, sheet *Sheet) *Row {
  237. var error error
  238. var upper int
  239. var row *Row
  240. var cell *Cell
  241. row = new(Row)
  242. row.Sheet = sheet
  243. _, upper, error = getRangeFromString(spans)
  244. if error != nil {
  245. panic(error)
  246. }
  247. error = nil
  248. row.Cells = make([]*Cell, upper)
  249. for i := 0; i < upper; i++ {
  250. cell = new(Cell)
  251. cell.Value = ""
  252. row.Cells[i] = cell
  253. }
  254. return row
  255. }
  256. // makeRowFromRaw returns the Row representation of the xlsxRow.
  257. func makeRowFromRaw(rawrow xlsxRow, sheet *Sheet) *Row {
  258. var upper int
  259. var row *Row
  260. var cell *Cell
  261. row = new(Row)
  262. row.Sheet = sheet
  263. upper = -1
  264. for _, rawcell := range rawrow.C {
  265. if rawcell.R != "" {
  266. x, _, error := GetCoordsFromCellIDString(rawcell.R)
  267. if error != nil {
  268. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  269. }
  270. if x > upper {
  271. upper = x
  272. }
  273. continue
  274. }
  275. upper++
  276. }
  277. upper++
  278. row.OutlineLevel = rawrow.OutlineLevel
  279. row.Cells = make([]*Cell, upper)
  280. for i := 0; i < upper; i++ {
  281. cell = new(Cell)
  282. cell.Value = ""
  283. row.Cells[i] = cell
  284. }
  285. return row
  286. }
  287. func makeEmptyRow(sheet *Sheet) *Row {
  288. row := new(Row)
  289. row.Cells = make([]*Cell, 0)
  290. row.Sheet = sheet
  291. return row
  292. }
  293. type sharedFormula struct {
  294. x, y int
  295. formula string
  296. }
  297. func formulaForCell(rawcell xlsxC, sharedFormulas map[int]sharedFormula) string {
  298. var res string
  299. f := rawcell.F
  300. if f == nil {
  301. return ""
  302. }
  303. if f.T == "shared" {
  304. x, y, err := GetCoordsFromCellIDString(rawcell.R)
  305. if err != nil {
  306. res = f.Content
  307. } else {
  308. if f.Ref != "" {
  309. res = f.Content
  310. sharedFormulas[f.Si] = sharedFormula{x, y, res}
  311. } else {
  312. sharedFormula := sharedFormulas[f.Si]
  313. dx := x - sharedFormula.x
  314. dy := y - sharedFormula.y
  315. orig := []byte(sharedFormula.formula)
  316. var start, end int
  317. var stringLiteral bool
  318. for end = 0; end < len(orig); end++ {
  319. c := orig[end]
  320. if c == '"' {
  321. stringLiteral = !stringLiteral
  322. }
  323. if stringLiteral {
  324. continue // Skip characters in quotes
  325. }
  326. if c >= 'A' && c <= 'Z' || c == '$' {
  327. res += string(orig[start:end])
  328. start = end
  329. end++
  330. foundNum := false
  331. for ; end < len(orig); end++ {
  332. idc := orig[end]
  333. if idc >= '0' && idc <= '9' || idc == '$' {
  334. foundNum = true
  335. } else if idc >= 'A' && idc <= 'Z' {
  336. if foundNum {
  337. break
  338. }
  339. } else {
  340. break
  341. }
  342. }
  343. if foundNum {
  344. cellID := string(orig[start:end])
  345. res += shiftCell(cellID, dx, dy)
  346. start = end
  347. }
  348. }
  349. }
  350. if start < len(orig) {
  351. res += string(orig[start:])
  352. }
  353. }
  354. }
  355. } else {
  356. res = f.Content
  357. }
  358. return strings.Trim(res, " \t\n\r")
  359. }
  360. // shiftCell returns the cell shifted according to dx and dy taking into consideration of absolute
  361. // references with dollar sign ($)
  362. func shiftCell(cellID string, dx, dy int) string {
  363. fx, fy, _ := GetCoordsFromCellIDString(cellID)
  364. // Is fixed column?
  365. fixedCol := strings.Index(cellID, "$") == 0
  366. // Is fixed row?
  367. fixedRow := strings.LastIndex(cellID, "$") > 0
  368. if !fixedCol {
  369. // Shift column
  370. fx += dx
  371. }
  372. if !fixedRow {
  373. // Shift row
  374. fy += dy
  375. }
  376. // New shifted cell
  377. shiftedCellID := GetCellIDStringFromCoords(fx, fy)
  378. if !fixedCol && !fixedRow {
  379. return shiftedCellID
  380. }
  381. // There are absolute references, need to put the $ back into the formula.
  382. letterPart := strings.Map(letterOnlyMapF, shiftedCellID)
  383. numberPart := strings.Map(intOnlyMapF, shiftedCellID)
  384. result := ""
  385. if fixedCol {
  386. result += "$"
  387. }
  388. result += letterPart
  389. if fixedRow {
  390. result += "$"
  391. }
  392. result += numberPart
  393. return result
  394. }
  395. // fillCellData attempts to extract a valid value, usable in
  396. // CSV form from the raw cell value. Note - this is not actually
  397. // general enough - we should support retaining tabs and newlines.
  398. func fillCellData(rawCell xlsxC, refTable *RefTable, sharedFormulas map[int]sharedFormula, cell *Cell) {
  399. val := strings.Trim(rawCell.V, " \t\n\r")
  400. cell.formula = formulaForCell(rawCell, sharedFormulas)
  401. switch rawCell.T {
  402. case "s": // Shared String
  403. cell.cellType = CellTypeString
  404. if val != "" {
  405. ref, err := strconv.Atoi(val)
  406. if err != nil {
  407. panic(err)
  408. }
  409. cell.Value = refTable.ResolveSharedString(ref)
  410. }
  411. case "inlineStr":
  412. cell.cellType = CellTypeInline
  413. fillCellDataFromInlineString(rawCell, cell)
  414. case "b": // Boolean
  415. cell.Value = val
  416. cell.cellType = CellTypeBool
  417. case "e": // Error
  418. cell.Value = val
  419. cell.cellType = CellTypeError
  420. case "str":
  421. // String Formula (special type for cells with formulas that return a string value)
  422. // Unlike the other string cell types, the string is stored directly in the value.
  423. cell.Value = val
  424. cell.cellType = CellTypeStringFormula
  425. case "d": // Date: Cell contains a date in the ISO 8601 format.
  426. cell.Value = val
  427. cell.cellType = CellTypeDate
  428. case "": // Numeric is the default
  429. fallthrough
  430. case "n": // Numeric
  431. cell.Value = val
  432. cell.cellType = CellTypeNumeric
  433. default:
  434. panic(errors.New("invalid cell type"))
  435. }
  436. }
  437. // fillCellDataFromInlineString attempts to get inline string data and put it into a Cell.
  438. func fillCellDataFromInlineString(rawcell xlsxC, cell *Cell) {
  439. cell.Value = ""
  440. if rawcell.Is != nil {
  441. if rawcell.Is.T != "" {
  442. cell.Value = strings.Trim(rawcell.Is.T, " \t\n\r")
  443. } else {
  444. for _, r := range rawcell.Is.R {
  445. cell.Value += r.T
  446. }
  447. }
  448. }
  449. }
  450. // readRowsFromSheet is an internal helper function that extracts the
  451. // rows from a XSLXWorksheet, populates them with Cells and resolves
  452. // the value references from the reference table and stores them in
  453. // the rows and columns.
  454. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File, sheet *Sheet, rowLimit int) ([]*Row, []*Col, int, int) {
  455. var rows []*Row
  456. var cols []*Col
  457. var row *Row
  458. var minCol, maxCol, maxRow, colCount, rowCount int
  459. var reftable *RefTable
  460. var err error
  461. var insertRowIndex, insertColIndex int
  462. sharedFormulas := map[int]sharedFormula{}
  463. if len(Worksheet.SheetData.Row) == 0 {
  464. return nil, nil, 0, 0
  465. }
  466. reftable = file.referenceTable
  467. if len(Worksheet.Dimension.Ref) > 0 && len(strings.Split(Worksheet.Dimension.Ref, ":")) == 2 && rowLimit == NoRowLimit {
  468. minCol, _, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref)
  469. } else {
  470. minCol, _, maxCol, maxRow, err = calculateMaxMinFromWorksheet(Worksheet)
  471. }
  472. if err != nil {
  473. panic(err.Error())
  474. }
  475. rowCount = maxRow + 1
  476. colCount = maxCol + 1
  477. rows = make([]*Row, rowCount)
  478. cols = make([]*Col, colCount)
  479. for i := range cols {
  480. cols[i] = &Col{
  481. Hidden: false,
  482. }
  483. }
  484. if Worksheet.Cols != nil {
  485. // Columns can apply to a range, for convenience we expand the
  486. // ranges out into individual column definitions.
  487. for _, rawcol := range Worksheet.Cols.Col {
  488. // Note, below, that sometimes column definitions can
  489. // exist outside the defined dimensions of the
  490. // spreadsheet - we deliberately exclude these
  491. // columns.
  492. for i := rawcol.Min; i <= rawcol.Max && i <= colCount; i++ {
  493. col := &Col{
  494. Min: rawcol.Min,
  495. Max: rawcol.Max,
  496. Hidden: rawcol.Hidden,
  497. Width: rawcol.Width,
  498. OutlineLevel: rawcol.OutlineLevel}
  499. cols[i-1] = col
  500. if file.styles != nil {
  501. col.style = file.styles.getStyle(rawcol.Style)
  502. col.numFmt, col.parsedNumFmt = file.styles.getNumberFormat(rawcol.Style)
  503. }
  504. }
  505. }
  506. }
  507. numRows := len(rows)
  508. for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ {
  509. rawrow := Worksheet.SheetData.Row[rowIndex]
  510. // Some spreadsheets will omit blank rows from the
  511. // stored data
  512. for rawrow.R > (insertRowIndex + 1) {
  513. // Put an empty Row into the array
  514. if insertRowIndex < numRows {
  515. rows[insertRowIndex] = makeEmptyRow(sheet)
  516. }
  517. insertRowIndex++
  518. }
  519. // range is not empty and only one range exist
  520. if len(rawrow.Spans) != 0 && strings.Count(rawrow.Spans, ":") == 1 {
  521. row = makeRowFromSpan(rawrow.Spans, sheet)
  522. } else {
  523. row = makeRowFromRaw(rawrow, sheet)
  524. }
  525. row.Hidden = rawrow.Hidden
  526. height, err := strconv.ParseFloat(rawrow.Ht, 64)
  527. if err == nil {
  528. row.Height = height
  529. }
  530. row.isCustom = rawrow.CustomHeight
  531. row.OutlineLevel = rawrow.OutlineLevel
  532. insertColIndex = minCol
  533. for _, rawcell := range rawrow.C {
  534. h, v, err := Worksheet.MergeCells.getExtent(rawcell.R)
  535. if err != nil {
  536. panic(err.Error())
  537. }
  538. x, _, _ := GetCoordsFromCellIDString(rawcell.R)
  539. // K1000000: Prevent panic when the range specified in the spreadsheet
  540. // view exceeds the actual number of columns in the dataset.
  541. // Some spreadsheets will omit blank cells
  542. // from the data.
  543. for x > insertColIndex {
  544. // Put an empty Cell into the array
  545. if insertColIndex < len(row.Cells) {
  546. row.Cells[insertColIndex] = new(Cell)
  547. }
  548. insertColIndex++
  549. }
  550. cellX := insertColIndex
  551. if cellX < len(row.Cells) {
  552. cell := row.Cells[cellX]
  553. cell.HMerge = h
  554. cell.VMerge = v
  555. fillCellData(rawcell, reftable, sharedFormulas, cell)
  556. if file.styles != nil {
  557. cell.style = file.styles.getStyle(rawcell.S)
  558. cell.NumFmt, cell.parsedNumFmt = file.styles.getNumberFormat(rawcell.S)
  559. }
  560. cell.date1904 = file.Date1904
  561. // Cell is considered hidden if the row or the column of this cell is hidden
  562. cell.Hidden = rawrow.Hidden || (len(cols) > cellX && cols[cellX].Hidden)
  563. insertColIndex++
  564. }
  565. }
  566. if len(rows) > insertRowIndex {
  567. rows[insertRowIndex] = row
  568. }
  569. insertRowIndex++
  570. }
  571. // insert trailing empty rows for the rest of the file
  572. for ; insertRowIndex < rowCount; insertRowIndex++ {
  573. rows[insertRowIndex] = makeEmptyRow(sheet)
  574. }
  575. return rows, cols, colCount, rowCount
  576. }
  577. type indexedSheet struct {
  578. Index int
  579. Sheet *Sheet
  580. Error error
  581. }
  582. func readSheetViews(xSheetViews xlsxSheetViews) []SheetView {
  583. if xSheetViews.SheetView == nil || len(xSheetViews.SheetView) == 0 {
  584. return nil
  585. }
  586. sheetViews := []SheetView{}
  587. for _, xSheetView := range xSheetViews.SheetView {
  588. sheetView := SheetView{}
  589. if xSheetView.Pane != nil {
  590. xlsxPane := xSheetView.Pane
  591. pane := &Pane{}
  592. pane.XSplit = xlsxPane.XSplit
  593. pane.YSplit = xlsxPane.YSplit
  594. pane.TopLeftCell = xlsxPane.TopLeftCell
  595. pane.ActivePane = xlsxPane.ActivePane
  596. pane.State = xlsxPane.State
  597. sheetView.Pane = pane
  598. }
  599. sheetViews = append(sheetViews, sheetView)
  600. }
  601. return sheetViews
  602. }
  603. // readSheetFromFile is the logic of converting a xlsxSheet struct
  604. // into a Sheet struct. This work can be done in parallel and so
  605. // readSheetsFromZipFile will spawn an instance of this function per
  606. // sheet and get the results back on the provided channel.
  607. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string, rowLimit int) (errRes error) {
  608. result := &indexedSheet{Index: index, Sheet: nil, Error: nil}
  609. defer func() {
  610. if e := recover(); e != nil {
  611. switch e.(type) {
  612. case error:
  613. result.Error = e.(error)
  614. errRes = e.(error)
  615. default:
  616. result.Error = errors.New("unexpected error")
  617. }
  618. // The only thing here, is if one close the channel. but its not the case
  619. sc <- result
  620. }
  621. }()
  622. worksheet, err := getWorksheetFromSheet(rsheet, fi.worksheets, sheetXMLMap, rowLimit)
  623. if err != nil {
  624. result.Error = err
  625. sc <- result
  626. return err
  627. }
  628. sheet := new(Sheet)
  629. sheet.File = fi
  630. sheet.Rows, sheet.Cols, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi, sheet, rowLimit)
  631. sheet.Hidden = rsheet.State == sheetStateHidden || rsheet.State == sheetStateVeryHidden
  632. sheet.SheetViews = readSheetViews(worksheet.SheetViews)
  633. sheet.SheetFormat.DefaultColWidth = worksheet.SheetFormatPr.DefaultColWidth
  634. sheet.SheetFormat.DefaultRowHeight = worksheet.SheetFormatPr.DefaultRowHeight
  635. sheet.SheetFormat.OutlineLevelCol = worksheet.SheetFormatPr.OutlineLevelCol
  636. sheet.SheetFormat.OutlineLevelRow = worksheet.SheetFormatPr.OutlineLevelRow
  637. result.Sheet = sheet
  638. sc <- result
  639. return nil
  640. }
  641. // readSheetsFromZipFile is an internal helper function that loops
  642. // over the Worksheets defined in the XSLXWorkbook and loads them into
  643. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  644. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string, rowLimit int) (map[string]*Sheet, []*Sheet, error) {
  645. var workbook *xlsxWorkbook
  646. var err error
  647. var rc io.ReadCloser
  648. var decoder *xml.Decoder
  649. var sheetCount int
  650. workbook = new(xlsxWorkbook)
  651. rc, err = f.Open()
  652. if err != nil {
  653. return nil, nil, err
  654. }
  655. decoder = xml.NewDecoder(rc)
  656. err = decoder.Decode(workbook)
  657. if err != nil {
  658. return nil, nil, err
  659. }
  660. file.Date1904 = workbook.WorkbookPr.Date1904
  661. for entryNum := range workbook.DefinedNames.DefinedName {
  662. file.DefinedNames = append(file.DefinedNames, &workbook.DefinedNames.DefinedName[entryNum])
  663. }
  664. // Only try and read sheets that have corresponding files.
  665. // Notably this excludes chartsheets don't right now
  666. var workbookSheets []xlsxSheet
  667. for _, sheet := range workbook.Sheets.Sheet {
  668. if f := worksheetFileForSheet(sheet, file.worksheets, sheetXMLMap); f != nil {
  669. workbookSheets = append(workbookSheets, sheet)
  670. }
  671. }
  672. sheetCount = len(workbookSheets)
  673. sheetsByName := make(map[string]*Sheet, sheetCount)
  674. sheets := make([]*Sheet, sheetCount)
  675. sheetChan := make(chan *indexedSheet, sheetCount)
  676. go func() {
  677. defer close(sheetChan)
  678. err = nil
  679. for i, rawsheet := range workbookSheets {
  680. if err := readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap, rowLimit); err != nil {
  681. return
  682. }
  683. }
  684. }()
  685. for j := 0; j < sheetCount; j++ {
  686. sheet := <-sheetChan
  687. if sheet.Error != nil {
  688. return nil, nil, sheet.Error
  689. }
  690. sheetName := workbookSheets[sheet.Index].Name
  691. sheetsByName[sheetName] = sheet.Sheet
  692. sheet.Sheet.Name = sheetName
  693. sheets[sheet.Index] = sheet.Sheet
  694. }
  695. return sheetsByName, sheets, nil
  696. }
  697. // readSharedStringsFromZipFile() is an internal helper function to
  698. // extract a reference table from the sharedStrings.xml file within
  699. // the XLSX zip file.
  700. func readSharedStringsFromZipFile(f *zip.File) (*RefTable, error) {
  701. var sst *xlsxSST
  702. var error error
  703. var rc io.ReadCloser
  704. var decoder *xml.Decoder
  705. var reftable *RefTable
  706. // In a file with no strings it's possible that
  707. // sharedStrings.xml doesn't exist. In this case the value
  708. // passed as f will be nil.
  709. if f == nil {
  710. return nil, nil
  711. }
  712. rc, error = f.Open()
  713. if error != nil {
  714. return nil, error
  715. }
  716. sst = new(xlsxSST)
  717. decoder = xml.NewDecoder(rc)
  718. error = decoder.Decode(sst)
  719. if error != nil {
  720. return nil, error
  721. }
  722. reftable = MakeSharedStringRefTable(sst)
  723. return reftable, nil
  724. }
  725. // readStylesFromZipFile() is an internal helper function to
  726. // extract a style table from the style.xml file within
  727. // the XLSX zip file.
  728. func readStylesFromZipFile(f *zip.File, theme *theme) (*xlsxStyleSheet, error) {
  729. var style *xlsxStyleSheet
  730. var error error
  731. var rc io.ReadCloser
  732. var decoder *xml.Decoder
  733. rc, error = f.Open()
  734. if error != nil {
  735. return nil, error
  736. }
  737. style = newXlsxStyleSheet(theme)
  738. decoder = xml.NewDecoder(rc)
  739. error = decoder.Decode(style)
  740. if error != nil {
  741. return nil, error
  742. }
  743. buildNumFmtRefTable(style)
  744. return style, nil
  745. }
  746. func buildNumFmtRefTable(style *xlsxStyleSheet) {
  747. for _, numFmt := range style.NumFmts.NumFmt {
  748. // We do this for the side effect of populating the NumFmtRefTable.
  749. style.addNumFmt(numFmt)
  750. }
  751. }
  752. func readThemeFromZipFile(f *zip.File) (*theme, error) {
  753. rc, err := f.Open()
  754. if err != nil {
  755. return nil, err
  756. }
  757. var themeXml xlsxTheme
  758. err = xml.NewDecoder(rc).Decode(&themeXml)
  759. if err != nil {
  760. return nil, err
  761. }
  762. return newTheme(themeXml), nil
  763. }
  764. type WorkBookRels map[string]string
  765. func (w *WorkBookRels) MakeXLSXWorkbookRels() xlsxWorkbookRels {
  766. relCount := len(*w)
  767. xWorkbookRels := xlsxWorkbookRels{}
  768. xWorkbookRels.Relationships = make([]xlsxWorkbookRelation, relCount+3)
  769. for k, v := range *w {
  770. index, err := strconv.Atoi(k[3:])
  771. if err != nil {
  772. panic(err.Error())
  773. }
  774. xWorkbookRels.Relationships[index-1] = xlsxWorkbookRelation{
  775. Id: k,
  776. Target: v,
  777. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"}
  778. }
  779. relCount++
  780. sheetId := fmt.Sprintf("rId%d", relCount)
  781. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  782. Id: sheetId,
  783. Target: "sharedStrings.xml",
  784. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"}
  785. relCount++
  786. sheetId = fmt.Sprintf("rId%d", relCount)
  787. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  788. Id: sheetId,
  789. Target: "theme/theme1.xml",
  790. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"}
  791. relCount++
  792. sheetId = fmt.Sprintf("rId%d", relCount)
  793. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  794. Id: sheetId,
  795. Target: "styles.xml",
  796. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"}
  797. return xWorkbookRels
  798. }
  799. // readWorkbookRelationsFromZipFile is an internal helper function to
  800. // extract a map of relationship ID strings to the name of the
  801. // worksheet.xml file they refer to. The resulting map can be used to
  802. // reliably derefence the worksheets in the XLSX file.
  803. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (WorkBookRels, error) {
  804. var sheetXMLMap WorkBookRels
  805. var wbRelationships *xlsxWorkbookRels
  806. var rc io.ReadCloser
  807. var decoder *xml.Decoder
  808. var err error
  809. rc, err = workbookRels.Open()
  810. if err != nil {
  811. return nil, err
  812. }
  813. decoder = xml.NewDecoder(rc)
  814. wbRelationships = new(xlsxWorkbookRels)
  815. err = decoder.Decode(wbRelationships)
  816. if err != nil {
  817. return nil, err
  818. }
  819. sheetXMLMap = make(WorkBookRels)
  820. for _, rel := range wbRelationships.Relationships {
  821. if strings.HasSuffix(rel.Target, ".xml") && rel.Type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" {
  822. _, filename := path.Split(rel.Target)
  823. sheetXMLMap[rel.Id] = strings.Replace(filename, ".xml", "", 1)
  824. }
  825. }
  826. return sheetXMLMap, nil
  827. }
  828. // ReadZip() takes a pointer to a zip.ReadCloser and returns a
  829. // xlsx.File struct populated with its contents. In most cases
  830. // ReadZip is not used directly, but is called internally by OpenFile.
  831. func ReadZip(f *zip.ReadCloser) (*File, error) {
  832. return ReadZipWithRowLimit(f, NoRowLimit)
  833. }
  834. // ReadZipWithRowLimit() takes a pointer to a zip.ReadCloser and returns a
  835. // xlsx.File struct populated with its contents. In most cases
  836. // ReadZip is not used directly, but is called internally by OpenFile.
  837. func ReadZipWithRowLimit(f *zip.ReadCloser, rowLimit int) (*File, error) {
  838. defer f.Close()
  839. return ReadZipReaderWithRowLimit(&f.Reader, rowLimit)
  840. }
  841. // ReadZipReader() can be used to read an XLSX in memory without
  842. // touching the filesystem.
  843. func ReadZipReader(r *zip.Reader) (*File, error) {
  844. return ReadZipReaderWithRowLimit(r, NoRowLimit)
  845. }
  846. // ReadZipReaderWithRowLimit() can be used to read an XLSX in memory without
  847. // touching the filesystem.
  848. // rowLimit is the number of rows that should be read from the file. If rowLimit is -1, no limit is applied.
  849. // You can specify this with the constant NoRowLimit.
  850. func ReadZipReaderWithRowLimit(r *zip.Reader, rowLimit int) (*File, error) {
  851. var err error
  852. var file *File
  853. var reftable *RefTable
  854. var sharedStrings *zip.File
  855. var sheetXMLMap map[string]string
  856. var sheetsByName map[string]*Sheet
  857. var sheets []*Sheet
  858. var style *xlsxStyleSheet
  859. var styles *zip.File
  860. var themeFile *zip.File
  861. var v *zip.File
  862. var workbook *zip.File
  863. var workbookRels *zip.File
  864. var worksheets map[string]*zip.File
  865. file = NewFile()
  866. // file.numFmtRefTable = make(map[int]xlsxNumFmt, 1)
  867. worksheets = make(map[string]*zip.File, len(r.File))
  868. for _, v = range r.File {
  869. switch v.Name {
  870. case "xl/sharedStrings.xml":
  871. sharedStrings = v
  872. case "xl/workbook.xml":
  873. workbook = v
  874. case "xl/_rels/workbook.xml.rels":
  875. workbookRels = v
  876. case "xl/styles.xml":
  877. styles = v
  878. case "xl/theme/theme1.xml":
  879. themeFile = v
  880. default:
  881. if len(v.Name) > 17 {
  882. if v.Name[0:13] == "xl/worksheets" {
  883. worksheets[v.Name[14:len(v.Name)-4]] = v
  884. }
  885. }
  886. }
  887. }
  888. if workbookRels == nil {
  889. return nil, fmt.Errorf("xl/_rels/workbook.xml.rels not found in input xlsx.")
  890. }
  891. sheetXMLMap, err = readWorkbookRelationsFromZipFile(workbookRels)
  892. if err != nil {
  893. return nil, err
  894. }
  895. if len(worksheets) == 0 {
  896. return nil, fmt.Errorf("Input xlsx contains no worksheets.")
  897. }
  898. file.worksheets = worksheets
  899. reftable, err = readSharedStringsFromZipFile(sharedStrings)
  900. if err != nil {
  901. return nil, err
  902. }
  903. file.referenceTable = reftable
  904. if themeFile != nil {
  905. theme, err := readThemeFromZipFile(themeFile)
  906. if err != nil {
  907. return nil, err
  908. }
  909. file.theme = theme
  910. }
  911. if styles != nil {
  912. style, err = readStylesFromZipFile(styles, file.theme)
  913. if err != nil {
  914. return nil, err
  915. }
  916. file.styles = style
  917. }
  918. sheetsByName, sheets, err = readSheetsFromZipFile(workbook, file, sheetXMLMap, rowLimit)
  919. if err != nil {
  920. return nil, err
  921. }
  922. if sheets == nil {
  923. readerErr := new(XLSXReaderError)
  924. readerErr.Err = "No sheets found in XLSX File"
  925. return nil, readerErr
  926. }
  927. file.Sheet = sheetsByName
  928. file.Sheets = sheets
  929. return file, nil
  930. }
  931. // truncateSheetXML will take in a reader to an XML sheet file and will return a reader that will read an equivalent
  932. // XML sheet file with only the number of rows specified. This greatly speeds up XML unmarshalling when only
  933. // a few rows need to be read from a large sheet.
  934. // When sheets are truncated, all formatting present after the sheetData tag will be lost, but all of this formatting
  935. // is related to printing and visibility, and is out of scope for most purposes of this library.
  936. func truncateSheetXML(r io.Reader, rowLimit int) (io.Reader, error) {
  937. var rowCount int
  938. var token xml.Token
  939. var readErr error
  940. output := new(bytes.Buffer)
  941. r = io.TeeReader(r, output)
  942. decoder := xml.NewDecoder(r)
  943. for {
  944. token, readErr = decoder.Token()
  945. if readErr == io.EOF {
  946. break
  947. } else if readErr != nil {
  948. return nil, readErr
  949. }
  950. end, ok := token.(xml.EndElement)
  951. if ok && end.Name.Local == "row" {
  952. rowCount++
  953. if rowCount >= rowLimit {
  954. break
  955. }
  956. }
  957. }
  958. offset := decoder.InputOffset()
  959. output.Truncate(int(offset))
  960. if readErr != io.EOF {
  961. _, err := output.Write([]byte(sheetEnding))
  962. if err != nil {
  963. return nil, err
  964. }
  965. }
  966. return output, nil
  967. }