stream_file_builder.go 16 KB

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