stream_file_builder.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  112. // that can be used to write the rows to the sheets.
  113. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  114. if sb.built {
  115. return nil, BuiltStreamFileBuilderError
  116. }
  117. sb.built = true
  118. parts, err := sb.xlsxFile.MarshallParts()
  119. if err != nil {
  120. return nil, err
  121. }
  122. es := &StreamFile{
  123. zipWriter: sb.zipWriter,
  124. xlsxFile: sb.xlsxFile,
  125. sheetXmlPrefix: make([]string, len(sb.xlsxFile.Sheets)),
  126. sheetXmlSuffix: make([]string, len(sb.xlsxFile.Sheets)),
  127. styleIds: sb.styleIds,
  128. }
  129. for path, data := range parts {
  130. // If the part is a sheet, don't write it yet. We only want to write the XLSX metadata files, since at this
  131. // point the sheets are still empty. The sheet files will be written later as their rows come in.
  132. if strings.HasPrefix(path, sheetFilePathPrefix) {
  133. if err := sb.processEmptySheetXML(es, path, data); err != nil {
  134. return nil, err
  135. }
  136. continue
  137. }
  138. metadataFile, err := sb.zipWriter.Create(path)
  139. if err != nil {
  140. return nil, err
  141. }
  142. _, err = metadataFile.Write([]byte(data))
  143. if err != nil {
  144. return nil, err
  145. }
  146. }
  147. if err := es.NextSheet(); err != nil {
  148. return nil, err
  149. }
  150. return es, nil
  151. }
  152. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  153. // XML file so that these can be written at the right time.
  154. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error {
  155. // Get the sheet index from the path
  156. sheetIndex, err := getSheetIndex(sf, path)
  157. if err != nil {
  158. return err
  159. }
  160. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  161. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  162. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  163. if err != nil {
  164. return err
  165. }
  166. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  167. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  168. if err != nil {
  169. return err
  170. }
  171. sf.sheetXmlPrefix[sheetIndex] = prefix
  172. sf.sheetXmlSuffix[sheetIndex] = suffix
  173. return nil
  174. }
  175. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  176. // The files that store the data for each sheet must have the format:
  177. // xl/worksheets/sheet123.xml
  178. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  179. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  180. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  181. sheetXLSXIndex, err := strconv.Atoi(indexString)
  182. if err != nil {
  183. return -1, errors.New("Unexpected sheet file name from xlsx package")
  184. }
  185. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  186. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  187. return -1, errors.New("Unexpected sheet index")
  188. }
  189. sheetArrayIndex := sheetXLSXIndex - 1
  190. return sheetArrayIndex, nil
  191. }
  192. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  193. // data is the XML data for the sheet
  194. // sheet is the Sheet struct that the XML was created from.
  195. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
  196. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  197. x := len(sheet.Cols) - 1
  198. y := len(sheet.Rows) - 1
  199. if x < 0 {
  200. x = 0
  201. }
  202. if y < 0 {
  203. y = 0
  204. }
  205. var dimensionRef string
  206. if x == 0 && y == 0 {
  207. dimensionRef = "A1"
  208. } else {
  209. endCoordinate := GetCellIDStringFromCoords(x, y)
  210. dimensionRef = "A1:" + endCoordinate
  211. }
  212. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  213. if len(dataParts) != 2 {
  214. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  215. }
  216. return dataParts[0] + dataParts[1], nil
  217. }
  218. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  219. // more spreadsheet rows can be inserted in between.
  220. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  221. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  222. sheetParts := strings.Split(data, endSheetDataTag)
  223. if len(sheetParts) != 2 {
  224. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  225. }
  226. return sheetParts[0], sheetParts[1], nil
  227. }