lib.go 29 KB

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