stream_file_builder.go 9.3 KB

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