stream_file_builder.go 10.0 KB

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