lib.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "encoding/xml"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "path"
  9. "strconv"
  10. "strings"
  11. )
  12. // XLSXReaderError is the standard error type for otherwise undefined
  13. // errors in the XSLX reading process.
  14. type XLSXReaderError struct {
  15. Err string
  16. }
  17. // String() returns a string value from an XLSXReaderError struct in
  18. // order that it might comply with the os.Error interface.
  19. func (e *XLSXReaderError) Error() string {
  20. return e.Err
  21. }
  22. // getRangeFromString is an internal helper function that converts
  23. // XLSX internal range syntax to a pair of integers. For example,
  24. // the range string "1:3" yield the upper and lower intergers 1 and 3.
  25. func getRangeFromString(rangeString string) (lower int, upper int, error error) {
  26. var parts []string
  27. parts = strings.SplitN(rangeString, ":", 2)
  28. if parts[0] == "" {
  29. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  30. }
  31. if parts[1] == "" {
  32. error = errors.New(fmt.Sprintf("Invalid range '%s'\n", rangeString))
  33. }
  34. lower, error = strconv.Atoi(parts[0])
  35. if error != nil {
  36. error = errors.New(fmt.Sprintf("Invalid range (not integer in lower bound) %s\n", rangeString))
  37. }
  38. upper, error = strconv.Atoi(parts[1])
  39. if error != nil {
  40. error = errors.New(fmt.Sprintf("Invalid range (not integer in upper bound) %s\n", rangeString))
  41. }
  42. return lower, upper, error
  43. }
  44. // lettersToNumeric is used to convert a character based column
  45. // reference to a zero based numeric column identifier.
  46. func lettersToNumeric(letters string) int {
  47. sum, mul, n := 0, 1, 0
  48. for i := len(letters) - 1; i >= 0; i, mul, n = i-1, mul*26, 1 {
  49. c := letters[i]
  50. switch {
  51. case 'A' <= c && c <= 'Z':
  52. n += int(c - 'A')
  53. case 'a' <= c && c <= 'z':
  54. n += int(c - 'a')
  55. }
  56. sum += n * mul
  57. }
  58. return sum
  59. }
  60. // Get the largestDenominator that is a multiple of a basedDenominator
  61. // and fits at least once into a given numerator.
  62. func getLargestDenominator(numerator, multiple, baseDenominator, power int) (int, int) {
  63. if numerator/multiple == 0 {
  64. return 1, power
  65. }
  66. next, nextPower := getLargestDenominator(
  67. numerator, multiple*baseDenominator, baseDenominator, power+1)
  68. if next > multiple {
  69. return next, nextPower
  70. }
  71. return multiple, power
  72. }
  73. // Convers a list of numbers representing a column into a alphabetic
  74. // representation, as used in the spreadsheet.
  75. func formatColumnName(colId []int) string {
  76. lastPart := len(colId) - 1
  77. result := ""
  78. for n, part := range colId {
  79. if n == lastPart {
  80. // The least significant number is in the
  81. // range 0-25, all other numbers are 1-26,
  82. // hence we use a differente offset for the
  83. // last part.
  84. result += string(part + 65)
  85. } else {
  86. // Don't output leading 0s, as there is no
  87. // representation of 0 in this format.
  88. if part > 0 {
  89. result += string(part + 64)
  90. }
  91. }
  92. }
  93. return result
  94. }
  95. func smooshBase26Slice(b26 []int) []int {
  96. // Smoosh values together, eliminating 0s from all but the
  97. // least significant part.
  98. lastButOnePart := len(b26) - 2
  99. for i := lastButOnePart; i > 0; i-- {
  100. part := b26[i]
  101. if part == 0 {
  102. greaterPart := b26[i-1]
  103. if greaterPart > 0 {
  104. b26[i-1] = greaterPart - 1
  105. b26[i] = 26
  106. }
  107. }
  108. }
  109. return b26
  110. }
  111. func intToBase26(x int) (parts []int) {
  112. // Excel column codes are pure evil - in essence they're just
  113. // base26, but they don't represent the number 0.
  114. b26Denominator, _ := getLargestDenominator(x, 1, 26, 0)
  115. // This loop terminates because integer division of 1 / 26
  116. // returns 0.
  117. for d := b26Denominator; d > 0; d = d / 26 {
  118. value := x / d
  119. remainder := x % d
  120. parts = append(parts, value)
  121. x = remainder
  122. }
  123. return parts
  124. }
  125. // numericToLetters is used to convert a zero based, numeric column
  126. // indentifier into a character code.
  127. func numericToLetters(colRef int) string {
  128. parts := intToBase26(colRef)
  129. return formatColumnName(smooshBase26Slice(parts))
  130. }
  131. // letterOnlyMapF is used in conjunction with strings.Map to return
  132. // only the characters A-Z and a-z in a string
  133. func letterOnlyMapF(rune rune) rune {
  134. switch {
  135. case 'A' <= rune && rune <= 'Z':
  136. return rune
  137. case 'a' <= rune && rune <= 'z':
  138. return rune - 32
  139. }
  140. return -1
  141. }
  142. // intOnlyMapF is used in conjunction with strings.Map to return only
  143. // the numeric portions of a string.
  144. func intOnlyMapF(rune rune) rune {
  145. if rune >= 48 && rune < 58 {
  146. return rune
  147. }
  148. return -1
  149. }
  150. // getCoordsFromCellIDString returns the zero based cartesian
  151. // coordinates from a cell name in Excel format, e.g. the cellIDString
  152. // "A1" returns 0, 0 and the "B3" return 1, 2.
  153. func getCoordsFromCellIDString(cellIDString string) (x, y int, error error) {
  154. var letterPart string = strings.Map(letterOnlyMapF, cellIDString)
  155. y, error = strconv.Atoi(strings.Map(intOnlyMapF, cellIDString))
  156. if error != nil {
  157. return x, y, error
  158. }
  159. y -= 1 // Zero based
  160. x = lettersToNumeric(letterPart)
  161. return x, y, error
  162. }
  163. // getCellIDStringFromCoords returns the Excel format cell name that
  164. // represents a pair of zero based cartesian coordinates.
  165. func getCellIDStringFromCoords(x, y int) string {
  166. letterPart := numericToLetters(x)
  167. numericPart := y + 1
  168. return fmt.Sprintf("%s%d", letterPart, numericPart)
  169. }
  170. // getMaxMinFromDimensionRef return the zero based cartesian maximum
  171. // and minimum coordinates from the dimension reference embedded in a
  172. // XLSX worksheet. For example, the dimension reference "A1:B2"
  173. // returns "0,0", "1,1".
  174. func getMaxMinFromDimensionRef(ref string) (minx, miny, maxx, maxy int, err error) {
  175. var parts []string
  176. parts = strings.Split(ref, ":")
  177. minx, miny, err = getCoordsFromCellIDString(parts[0])
  178. if err != nil {
  179. return -1, -1, -1, -1, err
  180. }
  181. if len(parts) == 1 {
  182. maxx, maxy = minx, miny
  183. return
  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. func calculateMaxMinFromWorksheet(worksheet *xlsxWorksheet) (minx, miny, maxx, maxy int, err error) {
  195. // Note, this method could be very slow for large spreadsheets.
  196. var x, y int
  197. var maxVal int
  198. maxVal = int(^uint(0) >> 1)
  199. minx = maxVal
  200. miny = maxVal
  201. maxy = 0
  202. maxx = 0
  203. for _, row := range worksheet.SheetData.Row {
  204. for _, cell := range row.C {
  205. x, y, err = getCoordsFromCellIDString(cell.R)
  206. if err != nil {
  207. return -1, -1, -1, -1, err
  208. }
  209. if x < minx {
  210. minx = x
  211. }
  212. if x > maxx {
  213. maxx = x
  214. }
  215. if y < miny {
  216. miny = y
  217. }
  218. if y > maxy {
  219. maxy = y
  220. }
  221. }
  222. }
  223. if minx == maxVal {
  224. minx = 0
  225. }
  226. if miny == maxVal {
  227. miny = 0
  228. }
  229. return
  230. }
  231. // makeRowFromSpan will, when given a span expressed as a string,
  232. // return an empty Row large enough to encompass that span and
  233. // populate it with empty cells. All rows start from cell 1 -
  234. // regardless of the lower bound of the span.
  235. func makeRowFromSpan(spans string) *Row {
  236. var error error
  237. var upper int
  238. var row *Row
  239. var cell *Cell
  240. row = new(Row)
  241. _, upper, error = getRangeFromString(spans)
  242. if error != nil {
  243. panic(error)
  244. }
  245. error = nil
  246. row.Cells = make([]*Cell, upper)
  247. for i := 0; i < upper; i++ {
  248. cell = new(Cell)
  249. cell.Value = ""
  250. row.Cells[i] = cell
  251. }
  252. return row
  253. }
  254. // makeRowFromRaw returns the Row representation of the xlsxRow.
  255. func makeRowFromRaw(rawrow xlsxRow) *Row {
  256. var upper int
  257. var row *Row
  258. var cell *Cell
  259. row = new(Row)
  260. upper = -1
  261. for _, rawcell := range rawrow.C {
  262. if rawcell.R != "" {
  263. x, _, error := getCoordsFromCellIDString(rawcell.R)
  264. if error != nil {
  265. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  266. }
  267. if x > upper {
  268. upper = x
  269. }
  270. continue
  271. }
  272. upper++
  273. }
  274. upper++
  275. row.Cells = make([]*Cell, upper)
  276. for i := 0; i < upper; i++ {
  277. cell = new(Cell)
  278. cell.Value = ""
  279. row.Cells[i] = cell
  280. }
  281. return row
  282. }
  283. func makeEmptyRow() *Row {
  284. row := new(Row)
  285. row.Cells = make([]*Cell, 0)
  286. return row
  287. }
  288. // fillCellData attempts to extract a valid value, usable in
  289. // CSV form from the raw cell value. Note - this is not actually
  290. // general enough - we should support retaining tabs and newlines.
  291. func fillCellData(rawcell xlsxC, reftable *RefTable, cell *Cell) {
  292. var data string = rawcell.V
  293. if len(data) > 0 {
  294. vval := strings.Trim(data, " \t\n\r")
  295. switch rawcell.T {
  296. case "s": // Shared String
  297. ref, error := strconv.Atoi(vval)
  298. if error != nil {
  299. panic(error)
  300. }
  301. cell.Value = reftable.ResolveSharedString(ref)
  302. cell.cellType = CellTypeString
  303. case "b": // Boolean
  304. cell.Value = vval
  305. cell.cellType = CellTypeBool
  306. case "e": // Error
  307. cell.Value = vval
  308. cell.formula = strings.Trim(rawcell.F, " \t\n\r")
  309. cell.cellType = CellTypeError
  310. default:
  311. if len(rawcell.F) == 0 {
  312. // Numeric
  313. cell.Value = vval
  314. cell.cellType = CellTypeNumeric
  315. } else {
  316. // Formula
  317. cell.Value = vval
  318. cell.formula = strings.Trim(rawcell.F, " \t\n\r")
  319. cell.cellType = CellTypeFormula
  320. }
  321. }
  322. }
  323. }
  324. // readRowsFromSheet is an internal helper function that extracts the
  325. // rows from a XSLXWorksheet, populates them with Cells and resolves
  326. // the value references from the reference table and stores them in
  327. // the rows and columns.
  328. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File) ([]*Row, []*Col, int, int) {
  329. var rows []*Row
  330. var cols []*Col
  331. var row *Row
  332. var minCol, maxCol, minRow, maxRow, colCount, rowCount int
  333. var reftable *RefTable
  334. var err error
  335. var insertRowIndex, insertColIndex int
  336. if len(Worksheet.SheetData.Row) == 0 {
  337. return nil, nil, 0, 0
  338. }
  339. reftable = file.referenceTable
  340. if len(Worksheet.Dimension.Ref) > 0 {
  341. minCol, minRow, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref)
  342. } else {
  343. minCol, minRow, maxCol, maxRow, err = calculateMaxMinFromWorksheet(Worksheet)
  344. }
  345. if err != nil {
  346. panic(err.Error())
  347. }
  348. rowCount = maxRow + 1
  349. colCount = maxCol + 1
  350. rows = make([]*Row, rowCount)
  351. cols = make([]*Col, colCount)
  352. insertRowIndex = minRow
  353. for i := range cols {
  354. cols[i] = &Col{
  355. Hidden: false,
  356. }
  357. }
  358. // Columns can apply to a range, for convenience we expand the
  359. // ranges out into individual column definitions.
  360. for _, rawcol := range Worksheet.Cols.Col {
  361. // Note, below, that sometimes column definitions can
  362. // exist outside the defined dimensions of the
  363. // spreadsheet - we deliberately exclude these
  364. // columns.
  365. for i := rawcol.Min; i <= rawcol.Max && i <= colCount; i++ {
  366. cols[i-1] = &Col{
  367. Min: rawcol.Min,
  368. Max: rawcol.Max,
  369. Hidden: rawcol.Hidden,
  370. Width: rawcol.Width}
  371. }
  372. }
  373. // insert leading empty rows that is in front of minRow
  374. for rowIndex := 0; rowIndex < minRow; rowIndex++ {
  375. rows[rowIndex] = makeEmptyRow()
  376. }
  377. for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ {
  378. rawrow := Worksheet.SheetData.Row[rowIndex]
  379. // Some spreadsheets will omit blank rows from the
  380. // stored data
  381. for rawrow.R > (insertRowIndex + 1) {
  382. // Put an empty Row into the array
  383. rows[insertRowIndex-minRow] = makeEmptyRow()
  384. insertRowIndex++
  385. }
  386. // range is not empty and only one range exist
  387. if len(rawrow.Spans) != 0 && strings.Count(rawrow.Spans, ":") == 1 {
  388. row = makeRowFromSpan(rawrow.Spans)
  389. } else {
  390. row = makeRowFromRaw(rawrow)
  391. }
  392. row.Hidden = rawrow.Hidden
  393. insertColIndex = minCol
  394. for _, rawcell := range rawrow.C {
  395. x, _, _ := getCoordsFromCellIDString(rawcell.R)
  396. // Some spreadsheets will omit blank cells
  397. // from the data.
  398. for x > insertColIndex {
  399. // Put an empty Cell into the array
  400. row.Cells[insertColIndex-minCol] = new(Cell)
  401. insertColIndex++
  402. }
  403. cellX := insertColIndex
  404. cell := row.Cells[cellX]
  405. fillCellData(rawcell, reftable, cell)
  406. if file.styles != nil {
  407. cell.style = file.styles.getStyle(rawcell.S)
  408. cell.numFmt = file.styles.getNumberFormat(rawcell.S)
  409. }
  410. cell.date1904 = file.Date1904
  411. cell.Hidden = rawrow.Hidden || (len(cols) > cellX && cell.Hidden)
  412. insertColIndex++
  413. }
  414. if len(rows) > insertRowIndex {
  415. rows[insertRowIndex] = row
  416. }
  417. insertRowIndex++
  418. }
  419. return rows, cols, colCount, rowCount
  420. }
  421. type indexedSheet struct {
  422. Index int
  423. Sheet *Sheet
  424. Error error
  425. }
  426. // readSheetFromFile is the logic of converting a xlsxSheet struct
  427. // into a Sheet struct. This work can be done in parallel and so
  428. // readSheetsFromZipFile will spawn an instance of this function per
  429. // sheet and get the results back on the provided channel.
  430. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string) {
  431. result := &indexedSheet{Index: index, Sheet: nil, Error: nil}
  432. worksheet, error := getWorksheetFromSheet(rsheet, fi.worksheets, sheetXMLMap)
  433. if error != nil {
  434. result.Error = error
  435. sc <- result
  436. return
  437. }
  438. sheet := new(Sheet)
  439. sheet.File = fi
  440. sheet.Rows, sheet.Cols, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi)
  441. sheet.Hidden = rsheet.State == sheetStateHidden || rsheet.State == sheetStateVeryHidden
  442. result.Sheet = sheet
  443. sc <- result
  444. }
  445. // readSheetsFromZipFile is an internal helper function that loops
  446. // over the Worksheets defined in the XSLXWorkbook and loads them into
  447. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  448. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string) (map[string]*Sheet, []*Sheet, error) {
  449. var workbook *xlsxWorkbook
  450. var err error
  451. var rc io.ReadCloser
  452. var decoder *xml.Decoder
  453. var sheetCount int
  454. workbook = new(xlsxWorkbook)
  455. rc, err = f.Open()
  456. if err != nil {
  457. return nil, nil, err
  458. }
  459. decoder = xml.NewDecoder(rc)
  460. err = decoder.Decode(workbook)
  461. if err != nil {
  462. return nil, nil, err
  463. }
  464. file.Date1904 = workbook.WorkbookPr.Date1904
  465. sheetCount = len(workbook.Sheets.Sheet)
  466. sheetsByName := make(map[string]*Sheet, sheetCount)
  467. sheets := make([]*Sheet, sheetCount)
  468. sheetChan := make(chan *indexedSheet, sheetCount)
  469. defer close(sheetChan)
  470. go func() {
  471. defer func() {
  472. if e := recover(); e != nil {
  473. err = fmt.Errorf("%v", e)
  474. result := &indexedSheet{Index: -1, Sheet: nil, Error: err}
  475. sheetChan <- result
  476. }
  477. }()
  478. err = nil
  479. for i, rawsheet := range workbook.Sheets.Sheet {
  480. readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap)
  481. }
  482. }()
  483. for j := 0; j < sheetCount; j++ {
  484. sheet := <-sheetChan
  485. if sheet.Error != nil {
  486. return nil, nil, sheet.Error
  487. }
  488. sheetName := workbook.Sheets.Sheet[sheet.Index].Name
  489. sheetsByName[sheetName] = sheet.Sheet
  490. sheet.Sheet.Name = sheetName
  491. sheets[sheet.Index] = sheet.Sheet
  492. }
  493. return sheetsByName, sheets, nil
  494. }
  495. // readSharedStringsFromZipFile() is an internal helper function to
  496. // extract a reference table from the sharedStrings.xml file within
  497. // the XLSX zip file.
  498. func readSharedStringsFromZipFile(f *zip.File) (*RefTable, error) {
  499. var sst *xlsxSST
  500. var error error
  501. var rc io.ReadCloser
  502. var decoder *xml.Decoder
  503. var reftable *RefTable
  504. // In a file with no strings it's possible that
  505. // sharedStrings.xml doesn't exist. In this case the value
  506. // passed as f will be nil.
  507. if f == nil {
  508. return nil, nil
  509. }
  510. rc, error = f.Open()
  511. if error != nil {
  512. return nil, error
  513. }
  514. sst = new(xlsxSST)
  515. decoder = xml.NewDecoder(rc)
  516. error = decoder.Decode(sst)
  517. if error != nil {
  518. return nil, error
  519. }
  520. reftable = MakeSharedStringRefTable(sst)
  521. return reftable, nil
  522. }
  523. // readStylesFromZipFile() is an internal helper function to
  524. // extract a style table from the style.xml file within
  525. // the XLSX zip file.
  526. func readStylesFromZipFile(f *zip.File) (*xlsxStyleSheet, error) {
  527. var style *xlsxStyleSheet
  528. var error error
  529. var rc io.ReadCloser
  530. var decoder *xml.Decoder
  531. rc, error = f.Open()
  532. if error != nil {
  533. return nil, error
  534. }
  535. style = newXlsxStyleSheet()
  536. decoder = xml.NewDecoder(rc)
  537. error = decoder.Decode(style)
  538. if error != nil {
  539. return nil, error
  540. }
  541. buildNumFmtRefTable(style)
  542. return style, nil
  543. }
  544. func buildNumFmtRefTable(style *xlsxStyleSheet) {
  545. for _, numFmt := range style.NumFmts.NumFmt {
  546. // We do this for the side effect of populating the NumFmtRefTable.
  547. style.addNumFmt(numFmt)
  548. }
  549. }
  550. type WorkBookRels map[string]string
  551. func (w *WorkBookRels) MakeXLSXWorkbookRels() xlsxWorkbookRels {
  552. relCount := len(*w)
  553. xWorkbookRels := xlsxWorkbookRels{}
  554. xWorkbookRels.Relationships = make([]xlsxWorkbookRelation, relCount+3)
  555. for k, v := range *w {
  556. index, err := strconv.Atoi(k[3:])
  557. if err != nil {
  558. panic(err.Error())
  559. }
  560. xWorkbookRels.Relationships[index-1] = xlsxWorkbookRelation{
  561. Id: k,
  562. Target: v,
  563. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"}
  564. }
  565. relCount++
  566. sheetId := fmt.Sprintf("rId%d", relCount)
  567. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  568. Id: sheetId,
  569. Target: "sharedStrings.xml",
  570. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"}
  571. relCount++
  572. sheetId = fmt.Sprintf("rId%d", relCount)
  573. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  574. Id: sheetId,
  575. Target: "theme/theme1.xml",
  576. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"}
  577. relCount++
  578. sheetId = fmt.Sprintf("rId%d", relCount)
  579. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  580. Id: sheetId,
  581. Target: "styles.xml",
  582. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"}
  583. return xWorkbookRels
  584. }
  585. // readWorkbookRelationsFromZipFile is an internal helper function to
  586. // extract a map of relationship ID strings to the name of the
  587. // worksheet.xml file they refer to. The resulting map can be used to
  588. // reliably derefence the worksheets in the XLSX file.
  589. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (WorkBookRels, error) {
  590. var sheetXMLMap WorkBookRels
  591. var wbRelationships *xlsxWorkbookRels
  592. var rc io.ReadCloser
  593. var decoder *xml.Decoder
  594. var err error
  595. rc, err = workbookRels.Open()
  596. if err != nil {
  597. return nil, err
  598. }
  599. decoder = xml.NewDecoder(rc)
  600. wbRelationships = new(xlsxWorkbookRels)
  601. err = decoder.Decode(wbRelationships)
  602. if err != nil {
  603. return nil, err
  604. }
  605. sheetXMLMap = make(WorkBookRels)
  606. for _, rel := range wbRelationships.Relationships {
  607. if strings.HasSuffix(rel.Target, ".xml") && rel.Type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" {
  608. _, filename := path.Split(rel.Target)
  609. sheetXMLMap[rel.Id] = strings.Replace(filename, ".xml", "", 1)
  610. }
  611. }
  612. return sheetXMLMap, nil
  613. }
  614. // ReadZip() takes a pointer to a zip.ReadCloser and returns a
  615. // xlsx.File struct populated with its contents. In most cases
  616. // ReadZip is not used directly, but is called internally by OpenFile.
  617. func ReadZip(f *zip.ReadCloser) (*File, error) {
  618. defer f.Close()
  619. return ReadZipReader(&f.Reader)
  620. }
  621. // ReadZipReader() can be used to read an XLSX in memory without
  622. // touching the filesystem.
  623. func ReadZipReader(r *zip.Reader) (*File, error) {
  624. var err error
  625. var file *File
  626. var reftable *RefTable
  627. var sharedStrings *zip.File
  628. var sheetXMLMap map[string]string
  629. var sheetsByName map[string]*Sheet
  630. var sheets []*Sheet
  631. var style *xlsxStyleSheet
  632. var styles *zip.File
  633. var v *zip.File
  634. var workbook *zip.File
  635. var workbookRels *zip.File
  636. var worksheets map[string]*zip.File
  637. file = NewFile()
  638. // file.numFmtRefTable = make(map[int]xlsxNumFmt, 1)
  639. worksheets = make(map[string]*zip.File, len(r.File))
  640. for _, v = range r.File {
  641. switch v.Name {
  642. case "xl/sharedStrings.xml":
  643. sharedStrings = v
  644. case "xl/workbook.xml":
  645. workbook = v
  646. case "xl/_rels/workbook.xml.rels":
  647. workbookRels = v
  648. case "xl/styles.xml":
  649. styles = v
  650. default:
  651. if len(v.Name) > 14 {
  652. if v.Name[0:13] == "xl/worksheets" {
  653. worksheets[v.Name[14:len(v.Name)-4]] = v
  654. }
  655. }
  656. }
  657. }
  658. sheetXMLMap, err = readWorkbookRelationsFromZipFile(workbookRels)
  659. if err != nil {
  660. return nil, err
  661. }
  662. file.worksheets = worksheets
  663. reftable, err = readSharedStringsFromZipFile(sharedStrings)
  664. if err != nil {
  665. return nil, err
  666. }
  667. file.referenceTable = reftable
  668. if styles != nil {
  669. style, err = readStylesFromZipFile(styles)
  670. if err != nil {
  671. return nil, err
  672. }
  673. file.styles = style
  674. }
  675. sheetsByName, sheets, err = readSheetsFromZipFile(workbook, file, sheetXMLMap)
  676. if err != nil {
  677. return nil, err
  678. }
  679. if sheets == nil {
  680. readerErr := new(XLSXReaderError)
  681. readerErr.Err = "No sheets found in XLSX File"
  682. return nil, readerErr
  683. }
  684. file.Sheet = sheetsByName
  685. file.Sheets = sheets
  686. return file, nil
  687. }