stream_file_builder.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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. xlsxFile *File
  33. zipWriter *zip.Writer
  34. cellTypeToStyleIds map[CellType]int
  35. maxStyleId int
  36. styleIds [][]int
  37. }
  38. const (
  39. sheetFilePathPrefix = "xl/worksheets/sheet"
  40. sheetFilePathSuffix = ".xml"
  41. endSheetDataTag = "</sheetData>"
  42. dimensionTag = `<dimension ref="%s"></dimension>`
  43. // This is the index of the max style that this library will insert into XLSX sheets by default.
  44. // This allows us to predict what the style id of styles that we add will be.
  45. // TestXlsxStyleBehavior tests that this behavior continues to be what we expect.
  46. initMaxStyleId = 1
  47. )
  48. var BuiltStreamFileBuilderError = errors.New("StreamFileBuilder has already been built, functions may no longer be used")
  49. // NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
  50. func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder {
  51. return &StreamFileBuilder{
  52. zipWriter: zip.NewWriter(writer),
  53. xlsxFile: NewFile(),
  54. cellTypeToStyleIds: make(map[CellType]int),
  55. maxStyleId: initMaxStyleId,
  56. }
  57. }
  58. // NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it.
  59. // The file will be created if it does not exist, or truncated if it does.
  60. func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) {
  61. file, err := os.Create(path)
  62. if err != nil {
  63. return nil, err
  64. }
  65. return NewStreamFileBuilder(file), nil
  66. }
  67. // AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all
  68. // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an
  69. // error will be thrown.
  70. func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellTypes []*CellType) error {
  71. if sb.built {
  72. return BuiltStreamFileBuilderError
  73. }
  74. if len(cellTypes) > len(headers) {
  75. return errors.New("cellTypes is longer than headers")
  76. }
  77. sheet, err := sb.xlsxFile.AddSheet(name)
  78. if err != nil {
  79. // Set built on error so that all subsequent calls to the builder will also fail.
  80. sb.built = true
  81. return err
  82. }
  83. sb.styleIds = append(sb.styleIds, []int{})
  84. row := sheet.AddRow()
  85. if count := row.WriteSlice(&headers, -1); count != len(headers) {
  86. // Set built on error so that all subsequent calls to the builder will also fail.
  87. sb.built = true
  88. return errors.New("failed to write headers")
  89. }
  90. for i, cellType := range cellTypes {
  91. var cellStyleIndex int
  92. var ok bool
  93. if cellType != nil {
  94. // The cell type is one of the attributes of a Style.
  95. // Since it is the only attribute of Style that we use, we can assume that cell types
  96. // map one to one with Styles and their Style ID.
  97. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is
  98. // used, the pre-existing style will also be used.
  99. cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType]
  100. if !ok {
  101. sb.maxStyleId++
  102. cellStyleIndex = sb.maxStyleId
  103. sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId
  104. }
  105. sheet.Cols[i].SetType(*cellType)
  106. }
  107. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  108. }
  109. return nil
  110. }
  111. // AddValidation will add a validation to a specific column.
  112. func (sb *StreamFileBuilder) AddValidation(sheetIndex, colIndex, rowStartIndex int, validation *xlsxCellDataValidation) {
  113. sheet := sb.xlsxFile.Sheets[sheetIndex]
  114. column := sheet.Col(colIndex)
  115. column.SetDataValidationWithStart(validation, rowStartIndex)
  116. }
  117. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  118. // that can be used to write the rows to the sheets.
  119. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  120. if sb.built {
  121. return nil, BuiltStreamFileBuilderError
  122. }
  123. sb.built = true
  124. parts, err := sb.xlsxFile.MarshallParts()
  125. if err != nil {
  126. return nil, err
  127. }
  128. es := &StreamFile{
  129. zipWriter: sb.zipWriter,
  130. xlsxFile: sb.xlsxFile,
  131. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  132. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  133. styleIds: sb.styleIds,
  134. }
  135. for path, data := range parts {
  136. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  137. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  138. if strings.HasPrefix(path, sheetFilePathPrefix) {
  139. if err := sb.processEmptySheetXML(es, path, data); err != nil {
  140. return nil, err
  141. }
  142. continue
  143. }
  144. metadataFile, err := sb.zipWriter.Create(path)
  145. if err != nil {
  146. return nil, err
  147. }
  148. _, err = metadataFile.Write([]byte(data))
  149. if err != nil {
  150. return nil, err
  151. }
  152. }
  153. if err := es.NextSheet(); err != nil {
  154. return nil, err
  155. }
  156. return es, nil
  157. }
  158. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  159. // XML file so that these can be written at the right time.
  160. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error {
  161. // Get the sheet index from the path
  162. sheetIndex, err := getSheetIndex(sf, path)
  163. if err != nil {
  164. return err
  165. }
  166. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  167. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  168. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  169. if err != nil {
  170. return err
  171. }
  172. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  173. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  174. if err != nil {
  175. return err
  176. }
  177. sf.sheetXmlPrefix[sheetIndex] = prefix
  178. sf.sheetXmlSuffix[sheetIndex] = suffix
  179. return nil
  180. }
  181. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  182. // The files that store the data for each sheet must have the format:
  183. // xl/worksheets/sheet123.xml
  184. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  185. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  186. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  187. sheetXLSXIndex, err := strconv.Atoi(indexString)
  188. if err != nil {
  189. return -1, errors.New("Unexpected sheet file name from xlsx package")
  190. }
  191. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  192. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  193. return -1, errors.New("Unexpected sheet index")
  194. }
  195. sheetArrayIndex := sheetXLSXIndex - 1
  196. return sheetArrayIndex, nil
  197. }
  198. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  199. // data is the XML data for the sheet
  200. // sheet is the Sheet struct that the XML was created from.
  201. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
  202. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  203. x := len(sheet.Cols) - 1
  204. y := len(sheet.Rows) - 1
  205. if x < 0 {
  206. x = 0
  207. }
  208. if y < 0 {
  209. y = 0
  210. }
  211. var dimensionRef string
  212. if x == 0 && y == 0 {
  213. dimensionRef = "A1"
  214. } else {
  215. endCoordinate := GetCellIDStringFromCoords(x, y)
  216. dimensionRef = "A1:" + endCoordinate
  217. }
  218. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  219. if len(dataParts) != 2 {
  220. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  221. }
  222. return dataParts[0] + dataParts[1], nil
  223. }
  224. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  225. // more spreadsheet rows can be inserted in between.
  226. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  227. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  228. sheetParts := strings.Split(data, endSheetDataTag)
  229. if len(sheetParts) != 2 {
  230. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  231. }
  232. return sheetParts[0], sheetParts[1], nil
  233. }