stream_file_builder.go 10 KB

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