lib.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  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. x, _, error := getCoordsFromCellIDString(rawcell.R)
  263. if error != nil {
  264. panic(fmt.Sprintf("Invalid Cell Coord, %s\n", rawcell.R))
  265. }
  266. if x > upper {
  267. upper = x
  268. }
  269. }
  270. upper++
  271. row.Cells = make([]*Cell, upper)
  272. for i := 0; i < upper; i++ {
  273. cell = new(Cell)
  274. cell.Value = ""
  275. row.Cells[i] = cell
  276. }
  277. return row
  278. }
  279. // fillCellData attempts to extract a valid value, usable in
  280. // CSV form from the raw cell value. Note - this is not actually
  281. // general enough - we should support retaining tabs and newlines.
  282. func fillCellData(rawcell xlsxC, reftable *RefTable, cell *Cell) {
  283. var data string = rawcell.V
  284. if len(data) > 0 {
  285. vval := strings.Trim(data, " \t\n\r")
  286. switch rawcell.T {
  287. case "s": // Shared String
  288. ref, error := strconv.Atoi(vval)
  289. if error != nil {
  290. panic(error)
  291. }
  292. cell.Value = reftable.ResolveSharedString(ref)
  293. cell.cellType = CellTypeString
  294. case "b": // Boolean
  295. cell.Value = vval
  296. cell.cellType = CellTypeBool
  297. case "e": // Error
  298. cell.Value = vval
  299. cell.formula = strings.Trim(rawcell.F, " \t\n\r")
  300. cell.cellType = CellTypeError
  301. default:
  302. if len(rawcell.F) == 0 {
  303. // Numeric
  304. cell.Value = vval
  305. cell.cellType = CellTypeNumeric
  306. } else {
  307. // Formula
  308. cell.Value = vval
  309. cell.formula = strings.Trim(rawcell.F, " \t\n\r")
  310. cell.cellType = CellTypeFormula
  311. }
  312. }
  313. }
  314. }
  315. // readRowsFromSheet is an internal helper function that extracts the
  316. // rows from a XSLXWorksheet, populates them with Cells and resolves
  317. // the value references from the reference table and stores them in
  318. // the rows and columns.
  319. func readRowsFromSheet(Worksheet *xlsxWorksheet, file *File) ([]*Row, []*Col, int, int) {
  320. var rows []*Row
  321. var cols []*Col
  322. var row *Row
  323. var minCol, maxCol, minRow, maxRow, colCount, rowCount int
  324. var reftable *RefTable
  325. var err error
  326. var insertRowIndex, insertColIndex int
  327. if len(Worksheet.SheetData.Row) == 0 {
  328. return nil, nil, 0, 0
  329. }
  330. reftable = file.referenceTable
  331. if len(Worksheet.Dimension.Ref) > 0 {
  332. minCol, minRow, maxCol, maxRow, err = getMaxMinFromDimensionRef(Worksheet.Dimension.Ref)
  333. } else {
  334. minCol, minRow, maxCol, maxRow, err = calculateMaxMinFromWorksheet(Worksheet)
  335. }
  336. if err != nil {
  337. panic(err.Error())
  338. }
  339. rowCount = (maxRow - minRow) + 1
  340. colCount = (maxCol - minCol) + 1
  341. rows = make([]*Row, rowCount)
  342. cols = make([]*Col, colCount)
  343. insertRowIndex = minRow
  344. for i := range cols {
  345. cols[i] = &Col{
  346. Hidden: false,
  347. }
  348. }
  349. // Columns can apply to a range, for convenience we expand the
  350. // ranges out into individual column definitions.
  351. for _, rawcol := range Worksheet.Cols.Col {
  352. // Note, below, that sometimes column definitions can
  353. // exist outside the defined dimensions of the
  354. // spreadsheet - we deliberately exclude these
  355. // columns.
  356. for i := rawcol.Min; i <= rawcol.Max && i <= colCount; i++ {
  357. cols[i-1] = &Col{
  358. Min: rawcol.Min,
  359. Max: rawcol.Max,
  360. Hidden: rawcol.Hidden}
  361. }
  362. }
  363. for rowIndex := 0; rowIndex < len(Worksheet.SheetData.Row); rowIndex++ {
  364. rawrow := Worksheet.SheetData.Row[rowIndex]
  365. // Some spreadsheets will omit blank rows from the
  366. // stored data
  367. for rawrow.R > (insertRowIndex + 1) {
  368. // Put an empty Row into the array
  369. rows[insertRowIndex-minRow] = new(Row)
  370. insertRowIndex++
  371. }
  372. // range is not empty and only one range exist
  373. if len(rawrow.Spans) != 0 && strings.Count(rawrow.Spans, ":") == 1 {
  374. row = makeRowFromSpan(rawrow.Spans)
  375. } else {
  376. row = makeRowFromRaw(rawrow)
  377. }
  378. row.Hidden = rawrow.Hidden
  379. insertColIndex = minCol
  380. for _, rawcell := range rawrow.C {
  381. x, _, _ := getCoordsFromCellIDString(rawcell.R)
  382. // Some spreadsheets will omit blank cells
  383. // from the data.
  384. for x > insertColIndex {
  385. // Put an empty Cell into the array
  386. row.Cells[insertColIndex-minCol] = new(Cell)
  387. insertColIndex++
  388. }
  389. cellX := insertColIndex - minCol
  390. cell := row.Cells[cellX]
  391. fillCellData(rawcell, reftable, cell)
  392. if file.styles != nil {
  393. cell.style = file.styles.getStyle(rawcell.S)
  394. cell.numFmt = file.styles.getNumberFormat(rawcell.S)
  395. }
  396. cell.date1904 = file.Date1904
  397. cell.Hidden = rawrow.Hidden || (len(cols) > cellX && cell.Hidden)
  398. insertColIndex++
  399. }
  400. if len(rows) > insertRowIndex-minRow {
  401. rows[insertRowIndex-minRow] = row
  402. }
  403. insertRowIndex++
  404. }
  405. return rows, cols, colCount, rowCount
  406. }
  407. type indexedSheet struct {
  408. Index int
  409. Sheet *Sheet
  410. Error error
  411. }
  412. // readSheetFromFile is the logic of converting a xlsxSheet struct
  413. // into a Sheet struct. This work can be done in parallel and so
  414. // readSheetsFromZipFile will spawn an instance of this function per
  415. // sheet and get the results back on the provided channel.
  416. func readSheetFromFile(sc chan *indexedSheet, index int, rsheet xlsxSheet, fi *File, sheetXMLMap map[string]string) {
  417. result := &indexedSheet{Index: index, Sheet: nil, Error: nil}
  418. worksheet, error := getWorksheetFromSheet(rsheet, fi.worksheets, sheetXMLMap)
  419. if error != nil {
  420. result.Error = error
  421. sc <- result
  422. return
  423. }
  424. sheet := new(Sheet)
  425. sheet.Rows, sheet.Cols, sheet.MaxCol, sheet.MaxRow = readRowsFromSheet(worksheet, fi)
  426. sheet.Hidden = rsheet.State == sheetStateHidden || rsheet.State == sheetStateVeryHidden
  427. result.Sheet = sheet
  428. sc <- result
  429. }
  430. // readSheetsFromZipFile is an internal helper function that loops
  431. // over the Worksheets defined in the XSLXWorkbook and loads them into
  432. // Sheet objects stored in the Sheets slice of a xlsx.File struct.
  433. func readSheetsFromZipFile(f *zip.File, file *File, sheetXMLMap map[string]string) (map[string]*Sheet, []*Sheet, error) {
  434. var workbook *xlsxWorkbook
  435. var error error
  436. var rc io.ReadCloser
  437. var decoder *xml.Decoder
  438. var sheetCount int
  439. workbook = new(xlsxWorkbook)
  440. rc, error = f.Open()
  441. if error != nil {
  442. return nil, nil, error
  443. }
  444. decoder = xml.NewDecoder(rc)
  445. error = decoder.Decode(workbook)
  446. if error != nil {
  447. return nil, nil, error
  448. }
  449. file.Date1904 = workbook.WorkbookPr.Date1904
  450. sheetCount = len(workbook.Sheets.Sheet)
  451. sheetsByName := make(map[string]*Sheet, sheetCount)
  452. sheets := make([]*Sheet, sheetCount)
  453. sheetChan := make(chan *indexedSheet, sheetCount)
  454. for i, rawsheet := range workbook.Sheets.Sheet {
  455. go readSheetFromFile(sheetChan, i, rawsheet, file, sheetXMLMap)
  456. }
  457. for j := 0; j < sheetCount; j++ {
  458. sheet := <-sheetChan
  459. if sheet.Error != nil {
  460. return nil, nil, sheet.Error
  461. }
  462. sheetName := workbook.Sheets.Sheet[sheet.Index].Name
  463. sheetsByName[sheetName] = sheet.Sheet
  464. sheet.Sheet.Name = sheetName
  465. sheets[sheet.Index] = sheet.Sheet
  466. }
  467. return sheetsByName, sheets, nil
  468. }
  469. // readSharedStringsFromZipFile() is an internal helper function to
  470. // extract a reference table from the sharedStrings.xml file within
  471. // the XLSX zip file.
  472. func readSharedStringsFromZipFile(f *zip.File) (*RefTable, error) {
  473. var sst *xlsxSST
  474. var error error
  475. var rc io.ReadCloser
  476. var decoder *xml.Decoder
  477. var reftable *RefTable
  478. // In a file with no strings it's possible that
  479. // sharedStrings.xml doesn't exist. In this case the value
  480. // passed as f will be nil.
  481. if f == nil {
  482. return nil, nil
  483. }
  484. rc, error = f.Open()
  485. if error != nil {
  486. return nil, error
  487. }
  488. sst = new(xlsxSST)
  489. decoder = xml.NewDecoder(rc)
  490. error = decoder.Decode(sst)
  491. if error != nil {
  492. return nil, error
  493. }
  494. reftable = MakeSharedStringRefTable(sst)
  495. return reftable, nil
  496. }
  497. // readStylesFromZipFile() is an internal helper function to
  498. // extract a style table from the style.xml file within
  499. // the XLSX zip file.
  500. func readStylesFromZipFile(f *zip.File) (*xlsxStyleSheet, error) {
  501. var style *xlsxStyleSheet
  502. var error error
  503. var rc io.ReadCloser
  504. var decoder *xml.Decoder
  505. rc, error = f.Open()
  506. if error != nil {
  507. return nil, error
  508. }
  509. style = new(xlsxStyleSheet)
  510. decoder = xml.NewDecoder(rc)
  511. error = decoder.Decode(style)
  512. if error != nil {
  513. return nil, error
  514. }
  515. buildNumFmtRefTable(style)
  516. return style, nil
  517. }
  518. func buildNumFmtRefTable(style *xlsxStyleSheet) {
  519. for _, numFmt := range style.NumFmts.NumFmt {
  520. // We do this for the side effect of populating the NumFmtRefTable.
  521. style.addNumFmt(numFmt)
  522. }
  523. }
  524. type WorkBookRels map[string]string
  525. func (w *WorkBookRels) MakeXLSXWorkbookRels() xlsxWorkbookRels {
  526. relCount := len(*w)
  527. xWorkbookRels := xlsxWorkbookRels{}
  528. xWorkbookRels.Relationships = make([]xlsxWorkbookRelation, relCount+3)
  529. for k, v := range *w {
  530. index, err := strconv.Atoi(k[3:])
  531. if err != nil {
  532. panic(err.Error())
  533. }
  534. xWorkbookRels.Relationships[index-1] = xlsxWorkbookRelation{
  535. Id: k,
  536. Target: v,
  537. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet"}
  538. }
  539. relCount++
  540. sheetId := fmt.Sprintf("rId%d", relCount)
  541. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  542. Id: sheetId,
  543. Target: "sharedStrings.xml",
  544. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/sharedStrings"}
  545. relCount++
  546. sheetId = fmt.Sprintf("rId%d", relCount)
  547. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  548. Id: sheetId,
  549. Target: "theme/theme1.xml",
  550. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme"}
  551. relCount++
  552. sheetId = fmt.Sprintf("rId%d", relCount)
  553. xWorkbookRels.Relationships[relCount-1] = xlsxWorkbookRelation{
  554. Id: sheetId,
  555. Target: "styles.xml",
  556. Type: "http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles"}
  557. return xWorkbookRels
  558. }
  559. // readWorkbookRelationsFromZipFile is an internal helper function to
  560. // extract a map of relationship ID strings to the name of the
  561. // worksheet.xml file they refer to. The resulting map can be used to
  562. // reliably derefence the worksheets in the XLSX file.
  563. func readWorkbookRelationsFromZipFile(workbookRels *zip.File) (WorkBookRels, error) {
  564. var sheetXMLMap WorkBookRels
  565. var wbRelationships *xlsxWorkbookRels
  566. var rc io.ReadCloser
  567. var decoder *xml.Decoder
  568. var err error
  569. rc, err = workbookRels.Open()
  570. if err != nil {
  571. return nil, err
  572. }
  573. decoder = xml.NewDecoder(rc)
  574. wbRelationships = new(xlsxWorkbookRels)
  575. err = decoder.Decode(wbRelationships)
  576. if err != nil {
  577. return nil, err
  578. }
  579. sheetXMLMap = make(WorkBookRels)
  580. for _, rel := range wbRelationships.Relationships {
  581. if strings.HasSuffix(rel.Target, ".xml") && rel.Type == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" {
  582. _, filename := path.Split(rel.Target)
  583. sheetXMLMap[rel.Id] = strings.Replace(filename, ".xml", "", 1)
  584. }
  585. }
  586. return sheetXMLMap, nil
  587. }
  588. // ReadZip() takes a pointer to a zip.ReadCloser and returns a
  589. // xlsx.File struct populated with its contents. In most cases
  590. // ReadZip is not used directly, but is called internally by OpenFile.
  591. func ReadZip(f *zip.ReadCloser) (*File, error) {
  592. defer f.Close()
  593. return ReadZipReader(&f.Reader)
  594. }
  595. // ReadZipReader() can be used to read an XLSX in memory without
  596. // touching the filesystem.
  597. func ReadZipReader(r *zip.Reader) (*File, error) {
  598. var err error
  599. var file *File
  600. var reftable *RefTable
  601. var sharedStrings *zip.File
  602. var sheetXMLMap map[string]string
  603. var sheetsByName map[string]*Sheet
  604. var sheets []*Sheet
  605. var style *xlsxStyleSheet
  606. var styles *zip.File
  607. var v *zip.File
  608. var workbook *zip.File
  609. var workbookRels *zip.File
  610. var worksheets map[string]*zip.File
  611. file = NewFile()
  612. // file.numFmtRefTable = make(map[int]xlsxNumFmt, 1)
  613. worksheets = make(map[string]*zip.File, len(r.File))
  614. for _, v = range r.File {
  615. switch v.Name {
  616. case "xl/sharedStrings.xml":
  617. sharedStrings = v
  618. case "xl/workbook.xml":
  619. workbook = v
  620. case "xl/_rels/workbook.xml.rels":
  621. workbookRels = v
  622. case "xl/styles.xml":
  623. styles = v
  624. default:
  625. if len(v.Name) > 14 {
  626. if v.Name[0:13] == "xl/worksheets" {
  627. worksheets[v.Name[14:len(v.Name)-4]] = v
  628. }
  629. }
  630. }
  631. }
  632. sheetXMLMap, err = readWorkbookRelationsFromZipFile(workbookRels)
  633. if err != nil {
  634. return nil, err
  635. }
  636. file.worksheets = worksheets
  637. reftable, err = readSharedStringsFromZipFile(sharedStrings)
  638. if err != nil {
  639. return nil, err
  640. }
  641. file.referenceTable = reftable
  642. if styles != nil {
  643. style, err = readStylesFromZipFile(styles)
  644. if err != nil {
  645. return nil, err
  646. }
  647. file.styles = style
  648. }
  649. sheetsByName, sheets, err = readSheetsFromZipFile(workbook, file, sheetXMLMap)
  650. if err != nil {
  651. return nil, err
  652. }
  653. if sheets == nil {
  654. readerErr := new(XLSXReaderError)
  655. readerErr.Err = "No sheets found in XLSX File"
  656. return nil, readerErr
  657. }
  658. file.Sheet = sheetsByName
  659. file.Sheets = sheets
  660. return file, nil
  661. }