stream_file_builder.go 9.9 KB

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