stream_file.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. switch cellType{
  141. case CellTypeBool:
  142. return "b", nil
  143. case CellTypeDate:
  144. return "d", nil
  145. case CellTypeError:
  146. return "e", nil
  147. case CellTypeInline:
  148. return "inlineStr", nil
  149. case CellTypeNumeric:
  150. return "n", nil
  151. case CellTypeString:
  152. // TODO Currently inline strings are typed as shared strings
  153. // TODO remove once the tests have been changed
  154. return "inlineStr", nil
  155. // return "s", nil
  156. case CellTypeStringFormula:
  157. return "str", nil
  158. default:
  159. return "", UnsupportedCellTypeError
  160. }
  161. }
  162. func GetCellContentOpenAncCloseTags(cellType CellType) (string, string, error) {
  163. // TODO Currently inline strings are types as shared strings
  164. // TODO remove once the tests have been changed
  165. if cellType == CellTypeString {
  166. return `<is><t>`, `</t></is>`, nil
  167. }
  168. switch cellType{
  169. case CellTypeInline:
  170. return `<is><t>`, `</t></is>`, nil
  171. case CellTypeStringFormula:
  172. // Formulas are currently not supported
  173. return ``, ``, UnsupportedCellTypeError
  174. default:
  175. return `<v>`, `</v>`, nil
  176. }
  177. }
  178. // Error reports any error that has occurred during a previous Write or Flush.
  179. func (sf *StreamFile) Error() error {
  180. return sf.err
  181. }
  182. func (sf *StreamFile) Flush() {
  183. if sf.err != nil {
  184. sf.err = sf.zipWriter.Flush()
  185. }
  186. }
  187. // NextSheet will switch to the next sheet. Sheets are selected in the same order they were added.
  188. // Once you leave a sheet, you cannot return to it.
  189. func (sf *StreamFile) NextSheet() error {
  190. if sf.err != nil {
  191. return sf.err
  192. }
  193. var sheetIndex int
  194. if sf.currentSheet != nil {
  195. if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) {
  196. sf.err = AlreadyOnLastSheetError
  197. return AlreadyOnLastSheetError
  198. }
  199. if err := sf.writeSheetEnd(); err != nil {
  200. sf.currentSheet = nil
  201. sf.err = err
  202. return err
  203. }
  204. sheetIndex = sf.currentSheet.index
  205. }
  206. sheetIndex++
  207. sf.currentSheet = &streamSheet{
  208. index: sheetIndex,
  209. columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols),
  210. styleIds: sf.styleIds[sheetIndex-1],
  211. rowCount: 1,
  212. }
  213. sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix
  214. fileWriter, err := sf.zipWriter.Create(sheetPath)
  215. if err != nil {
  216. sf.err = err
  217. return err
  218. }
  219. sf.currentSheet.writer = fileWriter
  220. if err := sf.writeSheetStart(); err != nil {
  221. sf.err = err
  222. return err
  223. }
  224. return nil
  225. }
  226. // Close closes the Stream File.
  227. // Any sheets that have not yet been written to will have an empty sheet created for them.
  228. func (sf *StreamFile) Close() error {
  229. if sf.err != nil {
  230. return sf.err
  231. }
  232. // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them.
  233. // XLSX readers may error if the sheets registered in the metadata are not present in the file.
  234. if sf.currentSheet != nil {
  235. for sf.currentSheet.index < len(sf.xlsxFile.Sheets) {
  236. if err := sf.NextSheet(); err != nil {
  237. sf.err = err
  238. return err
  239. }
  240. }
  241. // Write the end of the last sheet.
  242. if err := sf.writeSheetEnd(); err != nil {
  243. sf.err = err
  244. return err
  245. }
  246. }
  247. err := sf.zipWriter.Close()
  248. if err != nil {
  249. sf.err = err
  250. }
  251. return err
  252. }
  253. // writeSheetStart will write the start of the Sheet's XML
  254. func (sf *StreamFile) writeSheetStart() error {
  255. if sf.currentSheet == nil {
  256. return NoCurrentSheetError
  257. }
  258. return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1])
  259. }
  260. // writeSheetEnd will write the end of the Sheet's XML
  261. func (sf *StreamFile) writeSheetEnd() error {
  262. if sf.currentSheet == nil {
  263. return NoCurrentSheetError
  264. }
  265. if err := sf.currentSheet.write(endSheetDataTag); err != nil {
  266. return err
  267. }
  268. return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1])
  269. }
  270. func (ss *streamSheet) write(data string) error {
  271. _, err := ss.writer.Write([]byte(data))
  272. return err
  273. }