stream_file_builder.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. }
  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.Cols[i].SetType(*cellType)
  119. }
  120. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  121. }
  122. return nil
  123. }
  124. // AddSheetS will add a sheet with the given name and column styles. The number of column styles given
  125. // is the number of columns that will be created, and thus the number of cells each row has to have.
  126. // columnStyles[0] becomes the style of the first column, columnStyles[1] the style of the second column etc.
  127. // All the styles in columnStyles have to have been added or an error will be returned.
  128. // Sheet names must be unique, or an error will be returned.
  129. func (sb *StreamFileBuilder) AddSheetS(name string, columnStyles []StreamStyle) error {
  130. if sb.built {
  131. return BuiltStreamFileBuilderError
  132. }
  133. sheet, err := sb.xlsxFile.AddSheet(name)
  134. if err != nil {
  135. // Set built on error so that all subsequent calls to the builder will also fail.
  136. sb.built = true
  137. return err
  138. }
  139. // To make sure no new styles can be added after adding a sheet
  140. sb.firstSheetAdded = true
  141. // Check if all styles that will be used for columns have been created
  142. for _, colStyle := range columnStyles {
  143. if _, ok := sb.customStreamStyles[colStyle]; !ok {
  144. return errors.New("trying to make use of a style that has not been added")
  145. }
  146. }
  147. // Is needed for stream file to work but is not needed for streaming with styles
  148. sb.styleIds = append(sb.styleIds, []int{})
  149. sheet.maybeAddCol(len(columnStyles))
  150. // Set default column styles based on the cel styles in the first row
  151. // Set the default column width to 11. This makes enough places for the
  152. // default date style cells to display the dates correctly
  153. for i, colStyle := range columnStyles {
  154. sheet.Cols[i].SetStreamStyle(colStyle)
  155. sheet.Cols[i].Width = 11
  156. }
  157. return nil
  158. }
  159. // AddValidation will add a validation to a specific column.
  160. func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation) {
  161. sheet := sb.xlsxFile.Sheets[sheetIndex]
  162. column := sheet.Col(colIndex)
  163. column.SetDataValidationWithStart(validation, rowStartIndex)
  164. }
  165. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  166. // that can be used to write the rows to the sheets.
  167. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  168. if sb.built {
  169. return nil, BuiltStreamFileBuilderError
  170. }
  171. sb.built = true
  172. parts, err := sb.xlsxFile.MarshallParts()
  173. if err != nil {
  174. return nil, err
  175. }
  176. if sb.customStylesAdded {
  177. parts["xl/styles.xml"], err = sb.marshalStyles()
  178. if err != nil {
  179. return nil, err
  180. }
  181. }
  182. es := &StreamFile{
  183. zipWriter: sb.zipWriter,
  184. xlsxFile: sb.xlsxFile,
  185. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  186. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  187. styleIds: sb.styleIds,
  188. styleIdMap: sb.styleIdMap,
  189. }
  190. for path, data := range parts {
  191. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  192. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  193. if strings.HasPrefix(path, sheetFilePathPrefix) {
  194. if err := sb.processEmptySheetXML(es, path, data, !sb.customStylesAdded); err != nil {
  195. return nil, err
  196. }
  197. continue
  198. }
  199. metadataFile, err := sb.zipWriter.Create(path)
  200. if err != nil {
  201. return nil, err
  202. }
  203. _, err = metadataFile.Write([]byte(data))
  204. if err != nil {
  205. return nil, err
  206. }
  207. }
  208. if err := es.NextSheet(); err != nil {
  209. return nil, err
  210. }
  211. return es, nil
  212. }
  213. func (sb *StreamFileBuilder) marshalStyles() (string, error) {
  214. for streamStyle, _ := range sb.customStreamStyles {
  215. XfId := handleStyleForXLSX(streamStyle.style, streamStyle.xNumFmtId, sb.xlsxFile.styles)
  216. sb.styleIdMap[streamStyle] = XfId
  217. }
  218. styleSheetXMLString, err := sb.xlsxFile.styles.Marshal()
  219. if err != nil {
  220. return "", err
  221. }
  222. return styleSheetXMLString, nil
  223. }
  224. // AddStreamStyle adds a new style to the style sheet.
  225. // Only Styles that have been added through this function will be usable.
  226. // This function cannot be used after AddSheetS or Build has been called, and if it is
  227. // called after AddSheetS or Buildit will return an error.
  228. func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error {
  229. if sb.firstSheetAdded {
  230. return errors.New("at least one sheet has been added, cannot add new styles anymore")
  231. }
  232. if sb.built {
  233. return errors.New("file has been build, cannot add new styles anymore")
  234. }
  235. sb.customStreamStyles[streamStyle] = struct{}{}
  236. sb.customStylesAdded = true
  237. return nil
  238. }
  239. // AddStreamStyleList adds a list of new styles to the style sheet.
  240. // Only Styles that have been added through either this function or AddStreamStyle will be usable.
  241. // This function cannot be used after AddSheetS and Build has been called, and if it is
  242. // called after AddSheetS and Build it will return an error.
  243. func (sb *StreamFileBuilder) AddStreamStyleList(streamStyles []StreamStyle) error {
  244. for _, streamStyle := range streamStyles {
  245. err := sb.AddStreamStyle(streamStyle)
  246. if err != nil {
  247. return err
  248. }
  249. }
  250. return nil
  251. }
  252. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  253. // XML file so that these can be written at the right time.
  254. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string, removeDimensionTagFlag bool) error {
  255. // Get the sheet index from the path
  256. sheetIndex, err := getSheetIndex(sf, path)
  257. if err != nil {
  258. return err
  259. }
  260. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  261. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  262. if removeDimensionTagFlag {
  263. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  264. if err != nil {
  265. return err
  266. }
  267. }
  268. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  269. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  270. if err != nil {
  271. return err
  272. }
  273. sf.sheetXmlPrefix[sheetIndex] = prefix
  274. sf.sheetXmlSuffix[sheetIndex] = suffix
  275. return nil
  276. }
  277. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  278. // The files that store the data for each sheet must have the format:
  279. // xl/worksheets/sheet123.xml
  280. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  281. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  282. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  283. sheetXLSXIndex, err := strconv.Atoi(indexString)
  284. if err != nil {
  285. return -1, errors.New("unexpected sheet file name from xlsx package")
  286. }
  287. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  288. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  289. return -1, errors.New("unexpected sheet index")
  290. }
  291. sheetArrayIndex := sheetXLSXIndex - 1
  292. return sheetArrayIndex, nil
  293. }
  294. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  295. // data is the XML data for the sheet
  296. // sheet is the Sheet struct that the XML was created from.
  297. // Can return an error if the XML's dimension tag does not match what is expected based on the provided Sheet
  298. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  299. x := len(sheet.Cols) - 1
  300. y := len(sheet.Rows) - 1
  301. if x < 0 {
  302. x = 0
  303. }
  304. if y < 0 {
  305. y = 0
  306. }
  307. var dimensionRef string
  308. if x == 0 && y == 0 {
  309. dimensionRef = "A1"
  310. } else {
  311. endCoordinate := GetCellIDStringFromCoords(x, y)
  312. dimensionRef = "A1:" + endCoordinate
  313. }
  314. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  315. if len(dataParts) != 2 {
  316. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  317. }
  318. return dataParts[0] + dataParts[1], nil
  319. }
  320. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  321. // more spreadsheet rows can be inserted in between.
  322. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  323. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  324. sheetParts := strings.Split(data, endSheetDataTag)
  325. if len(sheetParts) != 2 {
  326. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  327. }
  328. return sheetParts[0], sheetParts[1], nil
  329. }