stream_file.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. styleIdMap map[StreamStyle]int
  17. err error
  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. UnsupportedCellTypeError = errors.New("the given cell type is not supported")
  35. )
  36. // Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the
  37. // same number of cells as the header provided when the sheet was created or an error will be returned. This function
  38. // will always trigger a flush on success. Currently the only supported data type is string data.
  39. func (sf *StreamFile) Write(cells []string) error {
  40. if sf.err != nil {
  41. return sf.err
  42. }
  43. err := sf.write(cells)
  44. if err != nil {
  45. sf.err = err
  46. return err
  47. }
  48. return sf.zipWriter.Flush()
  49. }
  50. // WriteS will write a row of cells to the current sheet. Every call to WriteS on the same sheet must
  51. // contain the same number of cells as the number of columns provided when the sheet was created or an error
  52. // will be returned. This function will always trigger a flush on success. WriteS supports all data types
  53. // and styles that are supported by StreamCell.
  54. func (sf *StreamFile) WriteS(cells []StreamCell) error {
  55. if sf.err != nil {
  56. return sf.err
  57. }
  58. err := sf.writeS(cells)
  59. if err != nil {
  60. sf.err = err
  61. return err
  62. }
  63. return sf.zipWriter.Flush()
  64. }
  65. func (sf *StreamFile) WriteAll(records [][]string) error {
  66. if sf.err != nil {
  67. return sf.err
  68. }
  69. for _, row := range records {
  70. err := sf.write(row)
  71. if err != nil {
  72. sf.err = err
  73. return err
  74. }
  75. }
  76. return sf.zipWriter.Flush()
  77. }
  78. // WriteAllS will write all the rows provided in records. All rows must have the same number of cells as
  79. // the number of columns given when creating the sheet. This function will always trigger a flush on success.
  80. // WriteAllS supports all data types and styles that are supported by StreamCell.
  81. func (sf *StreamFile) WriteAllS(records [][]StreamCell) error {
  82. if sf.err != nil {
  83. return sf.err
  84. }
  85. for _, row := range records {
  86. err := sf.writeS(row)
  87. if err != nil {
  88. sf.err = err
  89. return err
  90. }
  91. }
  92. return sf.zipWriter.Flush()
  93. }
  94. func (sf *StreamFile) write(cells []string) error {
  95. if sf.currentSheet == nil {
  96. return NoCurrentSheetError
  97. }
  98. if len(cells) != sf.currentSheet.columnCount {
  99. return WrongNumberOfRowsError
  100. }
  101. sf.currentSheet.rowCount++
  102. if err := sf.currentSheet.write(`<row r="` + strconv.Itoa(sf.currentSheet.rowCount) + `">`); err != nil {
  103. return err
  104. }
  105. for colIndex, cellData := range cells {
  106. // documentation for the c.t (cell.Type) attribute:
  107. // b (Boolean): Cell containing a boolean.
  108. // d (Date): Cell contains a date in the ISO 8601 format.
  109. // e (Error): Cell containing an error.
  110. // inlineStr (Inline String): Cell containing an (inline) rich string, i.e., one not in the shared string table.
  111. // 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).
  112. // n (Number): Cell containing a number.
  113. // s (Shared String): Cell containing a shared string.
  114. // str (String): Cell containing a formula string.
  115. cellCoordinate := GetCellIDStringFromCoords(colIndex, sf.currentSheet.rowCount-1)
  116. cellType := "inlineStr"
  117. cellOpen := `<c r="` + cellCoordinate + `" t="` + cellType + `"`
  118. // Add in the style id if the cell isn't using the default style
  119. if colIndex < len(sf.currentSheet.styleIds) && sf.currentSheet.styleIds[colIndex] != 0 {
  120. cellOpen += ` s="` + strconv.Itoa(sf.currentSheet.styleIds[colIndex]) + `"`
  121. }
  122. cellOpen += `><is><t>`
  123. cellClose := `</t></is></c>`
  124. if err := sf.currentSheet.write(cellOpen); err != nil {
  125. return err
  126. }
  127. if err := xml.EscapeText(sf.currentSheet.writer, []byte(cellData)); err != nil {
  128. return err
  129. }
  130. if err := sf.currentSheet.write(cellClose); err != nil {
  131. return err
  132. }
  133. }
  134. if err := sf.currentSheet.write(`</row>`); err != nil {
  135. return err
  136. }
  137. return sf.zipWriter.Flush()
  138. }
  139. func (sf *StreamFile) writeS(cells []StreamCell) error {
  140. if sf.currentSheet == nil {
  141. return NoCurrentSheetError
  142. }
  143. if len(cells) != sf.currentSheet.columnCount {
  144. return WrongNumberOfRowsError
  145. }
  146. sf.currentSheet.rowCount++
  147. // Write the row opening
  148. if err := sf.currentSheet.write(`<row r="` + strconv.Itoa(sf.currentSheet.rowCount) + `">`); err != nil {
  149. return err
  150. }
  151. // Add cells one by one
  152. for colIndex, cell := range cells {
  153. xlsxCell, err := sf.getXlsxCell(cell, colIndex)
  154. if err != nil {
  155. return err
  156. }
  157. marshaledCell, err := xml.Marshal(xlsxCell)
  158. if err != nil {
  159. return nil
  160. }
  161. // Write the cell
  162. if _, err := sf.currentSheet.writer.Write(marshaledCell); err != nil {
  163. return err
  164. }
  165. }
  166. // Write the row ending
  167. if err := sf.currentSheet.write(`</row>`); err != nil {
  168. return err
  169. }
  170. return sf.zipWriter.Flush()
  171. }
  172. func (sf *StreamFile) getXlsxCell(cell StreamCell, colIndex int) (xlsxC, error) {
  173. // Get the cell reference (location)
  174. cellCoordinate := GetCellIDStringFromCoords(colIndex, sf.currentSheet.rowCount-1)
  175. var cellStyleId int
  176. if cell.cellStyle != (StreamStyle{}) {
  177. if idx, ok := sf.styleIdMap[cell.cellStyle]; ok {
  178. cellStyleId = idx
  179. } else {
  180. return xlsxC{}, errors.New("trying to make use of a style that has not been added")
  181. }
  182. }
  183. return makeXlsxCell(cell.cellType, cellCoordinate, cellStyleId, cell.cellData)
  184. }
  185. func makeXlsxCell(cellType CellType, cellCoordinate string, cellStyleId int, cellData string) (xlsxC, error) {
  186. // documentation for the c.t (cell.Type) attribute:
  187. // b (Boolean): Cell containing a boolean.
  188. // d (Date): Cell contains a date in the ISO 8601 format.
  189. // e (Error): Cell containing an error.
  190. // inlineStr (Inline String): Cell containing an (inline) rich string, i.e., one not in the shared string table.
  191. // 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).
  192. // n (Number): Cell containing a number.
  193. // s (Shared String): Cell containing a shared string.
  194. // str (String): Cell containing a formula string.
  195. switch cellType {
  196. case CellTypeBool:
  197. return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "b", V: cellData}, nil
  198. // Dates are better represented using CellTyleNumeric and the date formatting
  199. //case CellTypeDate:
  200. //return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "d", V: cellData}, nil
  201. case CellTypeError:
  202. return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "e", V: cellData}, nil
  203. case CellTypeInline:
  204. return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "inlineStr", Is: &xlsxSI{T: cellData}}, nil
  205. case CellTypeNumeric:
  206. return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "n", V: cellData}, nil
  207. case CellTypeString:
  208. // TODO Currently shared strings are types as inline strings
  209. return xlsxC{XMLName: xml.Name{Local: "c"}, R: cellCoordinate, S: cellStyleId, T: "inlineStr", Is: &xlsxSI{T: cellData}}, nil
  210. // TODO currently not supported
  211. // case CellTypeStringFormula:
  212. // return xlsxC{}, UnsupportedCellTypeError
  213. default:
  214. return xlsxC{}, UnsupportedCellTypeError
  215. }
  216. }
  217. // Error reports any error that has occurred during a previous Write or Flush.
  218. func (sf *StreamFile) Error() error {
  219. return sf.err
  220. }
  221. func (sf *StreamFile) Flush() {
  222. if sf.err != nil {
  223. sf.err = sf.zipWriter.Flush()
  224. }
  225. }
  226. // NextSheet will switch to the next sheet. Sheets are selected in the same order they were added.
  227. // Once you leave a sheet, you cannot return to it.
  228. func (sf *StreamFile) NextSheet() error {
  229. if sf.err != nil {
  230. return sf.err
  231. }
  232. var sheetIndex int
  233. if sf.currentSheet != nil {
  234. if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) {
  235. sf.err = AlreadyOnLastSheetError
  236. return AlreadyOnLastSheetError
  237. }
  238. if err := sf.writeSheetEnd(); err != nil {
  239. sf.currentSheet = nil
  240. sf.err = err
  241. return err
  242. }
  243. sheetIndex = sf.currentSheet.index
  244. }
  245. sheetIndex++
  246. sf.currentSheet = &streamSheet{
  247. index: sheetIndex,
  248. columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols),
  249. styleIds: sf.styleIds[sheetIndex-1],
  250. rowCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Rows),
  251. }
  252. sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix
  253. fileWriter, err := sf.zipWriter.Create(sheetPath)
  254. if err != nil {
  255. sf.err = err
  256. return err
  257. }
  258. sf.currentSheet.writer = fileWriter
  259. if err := sf.writeSheetStart(); err != nil {
  260. sf.err = err
  261. return err
  262. }
  263. return nil
  264. }
  265. // Close closes the Stream File.
  266. // Any sheets that have not yet been written to will have an empty sheet created for them.
  267. func (sf *StreamFile) Close() error {
  268. if sf.err != nil {
  269. return sf.err
  270. }
  271. // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them.
  272. // XLSX readers may error if the sheets registered in the metadata are not present in the file.
  273. if sf.currentSheet != nil {
  274. for sf.currentSheet.index < len(sf.xlsxFile.Sheets) {
  275. if err := sf.NextSheet(); err != nil {
  276. sf.err = err
  277. return err
  278. }
  279. }
  280. // Write the end of the last sheet.
  281. if err := sf.writeSheetEnd(); err != nil {
  282. sf.err = err
  283. return err
  284. }
  285. }
  286. err := sf.zipWriter.Close()
  287. if err != nil {
  288. sf.err = err
  289. }
  290. return err
  291. }
  292. // writeSheetStart will write the start of the Sheet's XML
  293. func (sf *StreamFile) writeSheetStart() error {
  294. if sf.currentSheet == nil {
  295. return NoCurrentSheetError
  296. }
  297. return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1])
  298. }
  299. // writeSheetEnd will write the end of the Sheet's XML
  300. func (sf *StreamFile) writeSheetEnd() error {
  301. if sf.currentSheet == nil {
  302. return NoCurrentSheetError
  303. }
  304. if err := sf.currentSheet.write(endSheetDataTag); err != nil {
  305. return err
  306. }
  307. return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1])
  308. }
  309. func (ss *streamSheet) write(data string) error {
  310. _, err := ss.writer.Write([]byte(data))
  311. return err
  312. }