stream_file_builder.go 13 KB

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