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