stream_file_builder.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. // Authors: Ryan Hollis (ryanh@)
  2. // The purpose of StreamFileBuilder and StreamFile is to allow streamed writing of XLSX files.
  3. // Directions:
  4. // 1. Create a StreamFileBuilder with NewStreamFileBuilder() or NewStreamFileBuilderForPath().
  5. // 2. Add the sheets and their first row of data by calling AddSheet().
  6. // 3. Call Build() to get a StreamFile. Once built, all functions on the builder will return an error.
  7. // 4. Write to the StreamFile with Write(). Writes begin on the first sheet. New rows are always written and flushed
  8. // to the io. All rows written to the same sheet must have the same number of cells as the header provided when the sheet
  9. // was created or an error will be returned.
  10. // 5. Call NextSheet() to proceed to the next sheet. Once NextSheet() is called, the previous sheet can not be edited.
  11. // 6. Call Close() to finish.
  12. // Directions for using custom styles and different data types:
  13. // 1. Create a StreamFileBuilder with NewStreamFileBuilder() or NewStreamFileBuilderForPath().
  14. // 2. Use MakeStyle() to create the styles you want yo use in your document. Keep a list of these styles.
  15. // 3. Add all the styles you created by using AddStreamStyle() or AddStreamStyleList().
  16. // 4. Add the sheets and their column styles of data by calling AddSheetS().
  17. // 5. Call Build() to get a StreamFile. Once built, all functions on the builder will return an error.
  18. // 6. Write to the StreamFile with WriteS(). Writes begin on the first sheet. New rows are always written and flushed
  19. // to the io. All rows written to the same sheet must have the same number of cells as the number of column styles
  20. // provided when adding the sheet with AddSheetS() or an error will be returned.
  21. // 5. Call NextSheet() to proceed to the next sheet. Once NextSheet() is called, the previous sheet can not be edited.
  22. // 6. Call Close() to finish.
  23. // Future work suggestions:
  24. // The current default style uses fonts that are not on Macs by default so opening the XLSX files in Numbers causes a
  25. // pop up that says there are missing fonts. The font could be changed to something that is usually found on Mac and PC.
  26. // Extend support for Formulas and Shared Strings.
  27. package xlsx
  28. import (
  29. "archive/zip"
  30. "errors"
  31. "fmt"
  32. "io"
  33. "os"
  34. "strconv"
  35. "strings"
  36. )
  37. type StreamFileBuilder struct {
  38. built bool
  39. firstSheetAdded bool
  40. customStylesAdded bool
  41. xlsxFile *File
  42. zipWriter *zip.Writer
  43. cellTypeToStyleIds map[CellType]int
  44. maxStyleId int
  45. styleIds [][]int
  46. customStreamStyles map[StreamStyle]struct{}
  47. styleIdMap map[StreamStyle]int
  48. defaultColumnCellMetadataAdded bool
  49. }
  50. const (
  51. sheetFilePathPrefix = "xl/worksheets/sheet"
  52. sheetFilePathSuffix = ".xml"
  53. endSheetDataTag = "</sheetData>"
  54. dimensionTag = `<dimension ref="%s"></dimension>`
  55. // This is the index of the max style that this library will insert into XLSX sheets by default.
  56. // This allows us to predict what the style id of styles that we add will be.
  57. // TestXlsxStyleBehavior tests that this behavior continues to be what we expect.
  58. initMaxStyleId = 1
  59. )
  60. var BuiltStreamFileBuilderError = errors.New("StreamFileBuilder has already been built, functions may no longer be used")
  61. // NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
  62. func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder {
  63. return &StreamFileBuilder{
  64. zipWriter: zip.NewWriter(writer),
  65. xlsxFile: NewFile(),
  66. cellTypeToStyleIds: make(map[CellType]int),
  67. maxStyleId: initMaxStyleId,
  68. customStreamStyles: make(map[StreamStyle]struct{}),
  69. styleIdMap: make(map[StreamStyle]int),
  70. }
  71. }
  72. // NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it.
  73. // The file will be created if it does not exist, or truncated if it does.
  74. func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) {
  75. file, err := os.Create(path)
  76. if err != nil {
  77. return nil, err
  78. }
  79. return NewStreamFileBuilder(file), nil
  80. }
  81. // AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all
  82. // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an
  83. // error will be thrown.
  84. func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error {
  85. if sb.built {
  86. return BuiltStreamFileBuilderError
  87. }
  88. if len(cellTypes) > len(headers) {
  89. return errors.New("cellTypes is longer than headers")
  90. }
  91. sheet, err := sb.xlsxFile.AddSheet(name)
  92. if err != nil {
  93. // Set built on error so that all subsequent calls to the builder will also fail.
  94. sb.built = true
  95. return err
  96. }
  97. sb.styleIds = append(sb.styleIds, []int{})
  98. row := sheet.AddRow()
  99. if count := row.WriteSlice(&headers, -1); count != len(headers) {
  100. // Set built on error so that all subsequent calls to the builder will also fail.
  101. sb.built = true
  102. return errors.New("failed to write headers")
  103. }
  104. for i, cellType := range cellTypes {
  105. var cellStyleIndex int
  106. var ok bool
  107. if cellType != nil {
  108. // The cell type is one of the attributes of a Style.
  109. // Since it is the only attribute of Style that we use, we can assume that cell types
  110. // map one to one with Styles and their Style ID.
  111. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is
  112. // used, the pre-existing style will also be used.
  113. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType]
  114. if !ok {
  115. sb.maxStyleId++
  116. cellStyleIndex = sb.maxStyleId
  117. sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId
  118. }
  119. sheet.Cols[i].SetType(*cellType)
  120. }
  121. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  122. }
  123. return nil
  124. }
  125. func (sb *StreamFileBuilder) AddSheetWithDefaultColumnMetadata(name string, headers []string, columnsDefaultCellMetadata []*CellMetadata) error {
  126. if sb.built {
  127. return BuiltStreamFileBuilderError
  128. }
  129. if len(columnsDefaultCellMetadata) > len(headers) {
  130. return errors.New("columnsDefaultCellMetadata is longer than headers")
  131. }
  132. sheet, err := sb.xlsxFile.AddSheet(name)
  133. if err != nil {
  134. // Set built on error so that all subsequent calls to the builder will also fail.
  135. sb.built = true
  136. return err
  137. }
  138. sb.styleIds = append(sb.styleIds, []int{})
  139. row := sheet.AddRow()
  140. if count := row.WriteSlice(&headers, -1); count != len(headers) {
  141. // Set built on error so that all subsequent calls to the builder will also fail.
  142. sb.built = true
  143. return errors.New("failed to write headers")
  144. }
  145. for i, cellMetadata := range columnsDefaultCellMetadata {
  146. var cellStyleIndex int
  147. var ok bool
  148. if cellMetadata != nil {
  149. // Exact same logic as `AddSheet` to ensure compatibility as much as possible
  150. // with the `AddSheet` + `StreamFile.Write` code path
  151. cellStyleIndex, ok = sb.cellTypeToStyleIds[cellMetadata.cellType]
  152. if !ok {
  153. sb.maxStyleId++
  154. cellStyleIndex = sb.maxStyleId
  155. sb.cellTypeToStyleIds[cellMetadata.cellType] = sb.maxStyleId
  156. }
  157. // Add streamStyle and set default cell metadata on col
  158. sb.customStreamStyles[cellMetadata.streamStyle] = struct{}{}
  159. sheet.Cols[i].SetCellMetadata(*cellMetadata)
  160. }
  161. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  162. }
  163. // Add fall back streamStyle
  164. sb.customStreamStyles[StreamStyleDefaultString] = struct{}{}
  165. // Toggle to true to ensure `styleIdMap` is constructed from `customStreamStyles` on `Build`
  166. sb.customStylesAdded = true
  167. // Hack to ensure the `dimension` tag on each `worksheet` xml is stripped. Otherwise only the first
  168. // row of each worksheet will be read back rather than all rows
  169. sb.defaultColumnCellMetadataAdded = true
  170. return nil
  171. }
  172. // AddSheetS will add a sheet with the given name and column styles. The number of column styles given
  173. // is the number of columns that will be created, and thus the number of cells each row has to have.
  174. // columnStyles[0] becomes the style of the first column, columnStyles[1] the style of the second column etc.
  175. // All the styles in columnStyles have to have been added or an error will be returned.
  176. // Sheet names must be unique, or an error will be returned.
  177. func (sb *StreamFileBuilder) AddSheetS(name string, columnStyles []StreamStyle) error {
  178. if sb.built {
  179. return BuiltStreamFileBuilderError
  180. }
  181. sheet, err := sb.xlsxFile.AddSheet(name)
  182. if err != nil {
  183. // Set built on error so that all subsequent calls to the builder will also fail.
  184. sb.built = true
  185. return err
  186. }
  187. // To make sure no new styles can be added after adding a sheet
  188. sb.firstSheetAdded = true
  189. // Check if all styles that will be used for columns have been created
  190. for _, colStyle := range columnStyles {
  191. if _, ok := sb.customStreamStyles[colStyle]; !ok {
  192. return errors.New("trying to make use of a style that has not been added")
  193. }
  194. }
  195. // Is needed for stream file to work but is not needed for streaming with styles
  196. sb.styleIds = append(sb.styleIds, []int{})
  197. sheet.maybeAddCol(len(columnStyles))
  198. // Set default column styles based on the cel styles in the first row
  199. // Set the default column width to 11. This makes enough places for the
  200. // default date style cells to display the dates correctly
  201. for i, colStyle := range columnStyles {
  202. sheet.Cols[i].SetStreamStyle(colStyle)
  203. sheet.Cols[i].Width = 11
  204. }
  205. return nil
  206. }
  207. // AddValidation will add a validation to a specific column.
  208. func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation) {
  209. sheet := sb.xlsxFile.Sheets[sheetIndex]
  210. column := sheet.Col(colIndex)
  211. column.SetDataValidationWithStart(validation, rowStartIndex)
  212. }
  213. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  214. // that can be used to write the rows to the sheets.
  215. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  216. if sb.built {
  217. return nil, BuiltStreamFileBuilderError
  218. }
  219. sb.built = true
  220. parts, err := sb.xlsxFile.MarshallParts()
  221. if err != nil {
  222. return nil, err
  223. }
  224. if sb.customStylesAdded {
  225. parts["xl/styles.xml"], err = sb.marshalStyles()
  226. if err != nil {
  227. return nil, err
  228. }
  229. }
  230. es := &StreamFile{
  231. zipWriter: sb.zipWriter,
  232. xlsxFile: sb.xlsxFile,
  233. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  234. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  235. styleIds: sb.styleIds,
  236. styleIdMap: sb.styleIdMap,
  237. }
  238. for path, data := range parts {
  239. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  240. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  241. if strings.HasPrefix(path, sheetFilePathPrefix) {
  242. // sb.defaultColumnCellMetadataAdded is a hack because neither the `AddSheet` nor `AddSheetS` codepaths
  243. // actually encode a valid worksheet dimension. `AddSheet` encodes an empty one: "" and `AddSheetS` encodes
  244. // an effectively empty one: "A1". `AddSheetWithDefaultColumnMetadata` uses logic from both paths which results
  245. // in an effectively invalid dimension being encoded which, upon read, results in only reading in the header of
  246. // a given worksheet and non of the rows that follow
  247. if err := sb.processEmptySheetXML(es, path, data, !sb.customStylesAdded || sb.defaultColumnCellMetadataAdded); err != nil {
  248. return nil, err
  249. }
  250. continue
  251. }
  252. metadataFile, err := sb.zipWriter.Create(path)
  253. if err != nil {
  254. return nil, err
  255. }
  256. _, err = metadataFile.Write([]byte(data))
  257. if err != nil {
  258. return nil, err
  259. }
  260. }
  261. if err := es.NextSheet(); err != nil {
  262. return nil, err
  263. }
  264. return es, nil
  265. }
  266. func (sb *StreamFileBuilder) marshalStyles() (string, error) {
  267. for streamStyle, _ := range sb.customStreamStyles {
  268. XfId := handleStyleForXLSX(streamStyle.style, streamStyle.xNumFmtId, sb.xlsxFile.styles)
  269. sb.styleIdMap[streamStyle] = XfId
  270. }
  271. styleSheetXMLString, err := sb.xlsxFile.styles.Marshal()
  272. if err != nil {
  273. return "", err
  274. }
  275. return styleSheetXMLString, nil
  276. }
  277. // AddStreamStyle adds a new style to the style sheet.
  278. // Only Styles that have been added through this function will be usable.
  279. // This function cannot be used after AddSheetS or Build has been called, and if it is
  280. // called after AddSheetS or Buildit will return an error.
  281. func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error {
  282. if sb.firstSheetAdded {
  283. return errors.New("at least one sheet has been added, cannot add new styles anymore")
  284. }
  285. if sb.built {
  286. return errors.New("file has been build, cannot add new styles anymore")
  287. }
  288. sb.customStreamStyles[streamStyle] = struct{}{}
  289. sb.customStylesAdded = true
  290. return nil
  291. }
  292. // AddStreamStyleList adds a list of new styles to the style sheet.
  293. // Only Styles that have been added through either this function or AddStreamStyle will be usable.
  294. // This function cannot be used after AddSheetS and Build has been called, and if it is
  295. // called after AddSheetS and Build it will return an error.
  296. func (sb *StreamFileBuilder) AddStreamStyleList(streamStyles []StreamStyle) error {
  297. for _, streamStyle := range streamStyles {
  298. err := sb.AddStreamStyle(streamStyle)
  299. if err != nil {
  300. return err
  301. }
  302. }
  303. return nil
  304. }
  305. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  306. // XML file so that these can be written at the right time.
  307. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string, removeDimensionTagFlag bool) error {
  308. // Get the sheet index from the path
  309. sheetIndex, err := getSheetIndex(sf, path)
  310. if err != nil {
  311. return err
  312. }
  313. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  314. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  315. if removeDimensionTagFlag {
  316. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  317. if err != nil {
  318. return err
  319. }
  320. }
  321. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  322. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  323. if err != nil {
  324. return err
  325. }
  326. sf.sheetXmlPrefix[sheetIndex] = prefix
  327. sf.sheetXmlSuffix[sheetIndex] = suffix
  328. return nil
  329. }
  330. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  331. // The files that store the data for each sheet must have the format:
  332. // xl/worksheets/sheet123.xml
  333. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  334. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  335. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  336. sheetXLSXIndex, err := strconv.Atoi(indexString)
  337. if err != nil {
  338. return -1, errors.New("unexpected sheet file name from xlsx package")
  339. }
  340. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  341. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  342. return -1, errors.New("unexpected sheet index")
  343. }
  344. sheetArrayIndex := sheetXLSXIndex - 1
  345. return sheetArrayIndex, nil
  346. }
  347. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  348. // data is the XML data for the sheet
  349. // sheet is the Sheet struct that the XML was created from.
  350. // Can return an error if the XML's dimension tag does not match what is expected based on the provided Sheet
  351. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  352. x := len(sheet.Cols) - 1
  353. y := len(sheet.Rows) - 1
  354. if x < 0 {
  355. x = 0
  356. }
  357. if y < 0 {
  358. y = 0
  359. }
  360. var dimensionRef string
  361. if x == 0 && y == 0 {
  362. dimensionRef = "A1"
  363. } else {
  364. endCoordinate := GetCellIDStringFromCoords(x, y)
  365. dimensionRef = "A1:" + endCoordinate
  366. }
  367. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  368. if len(dataParts) != 2 {
  369. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  370. }
  371. return dataParts[0] + dataParts[1], nil
  372. }
  373. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  374. // more spreadsheet rows can be inserted in between.
  375. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  376. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  377. sheetParts := strings.Split(data, endSheetDataTag)
  378. if len(sheetParts) != 2 {
  379. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  380. }
  381. return sheetParts[0], sheetParts[1], nil
  382. }