stream_file.go 12 KB

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