stream_file_builder.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. styleIdMap map[*Style]int
  38. }
  39. const (
  40. sheetFilePathPrefix = "xl/worksheets/sheet"
  41. sheetFilePathSuffix = ".xml"
  42. endSheetDataTag = "</sheetData>"
  43. dimensionTag = `<dimension ref="%s"></dimension>`
  44. // This is the index of the max style that this library will insert into XLSX sheets by default.
  45. // This allows us to predict what the style id of styles that we add will be.
  46. // TestXlsxStyleBehavior tests that this behavior continues to be what we expect.
  47. initMaxStyleId = 1
  48. )
  49. var BuiltStreamFileBuilderError = errors.New("StreamFileBuilder has already been built, functions may no longer be used")
  50. // NewStreamFileBuilder creates an StreamFileBuilder that will write to the the provided io.writer
  51. func NewStreamFileBuilder(writer io.Writer) *StreamFileBuilder {
  52. return &StreamFileBuilder{
  53. zipWriter: zip.NewWriter(writer),
  54. xlsxFile: NewFile(),
  55. // cellTypeToStyleIds: make(map[CellType]int),
  56. maxStyleId: initMaxStyleId,
  57. styleIdMap: make(map[*Style]int),
  58. }
  59. }
  60. // NewStreamFileBuilderForPath takes the name of an XLSX file and returns a builder for it.
  61. // The file will be created if it does not exist, or truncated if it does.
  62. func NewStreamFileBuilderForPath(path string) (*StreamFileBuilder, error) {
  63. file, err := os.Create(path)
  64. if err != nil {
  65. return nil, err
  66. }
  67. return NewStreamFileBuilder(file), nil
  68. }
  69. // AddSheet will add sheets with the given name with the provided headers. The headers cannot be edited later, and all
  70. // rows written to the sheet must contain the same number of cells as the header. Sheet names must be unique, or an
  71. // error will be thrown.
  72. func (sb *StreamFileBuilder) AddSheet(name string, headers []string, cellStyles []int, cellTypes []*CellType) error {
  73. if sb.built {
  74. return BuiltStreamFileBuilderError
  75. }
  76. if len(cellTypes) > len(headers) {
  77. return errors.New("cellTypes is longer than headers")
  78. }
  79. sheet, err := sb.xlsxFile.AddSheet(name)
  80. if err != nil {
  81. // Set built on error so that all subsequent calls to the builder will also fail.
  82. sb.built = true
  83. return err
  84. }
  85. sb.styleIds = append(sb.styleIds, []int{})
  86. row := sheet.AddRow()
  87. if count := row.WriteSlice(&headers, -1); count != len(headers) {
  88. // Set built on error so that all subsequent calls to the builder will also fail.
  89. sb.built = true
  90. return errors.New("failed to write headers")
  91. }
  92. for i, cellType := range cellTypes {
  93. cellStyleIndex := cellStyles[i]
  94. //var ok bool
  95. if cellType != nil {
  96. // The cell type is one of the attributes of a Style.
  97. // Since it is the only attribute of Style that we use, we can assume that cell types
  98. // map one to one with Styles and their Style ID.
  99. // If a new cell type is used, a new style gets created with an increased id, if an existing cell type is
  100. // used, the pre-existing style will also be used.
  101. //cellStyleIndex, ok = sb.cellTypeToStyleIds[*cellType]
  102. //if !ok {
  103. // sb.maxStyleId++
  104. // cellStyleIndex = sb.maxStyleId
  105. // sb.cellTypeToStyleIds[*cellType] = sb.maxStyleId
  106. //}
  107. sheet.Cols[i].SetType(*cellType)
  108. }
  109. sb.styleIds[len(sb.styleIds)-1] = append(sb.styleIds[len(sb.styleIds)-1], cellStyleIndex)
  110. }
  111. return nil
  112. }
  113. // Build begins streaming the XLSX file to the io, by writing all the XLSX metadata. It creates a StreamFile struct
  114. // that can be used to write the rows to the sheets.
  115. func (sb *StreamFileBuilder) Build() (*StreamFile, error) {
  116. if sb.built {
  117. return nil, BuiltStreamFileBuilderError
  118. }
  119. sb.built = true
  120. parts, err := sb.xlsxFile.MarshallParts()
  121. if err != nil {
  122. return nil, err
  123. }
  124. parts, err = sb.addDefaultStyles(parts)
  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. func (sb *StreamFileBuilder) addDefaultStyles(parts map[string]string) (map[string]string, error) {
  159. var err error
  160. // Default style - Bold
  161. defaultBold := NewStyle()
  162. defaultBold.Font.Bold = true
  163. if defaultBold != nil {
  164. xNumFmtId := 0 // GENERAL FORMATTING
  165. XfId := handleStyleForXLSX(defaultBold, xNumFmtId, sb.xlsxFile.styles)
  166. sb.styleIdMap[defaultBold] = XfId
  167. }
  168. // Default style - Italic
  169. defaultItalic := NewStyle()
  170. defaultItalic.Font.Italic = true
  171. if defaultItalic != nil {
  172. xNumFmtId := 0 // GENERAL FORMATTING
  173. XfId := handleStyleForXLSX(defaultItalic, xNumFmtId, sb.xlsxFile.styles)
  174. sb.styleIdMap[defaultItalic] = XfId
  175. }
  176. // Default date
  177. defaultDate := NewStyle()
  178. if defaultDate != nil {
  179. xNumFmtId := 14
  180. XfId := handleStyleForXLSX(defaultDate, xNumFmtId, sb.xlsxFile.styles)
  181. sb.styleIdMap[defaultDate] = XfId
  182. }
  183. parts["xl/styles.xml"], err = sb.xlsxFile.styles.Marshal()
  184. if err!=nil {
  185. return nil, err
  186. }
  187. return parts, nil
  188. }
  189. // processEmptySheetXML will take in the path and XML data of an empty sheet, and will save the beginning and end of the
  190. // XML file so that these can be written at the right time.
  191. func (sb *StreamFileBuilder) processEmptySheetXML(sf *StreamFile, path, data string) error {
  192. // Get the sheet index from the path
  193. sheetIndex, err := getSheetIndex(sf, path)
  194. if err != nil {
  195. return err
  196. }
  197. // Remove the Dimension tag. Since more rows are going to be written to the sheet, it will be wrong.
  198. // It is valid to for a sheet to be missing a Dimension tag, but it is not valid for it to be wrong.
  199. data, err = removeDimensionTag(data, sf.xlsxFile.Sheets[sheetIndex])
  200. if err != nil {
  201. return err
  202. }
  203. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  204. prefix, suffix, err := splitSheetIntoPrefixAndSuffix(data)
  205. if err != nil {
  206. return err
  207. }
  208. sf.sheetXmlPrefix[sheetIndex] = prefix
  209. sf.sheetXmlSuffix[sheetIndex] = suffix
  210. return nil
  211. }
  212. // getSheetIndex parses the path to the XLSX sheet data and returns the index
  213. // The files that store the data for each sheet must have the format:
  214. // xl/worksheets/sheet123.xml
  215. // where 123 is the index of the sheet. This file path format is part of the XLSX file standard.
  216. func getSheetIndex(sf *StreamFile, path string) (int, error) {
  217. indexString := path[len(sheetFilePathPrefix) : len(path)-len(sheetFilePathSuffix)]
  218. sheetXLSXIndex, err := strconv.Atoi(indexString)
  219. if err != nil {
  220. return -1, errors.New("Unexpected sheet file name from xlsx package")
  221. }
  222. if sheetXLSXIndex < 1 || len(sf.sheetXmlPrefix) < sheetXLSXIndex ||
  223. len(sf.sheetXmlSuffix) < sheetXLSXIndex || len(sf.xlsxFile.Sheets) < sheetXLSXIndex {
  224. return -1, errors.New("Unexpected sheet index")
  225. }
  226. sheetArrayIndex := sheetXLSXIndex - 1
  227. return sheetArrayIndex, nil
  228. }
  229. // removeDimensionTag will return the passed in XLSX Spreadsheet XML with the dimension tag removed.
  230. // data is the XML data for the sheet
  231. // sheet is the Sheet struct that the XML was created from.
  232. // Can return an error if the XML's dimension tag does not match was is expected based on the provided Sheet
  233. func removeDimensionTag(data string, sheet *Sheet) (string, error) {
  234. x := len(sheet.Cols) - 1
  235. y := len(sheet.Rows) - 1
  236. if x < 0 {
  237. x = 0
  238. }
  239. if y < 0 {
  240. y = 0
  241. }
  242. var dimensionRef string
  243. if x == 0 && y == 0 {
  244. dimensionRef = "A1"
  245. } else {
  246. endCoordinate := GetCellIDStringFromCoords(x, y)
  247. dimensionRef = "A1:" + endCoordinate
  248. }
  249. dataParts := strings.Split(data, fmt.Sprintf(dimensionTag, dimensionRef))
  250. if len(dataParts) != 2 {
  251. return "", errors.New("unexpected Sheet XML: dimension tag not found")
  252. }
  253. return dataParts[0] + dataParts[1], nil
  254. }
  255. // splitSheetIntoPrefixAndSuffix will split the provided XML sheet into a prefix and a suffix so that
  256. // more spreadsheet rows can be inserted in between.
  257. func splitSheetIntoPrefixAndSuffix(data string) (string, string, error) {
  258. // Split the sheet at the end of its SheetData tag so that more rows can be added inside.
  259. sheetParts := strings.Split(data, endSheetDataTag)
  260. if len(sheetParts) != 2 {
  261. return "", "", errors.New("unexpected Sheet XML: SheetData close tag not found")
  262. }
  263. return sheetParts[0], sheetParts[1], nil
  264. }