stream_file_builder.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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. // Future work suggestions:
  13. // Currently the only supported cell type is string, since the main reason this library was written was to prevent
  14. // strings from being interpreted as numbers. It would be nice to have support for numbers and money so that the exported
  15. // files could better take advantage of XLSX's features.
  16. // All text is written with the same text style. Support for additional text styles could be added to highlight certain
  17. // data in the file.
  18. // The current default style uses fonts that are not on Macs by default so opening the XLSX files in Numbers causes a
  19. // pop up that says there are missing fonts. The font could be changed to something that is usually found on Mac and PC.
  20. package xlsx
  21. import (
  22. "archive/zip"
  23. "errors"
  24. "fmt"
  25. "io"
  26. "os"
  27. "strconv"
  28. "strings"
  29. )
  30. type StreamFileBuilder struct {
  31. built bool
  32. firstSheetAdded bool
  33. customStylesAdded bool
  34. xlsxFile *File
  35. zipWriter *zip.Writer
  36. cellTypeToStyleIds map[CellType]int
  37. maxStyleId int
  38. styleIds [][]int
  39. customStreamStyles map[StreamStyle]struct{}
  40. styleIdMap map[StreamStyle]int
  41. }
  42. const (
  43. sheetFilePathPrefix = "xl/worksheets/sheet"
  44. sheetFilePathSuffix = ".xml"
  45. endSheetDataTag = "</sheetData>"
  46. dimensionTag = `<dimension ref="%s"></dimension>`
  47. // This is the index of the max style that this library will insert into XLSX sheets by default.
  48. // This allows us to predict what the style id of styles that we add will be.
  49. // TestXlsxStyleBehavior tests that this behavior continues to be what we expect.
  50. initMaxStyleId = 1
  51. )
  52. var BuiltStreamFileBuilderError = errors.New("StreamFileBuilder has already been built, functions may no longer be used")
  53. // NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
  54. func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder {
  55. return &StreamFileBuilder{
  56. zipWriter: zip.NewWriter(writer),
  57. xlsxFile: NewFile(),
  58. cellTypeToStyleIds: make(map[CellType]int),
  59. maxStyleId: initMaxStyleId,
  60. customStreamStyles: make(map[StreamStyle]struct{}),
  61. styleIdMap: make(map[StreamStyle]int),
  62. }
  63. }
  64. // NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it.
  65. // The file will be created if it does not exist, or truncated if it does.
  66. func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) {
  67. file, err := os.Create(path)
  68. if err != nil {
  69. return nil, err
  70. }
  71. return NewStreamFileBuilder(file), nil
  72. }
  73. // AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all
  74. // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an
  75. // error will be thrown.
  76. func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error {
  77. if sb.built {
  78. return BuiltStreamFileBuilderError
  79. }
  80. if len(cellTypes) > len(headers) {
  81. return errors.New("cellTypes is longer than headers")
  82. }
  83. sheet, err := sb.xlsxFile.AddSheet(name)
  84. if err != nil {
  85. // Set built on error so that all subsequent calls to the builder will also fail.
  86. sb.built = true
  87. return err
  88. }
  89. sb.styleIds = append(sb.styleIds, []int{})
  90. row := sheet.AddRow()
  91. if count := row.WriteSlice(&headers, -1); count != len(headers) {
  92. // Set built on error so that all subsequent calls to the builder will also fail.
  93. sb.built = true
  94. return errors.New("failed to write headers")
  95. }
  96. for i, cellType := range cellTypes {
  97. var cellStyleIndex int
  98. var ok bool
  99. if cellType != nil {
  100. // The cell type is one of the attributes of a Style.
  101. // Since it is the only attribute of Style that we use, we can assume that cell types
  102. // map one to one with Styles and their Style ID.
  103. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is
  104. // used, the pre-existing style will also be used.
  105. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType]
  106. if !ok {
  107. sb.maxStyleId++
  108. cellStyleIndex = sb.maxStyleId
  109. sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId
  110. }
  111. sheet.Cols[i].SetType(*cellType)
  112. }
  113. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  114. }
  115. return nil
  116. }
  117. // AddSheetS will add a sheet with the given name and column styles. The number of column styles given
  118. // is the number of columns that will be created, and thus the number of cells each row has to have.
  119. // columnStyles[0] becomes the style of the first column, columnStyles[1] the style of the second column etc.
  120. // All the styles in columnStyles have to have been added or an error will be returned.
  121. // Sheet names must be unique, or an error will be returned.
  122. func (sb *StreamFileBuilder) AddSheetS(name string, columnStyles []StreamStyle) error {
  123. if sb.built {
  124. return BuiltStreamFileBuilderError
  125. }
  126. sheet, err := sb.xlsxFile.AddSheet(name)
  127. if err != nil {
  128. // Set built on error so that all subsequent calls to the builder will also fail.
  129. sb.built = true
  130. return err
  131. }
  132. // To make sure no new styles can be added after adding a sheet
  133. sb.firstSheetAdded = true
  134. // Check if all styles that will be used for columns have been created
  135. for _, colStyle := range columnStyles {
  136. if _, ok := sb.customStreamStyles[colStyle]; !ok {
  137. return errors.New("trying to make use of a style that has not been added")
  138. }
  139. }
  140. // TODO Is needed for stream file to work but is not needed for streaming with styles
  141. sb.styleIds = append(sb.styleIds, []int{})
  142. sheet.maybeAddCol(len(columnStyles))
  143. // Set default column styles based on the cel styles in the first row
  144. // Set the default column width to 11. This makes enough places for the
  145. // default date style cells to display the dates correctly
  146. for i, colStyle := range columnStyles {
  147. sheet.Cols[i].SetStreamStyle(colStyle)
  148. sheet.Cols[i].Width = 11
  149. }
  150. return nil
  151. }
  152. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  153. // that can be used to write the rows to the sheets.
  154. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  155. if sb.built {
  156. return nil, BuiltStreamFileBuilderError
  157. }
  158. sb.built = true
  159. parts, err := sb.xlsxFile.MarshallParts()
  160. if err != nil {
  161. return nil, err
  162. }
  163. if sb.customStylesAdded {
  164. parts["xl/styles.xml"], err = sb.marshalStyles()
  165. if err != nil {
  166. return nil, err
  167. }
  168. }
  169. es := &StreamFile{
  170. zipWriter: sb.zipWriter,
  171. xlsxFile: sb.xlsxFile,
  172. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  173. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  174. styleIds: sb.styleIds,
  175. styleIdMap: sb.styleIdMap,
  176. }
  177. for path, data := range parts {
  178. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  179. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  180. if strings.HasPrefix(path, sheetFilePathPrefix) {
  181. if err := sb.processEmptySheetXML(es, path, data, !sb.customStylesAdded); err != nil {
  182. return nil, err
  183. }
  184. continue
  185. }
  186. metadataFile, err := sb.zipWriter.Create(path)
  187. if err != nil {
  188. return nil, err
  189. }
  190. _, err = metadataFile.Write([]byte(data))
  191. if err != nil {
  192. return nil, err
  193. }
  194. }
  195. if err := es.NextSheet(); err != nil {
  196. return nil, err
  197. }
  198. return es, nil
  199. }
  200. func (sb *StreamFileBuilder) marshalStyles() (string, error) {
  201. for streamStyle, _ := range sb.customStreamStyles {
  202. // TODO do not add styles that already exist
  203. XfId := handleStyleForXLSX(streamStyle.style, streamStyle.xNumFmtId, sb.xlsxFile.styles)
  204. sb.styleIdMap[streamStyle] = XfId
  205. }
  206. styleSheetXMLString, err := sb.xlsxFile.styles.Marshal()
  207. if err != nil {
  208. return "", err
  209. }
  210. return styleSheetXMLString, nil
  211. }
  212. // AddStreamStyle adds a new style to the style sheet.
  213. // Only Styles that have been added through this function will be usable.
  214. // This function cannot be used after AddSheetS or Build has been called, and if it is
  215. // called after AddSheetS or Buildit will return an error.
  216. func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error {
  217. if sb.firstSheetAdded {
  218. return errors.New("at least one sheet has been added, cannot add new styles anymore")
  219. }
  220. if sb.built {
  221. return errors.New("file has been build, cannot add new styles anymore")
  222. }
  223. sb.customStreamStyles[streamStyle] = struct{}{}
  224. sb.customStylesAdded = true
  225. return nil
  226. }
  227. // AddStreamStyleList adds a list of new styles to the style sheet.
  228. // Only Styles that have been added through either this function or AddStreamStyle will be usable.
  229. // This function cannot be used after AddSheetS and Build has been called, and if it is
  230. // called after AddSheetS and Build it will return an error.
  231. func (sb *StreamFileBuilder) AddStreamStyleList(streamStyles []StreamStyle) error {
  232. for _, streamStyle := range streamStyles {
  233. err := sb.AddStreamStyle(streamStyle)
  234. if err != nil {
  235. return err
  236. }
  237. }
  238. return nil
  239. }
  240. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  241. // XML file so that these can be written at the right time.
  242. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string, removeDimensionTagFlag bool) error {
  243. // Get the sheet index from the path
  244. sheetIndex, err := getSheetIndex(sf, path)
  245. if err != nil {
  246. return err
  247. }
  248. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  249. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  250. if removeDimensionTagFlag {
  251. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  252. if err != nil {
  253. return err
  254. }
  255. }
  256. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  257. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  258. if err != nil {
  259. return err
  260. }
  261. sf.sheetXmlPrefix[sheetIndex] = prefix
  262. sf.sheetXmlSuffix[sheetIndex] = suffix
  263. return nil
  264. }
  265. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  266. // The files that store the data for each sheet must have the format:
  267. // xl/worksheets/sheet123.xml
  268. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  269. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  270. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  271. sheetXLSXIndex, err := strconv.Atoi(indexString)
  272. if err != nil {
  273. return -1, errors.New("unexpected sheet file name from xlsx package")
  274. }
  275. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  276. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  277. return -1, errors.New("unexpected sheet index")
  278. }
  279. sheetArrayIndex := sheetXLSXIndex - 1
  280. return sheetArrayIndex, nil
  281. }
  282. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  283. // data is the XML data for the sheet
  284. // sheet is the Sheet struct that the XML was created from.
  285. // Can return an error if the XML's dimension tag does not match what is expected based on the provided Sheet
  286. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  287. x := len(sheet.Cols) - 1
  288. y := len(sheet.Rows) - 1
  289. if x < 0 {
  290. x = 0
  291. }
  292. if y < 0 {
  293. y = 0
  294. }
  295. var dimensionRef string
  296. if x == 0 && y == 0 {
  297. dimensionRef = "A1"
  298. } else {
  299. endCoordinate := GetCellIDStringFromCoords(x, y)
  300. dimensionRef = "A1:" + endCoordinate
  301. }
  302. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  303. if len(dataParts) != 2 {
  304. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  305. }
  306. return dataParts[0] + dataParts[1], nil
  307. }
  308. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  309. // more spreadsheet rows can be inserted in between.
  310. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  311. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  312. sheetParts := strings.Split(data, endSheetDataTag)
  313. if len(sheetParts) != 2 {
  314. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  315. }
  316. return sheetParts[0], sheetParts[1], nil
  317. }