stream_file.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. package xlsx
  2. import (
  3. "archive/zip"
  4. "encoding/xml"
  5. "errors"
  6. "io"
  7. "strconv"
  8. )
  9. type StreamFile struct {
  10. xlsxFile *File
  11. sheetXmlPrefix []string
  12. sheetXmlSuffix []string
  13. zipWriter *zip.Writer
  14. currentSheet *streamSheet
  15. styleIds [][]int
  16. err error
  17. styleIdMap map[*StreamStyle]int
  18. }
  19. type streamSheet struct {
  20. // sheetIndex is the XLSX sheet index, which starts at 1
  21. index int
  22. // The number of rows that have been written to the sheet so far
  23. rowCount int
  24. // The number of columns in the sheet
  25. columnCount int
  26. // The writer to write to this sheet's file in the XLSX Zip file
  27. writer io.Writer
  28. styleIds []int
  29. }
  30. var (
  31. NoCurrentSheetError = errors.New("no Current Sheet")
  32. WrongNumberOfRowsError = errors.New("invalid number of cells passed to Write. All calls to Write on the same sheet must have the same number of cells")
  33. AlreadyOnLastSheetError = errors.New("NextSheet() called, but already on last sheet")
  34. WrongNumberOfCellTypesError = errors.New("the numbers of cells and cell types do not match")
  35. UnsupportedCellTypeError = errors.New("the given cell type is not supported")
  36. UnsupportedDataTypeError = errors.New("the given data type is not supported")
  37. )
  38. // Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the
  39. // same number of cells as the header provided when the sheet was created or an error will be returned. This function
  40. // will always trigger a flush on success. Currently the only supported data type is string data.
  41. // TODO update comment
  42. func (sf *StreamFile) Write(cells []string, cellTypes []*CellType, cellStyles []*StreamStyle) error {
  43. if sf.err != nil {
  44. return sf.err
  45. }
  46. err := sf.write(cells, cellTypes, cellStyles)
  47. if err != nil {
  48. sf.err = err
  49. return err
  50. }
  51. return sf.zipWriter.Flush()
  52. }
  53. //TODO Add comment
  54. func (sf *StreamFile) WriteAll(records [][]string, cellTypes []*CellType, cellStyles []*StreamStyle) error {
  55. if sf.err != nil {
  56. return sf.err
  57. }
  58. for _, row := range records {
  59. err := sf.write(row, cellTypes, cellStyles)
  60. if err != nil {
  61. sf.err = err
  62. return err
  63. }
  64. }
  65. return sf.zipWriter.Flush()
  66. }
  67. // TODO Add comment
  68. func (sf *StreamFile) write(cells []string, cellTypes []*CellType, cellStyles []*StreamStyle) error {
  69. if sf.currentSheet == nil {
  70. return NoCurrentSheetError
  71. }
  72. if len(cells) != sf.currentSheet.columnCount {
  73. return WrongNumberOfRowsError
  74. }
  75. if len(cells) != len(cellTypes) {
  76. return WrongNumberOfCellTypesError
  77. }
  78. sf.currentSheet.rowCount++
  79. // This is the XML row opening
  80. if err := sf.currentSheet.write(`<row r="` + strconv.Itoa(sf.currentSheet.rowCount) + `">`); err != nil {
  81. return err
  82. }
  83. // Add cells one by one
  84. for colIndex, cellData := range cells {
  85. // Get the cell reference (location)
  86. cellCoordinate := GetCellIDStringFromCoords(colIndex, sf.currentSheet.rowCount-1)
  87. // Get the cell type string
  88. cellType, err := GetCellTypeAsString(cellTypes[colIndex])
  89. if err != nil {
  90. return err
  91. }
  92. // Build the XML cell opening
  93. cellOpen := `<c r="` + cellCoordinate + `" t="` + cellType + `"`
  94. // Add in the style id if the cell isn't using the default style
  95. cellOpen += ` s="` + strconv.Itoa(sf.styleIdMap[cellStyles[colIndex]]) + `"`
  96. cellOpen += `>`
  97. // The XML cell contents
  98. cellContentsOpen, cellContentsClose, err := GetCellContentOpenAncCloseTags(cellTypes[colIndex])
  99. if err != nil {
  100. return err
  101. }
  102. // The XMl cell ending
  103. cellClose := `</c>`
  104. // Write the cell opening
  105. if err := sf.currentSheet.write(cellOpen); err != nil {
  106. return err
  107. }
  108. // Write the cell contents opening
  109. if err := sf.currentSheet.write(cellContentsOpen); err != nil {
  110. return err
  111. }
  112. // Write cell contents
  113. if err:= xml.EscapeText(sf.currentSheet.writer, []byte(cellData)); err != nil {
  114. return err
  115. }
  116. // Write cell contents ending
  117. if err := sf.currentSheet.write(cellContentsClose); err != nil {
  118. return err
  119. }
  120. // Write the cell ending
  121. if err := sf.currentSheet.write(cellClose); err != nil {
  122. return err
  123. }
  124. }
  125. if err := sf.currentSheet.write(`</row>`); err != nil {
  126. return err
  127. }
  128. return sf.zipWriter.Flush()
  129. }
  130. func GetCellTypeAsString(cellType *CellType) (string, error) {
  131. // documentation for the c.t (cell.Type) attribute:
  132. // b (Boolean): Cell containing a boolean.
  133. // d (Date): Cell contains a date in the ISO 8601 format.
  134. // e (Error): Cell containing an error.
  135. // inlineStr (Inline String): Cell containing an (inline) rich string, i.e., one not in the shared string table.
  136. // If this cell type is used, then the cell value is in the is element rather than the v element in the cell (c element).
  137. // n (Number): Cell containing a number.
  138. // s (Shared String): Cell containing a shared string.
  139. // str (String): Cell containing a formula string.
  140. if cellType == nil {
  141. // TODO should default be inline string?
  142. return "inlineStr", nil
  143. }
  144. switch *cellType{
  145. case CellTypeBool:
  146. return "b", nil
  147. case CellTypeDate:
  148. return "d", nil
  149. case CellTypeError:
  150. return "e", nil
  151. case CellTypeInline:
  152. return "inlineStr", nil
  153. case CellTypeNumeric:
  154. return "n", nil
  155. case CellTypeString:
  156. // TODO Currently inline strings are typed as shared strings
  157. // TODO remove once the tests have been changed
  158. return "inlineStr", nil
  159. // return "s", nil
  160. case CellTypeStringFormula:
  161. return "str", nil
  162. default:
  163. return "", UnsupportedCellTypeError
  164. }
  165. }
  166. func GetCellContentOpenAncCloseTags(cellType *CellType) (string, string, error) {
  167. if cellType == nil {
  168. // TODO should default be inline string?
  169. return `<is><t>`, `</t></is>`, nil
  170. }
  171. // TODO Currently inline strings are types as shared strings
  172. // TODO remove once the tests have been changed
  173. if *cellType == CellTypeString {
  174. return `<is><t>`, `</t></is>`, nil
  175. }
  176. switch *cellType{
  177. case CellTypeInline:
  178. return `<is><t>`, `</t></is>`, nil
  179. case CellTypeStringFormula:
  180. // Formulas are currently not supported
  181. return ``, ``, UnsupportedCellTypeError
  182. default:
  183. return `<v>`, `</v>`, nil
  184. }
  185. }
  186. // Error reports any error that has occurred during a previous Write or Flush.
  187. func (sf *StreamFile) Error() error {
  188. return sf.err
  189. }
  190. func (sf *StreamFile) Flush() {
  191. if sf.err != nil {
  192. sf.err = sf.zipWriter.Flush()
  193. }
  194. }
  195. // NextSheet will switch to the next sheet. Sheets are selected in the same order they were added.
  196. // Once you leave a sheet, you cannot return to it.
  197. func (sf *StreamFile) NextSheet() error {
  198. if sf.err != nil {
  199. return sf.err
  200. }
  201. var sheetIndex int
  202. if sf.currentSheet != nil {
  203. if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) {
  204. sf.err = AlreadyOnLastSheetError
  205. return AlreadyOnLastSheetError
  206. }
  207. if err := sf.writeSheetEnd(); err != nil {
  208. sf.currentSheet = nil
  209. sf.err = err
  210. return err
  211. }
  212. sheetIndex = sf.currentSheet.index
  213. }
  214. sheetIndex++
  215. sf.currentSheet = &streamSheet{
  216. index: sheetIndex,
  217. columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols),
  218. styleIds: sf.styleIds[sheetIndex-1],
  219. rowCount: 1,
  220. }
  221. sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix
  222. fileWriter, err := sf.zipWriter.Create(sheetPath)
  223. if err != nil {
  224. sf.err = err
  225. return err
  226. }
  227. sf.currentSheet.writer = fileWriter
  228. if err := sf.writeSheetStart(); err != nil {
  229. sf.err = err
  230. return err
  231. }
  232. return nil
  233. }
  234. // Close closes the Stream File.
  235. // Any sheets that have not yet been written to will have an empty sheet created for them.
  236. func (sf *StreamFile) Close() error {
  237. if sf.err != nil {
  238. return sf.err
  239. }
  240. // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them.
  241. // XLSX readers may error if the sheets registered in the metadata are not present in the file.
  242. if sf.currentSheet != nil {
  243. for sf.currentSheet.index < len(sf.xlsxFile.Sheets) {
  244. if err := sf.NextSheet(); err != nil {
  245. sf.err = err
  246. return err
  247. }
  248. }
  249. // Write the end of the last sheet.
  250. if err := sf.writeSheetEnd(); err != nil {
  251. sf.err = err
  252. return err
  253. }
  254. }
  255. err := sf.zipWriter.Close()
  256. if err != nil {
  257. sf.err = err
  258. }
  259. return err
  260. }
  261. // writeSheetStart will write the start of the Sheet's XML
  262. func (sf *StreamFile) writeSheetStart() error {
  263. if sf.currentSheet == nil {
  264. return NoCurrentSheetError
  265. }
  266. return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1])
  267. }
  268. // writeSheetEnd will write the end of the Sheet's XML
  269. func (sf *StreamFile) writeSheetEnd() error {
  270. if sf.currentSheet == nil {
  271. return NoCurrentSheetError
  272. }
  273. if err := sf.currentSheet.write(endSheetDataTag); err != nil {
  274. return err
  275. }
  276. return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1])
  277. }
  278. func (ss *streamSheet) write(data string) error {
  279. _, err := ss.writer.Write([]byte(data))
  280. return err
  281. }