stream_file_builder.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. // 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.styleIdMap[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. // Set default column types based on the cel types in the first row
  149. for i, cell := range cells {
  150. sheet.Cols[i].SetType(cell.cellType)
  151. // TODO test
  152. sheet.Cols[i].BestFit = true
  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. // Marshall Parts resets the style sheet, so to keep style information that has been added by the user
  164. // we have to marshal it beforehand and add it again after the entire file has been marshaled
  165. var xmlStylesSheetString string
  166. var err error
  167. if sb.customStylesAdded{
  168. xmlStylesSheetString, err = sb.marshalStyles()
  169. if err != nil {
  170. return nil, err
  171. }
  172. }
  173. parts, err := sb.xlsxFile.MarshallParts()
  174. if err != nil {
  175. return nil, err
  176. }
  177. if sb.customStylesAdded{
  178. parts["xl/styles.xml"] = xmlStylesSheetString
  179. }
  180. es := &StreamFile{
  181. zipWriter: sb.zipWriter,
  182. xlsxFile: sb.xlsxFile,
  183. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  184. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  185. styleIds: sb.styleIds,
  186. styleIdMap: sb.styleIdMap,
  187. }
  188. for path, data := range parts {
  189. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  190. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  191. if strings.HasPrefix(path, sheetFilePathPrefix) {
  192. if err := sb.processEmptySheetXML(es, path, data); err != nil {
  193. return nil, err
  194. }
  195. continue
  196. }
  197. metadataFile, err := sb.zipWriter.Create(path)
  198. if err != nil {
  199. return nil, err
  200. }
  201. _, err = metadataFile.Write([]byte(data))
  202. if err != nil {
  203. return nil, err
  204. }
  205. }
  206. if err := es.NextSheet(); err != nil {
  207. return nil, err
  208. }
  209. return es, nil
  210. }
  211. func (sb *StreamFileBuilder) marshalStyles() (string, error) {
  212. styleSheetXMLString, err := sb.xlsxFile.styles.Marshal()
  213. if err!=nil {
  214. return "", err
  215. }
  216. return styleSheetXMLString, nil
  217. }
  218. // AddStreamStyle adds a new style to the style sheet.
  219. // Only Styles that have been added through this function will be usable.
  220. // This function cannot be used after AddSheetWithStyle has been called, and if it is
  221. // called after AddSheetWithStyle it will return an error.
  222. //func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error {
  223. // if sb.firstSheetAdded {
  224. // return errors.New("at least one sheet has been added, cannot add new styles anymore")
  225. // }
  226. // sb.streamStyles[streamStyle] = struct{}{}
  227. // return nil
  228. //}
  229. // AddStreamStyle adds a new style to the style sheet.
  230. // Only Styles that have been added through either this function or AddStreamStyleList will be usable.
  231. // This function cannot be used after AddSheetWithStyle has been called, and if it is
  232. // called after AddSheetWithStyle it will return an error.
  233. func (sb *StreamFileBuilder) AddStreamStyle(streamStyle StreamStyle) error {
  234. if sb.firstSheetAdded {
  235. return errors.New("the style file has been built, cannot add new styles anymore")
  236. }
  237. if sb.xlsxFile.styles == nil {
  238. sb.xlsxFile.styles = newXlsxStyleSheet(sb.xlsxFile.theme)
  239. }
  240. XfId := handleStyleForXLSX(streamStyle.style, streamStyle.xNumFmtId, sb.xlsxFile.styles)
  241. sb.styleIdMap[streamStyle] = XfId
  242. sb.customStylesAdded = true
  243. return nil
  244. }
  245. // AddStreamStyleList adds a list of new styles to the style sheet.
  246. // Only Styles that have been added through either this function or AddStreamStyle will be usable.
  247. // This function cannot be used after AddSheetWithStyle has been called, and if it is
  248. // called after AddSheetWithStyle it will return an error.
  249. func (sb *StreamFileBuilder) AddStreamStyleList(streamStyles []StreamStyle) error {
  250. for _, streamStyle := range streamStyles {
  251. err := sb.AddStreamStyle(streamStyle)
  252. if err != nil{
  253. return err
  254. }
  255. }
  256. return nil
  257. }
  258. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  259. // XML file so that these can be written at the right time.
  260. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error {
  261. // Get the sheet index from the path
  262. sheetIndex, err := getSheetIndex(sf, path)
  263. if err != nil {
  264. return err
  265. }
  266. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  267. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  268. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  269. if err != nil {
  270. return err
  271. }
  272. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  273. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  274. if err != nil {
  275. return err
  276. }
  277. sf.sheetXmlPrefix[sheetIndex] = prefix
  278. sf.sheetXmlSuffix[sheetIndex] = suffix
  279. return nil
  280. }
  281. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  282. // The files that store the data for each sheet must have the format:
  283. // xl/worksheets/sheet123.xml
  284. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  285. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  286. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  287. sheetXLSXIndex, err := strconv.Atoi(indexString)
  288. if err != nil {
  289. return -1, errors.New("unexpected sheet file name from xlsx package")
  290. }
  291. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  292. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  293. return -1, errors.New("unexpected sheet index")
  294. }
  295. sheetArrayIndex := sheetXLSXIndex - 1
  296. return sheetArrayIndex, nil
  297. }
  298. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  299. // data is the XML data for the sheet
  300. // sheet is the Sheet struct that the XML was created from.
  301. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
  302. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  303. x := len(sheet.Cols) - 1
  304. y := len(sheet.Rows) - 1
  305. if x < 0 {
  306. x = 0
  307. }
  308. if y < 0 {
  309. y = 0
  310. }
  311. var dimensionRef string
  312. if x == 0 && y == 0 {
  313. dimensionRef = "A1"
  314. } else {
  315. endCoordinate := GetCellIDStringFromCoords(x, y)
  316. dimensionRef = "A1:" + endCoordinate
  317. }
  318. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  319. if len(dataParts) != 2 {
  320. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  321. }
  322. return dataParts[0] + dataParts[1], nil
  323. }
  324. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  325. // more spreadsheet rows can be inserted in between.
  326. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  327. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  328. sheetParts := strings.Split(data, endSheetDataTag)
  329. if len(sheetParts) != 2 {
  330. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  331. }
  332. return sheetParts[0], sheetParts[1], nil
  333. }