stream_file.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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. }
  18. type streamSheet struct {
  19. // sheetIndex is the XLSX sheet index, which starts at 1
  20. index int
  21. // The number of rows that have been written to the sheet so far
  22. rowCount int
  23. // The number of columns in the sheet
  24. columnCount int
  25. // The writer to write to this sheet's file in the XLSX Zip file
  26. writer io.Writer
  27. styleIds []int
  28. }
  29. var (
  30. NoCurrentSheetError = errors.New("no Current Sheet")
  31. 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")
  32. AlreadyOnLastSheetError = errors.New("NextSheet() called, but already on last sheet")
  33. )
  34. // Write will write a row of cells to the current sheet. Every call to Write on the same sheet must contain the
  35. // same number of cells as the header provided when the sheet was created or an error will be returned. This function
  36. // will always trigger a flush on success. Currently the only supported data type is string data.
  37. func (sf *StreamFile) Write(cells []string) error {
  38. if sf.err != nil {
  39. return sf.err
  40. }
  41. err := sf.write(cells)
  42. if err != nil {
  43. sf.err = err
  44. return err
  45. }
  46. return sf.zipWriter.Flush()
  47. }
  48. func (sf *StreamFile) WriteAll(records [][]string) error {
  49. if sf.err != nil {
  50. return sf.err
  51. }
  52. for _, row := range records {
  53. err := sf.write(row)
  54. if err != nil {
  55. sf.err = err
  56. return err
  57. }
  58. }
  59. return sf.zipWriter.Flush()
  60. }
  61. func (sf *StreamFile) write(cells []string) error {
  62. if sf.currentSheet == nil {
  63. return NoCurrentSheetError
  64. }
  65. if len(cells) != sf.currentSheet.columnCount {
  66. return WrongNumberOfRowsError
  67. }
  68. sf.currentSheet.rowCount++
  69. if err := sf.currentSheet.write(`<row r="` + strconv.Itoa(sf.currentSheet.rowCount) + `">`); err != nil {
  70. return err
  71. }
  72. for colIndex, cellData := range cells {
  73. // documentation for the c.t (cell.Type) attribute:
  74. // b (Boolean): Cell containing a boolean.
  75. // d (Date): Cell contains a date in the ISO 8601 format.
  76. // e (Error): Cell containing an error.
  77. // inlineStr (Inline String): Cell containing an (inline) rich string, i.e., one not in the shared string table.
  78. // 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).
  79. // n (Number): Cell containing a number.
  80. // s (Shared String): Cell containing a shared string.
  81. // str (String): Cell containing a formula string.
  82. cellCoordinate := GetCellIDStringFromCoords(colIndex, sf.currentSheet.rowCount-1)
  83. cellType := "inlineStr"
  84. cellOpen := `<c r="` + cellCoordinate + `" t="` + cellType + `"`
  85. // Add in the style id if the cell isn't using the default style
  86. if colIndex < len(sf.currentSheet.styleIds) && sf.currentSheet.styleIds[colIndex] != 0 {
  87. cellOpen += ` s="` + strconv.Itoa(sf.currentSheet.styleIds[colIndex]) + `"`
  88. }
  89. cellOpen += `><is><t>`
  90. cellClose := `</t></is></c>`
  91. if err := sf.currentSheet.write(cellOpen); err != nil {
  92. return err
  93. }
  94. if err := xml.EscapeText(sf.currentSheet.writer, []byte(cellData)); err != nil {
  95. return err
  96. }
  97. if err := sf.currentSheet.write(cellClose); err != nil {
  98. return err
  99. }
  100. }
  101. if err := sf.currentSheet.write(`</row>`); err != nil {
  102. return err
  103. }
  104. return sf.zipWriter.Flush()
  105. }
  106. // Error reports any error that has occurred during a previous Write or Flush.
  107. func (sf *StreamFile) Error() error {
  108. return sf.err
  109. }
  110. func (sf *StreamFile) Flush() {
  111. if sf.err != nil {
  112. sf.err = sf.zipWriter.Flush()
  113. }
  114. }
  115. // NextSheet will switch to the next sheet. Sheets are selected in the same order they were added.
  116. // Once you leave a sheet, you cannot return to it.
  117. func (sf *StreamFile) NextSheet() error {
  118. if sf.err != nil {
  119. return sf.err
  120. }
  121. var sheetIndex int
  122. if sf.currentSheet != nil {
  123. if sf.currentSheet.index >= len(sf.xlsxFile.Sheets) {
  124. sf.err = AlreadyOnLastSheetError
  125. return AlreadyOnLastSheetError
  126. }
  127. if err := sf.writeSheetEnd(); err != nil {
  128. sf.currentSheet = nil
  129. sf.err = err
  130. return err
  131. }
  132. sheetIndex = sf.currentSheet.index
  133. }
  134. sheetIndex++
  135. sf.currentSheet = &streamSheet{
  136. index: sheetIndex,
  137. columnCount: len(sf.xlsxFile.Sheets[sheetIndex-1].Cols),
  138. styleIds: sf.styleIds[sheetIndex-1],
  139. rowCount: 1,
  140. }
  141. sheetPath := sheetFilePathPrefix + strconv.Itoa(sf.currentSheet.index) + sheetFilePathSuffix
  142. fileWriter, err := sf.zipWriter.Create(sheetPath)
  143. if err != nil {
  144. sf.err = err
  145. return err
  146. }
  147. sf.currentSheet.writer = fileWriter
  148. if err := sf.writeSheetStart(); err != nil {
  149. sf.err = err
  150. return err
  151. }
  152. return nil
  153. }
  154. // Close closes the Stream File.
  155. // Any sheets that have not yet been written to will have an empty sheet created for them.
  156. func (sf *StreamFile) Close() error {
  157. if sf.err != nil {
  158. return sf.err
  159. }
  160. // If there are sheets that have not been written yet, call NextSheet() which will add files to the zip for them.
  161. // XLSX readers may error if the sheets registered in the metadata are not present in the file.
  162. if sf.currentSheet != nil {
  163. for sf.currentSheet.index < len(sf.xlsxFile.Sheets) {
  164. if err := sf.NextSheet(); err != nil {
  165. sf.err = err
  166. return err
  167. }
  168. }
  169. // Write the end of the last sheet.
  170. if err := sf.writeSheetEnd(); err != nil {
  171. sf.err = err
  172. return err
  173. }
  174. }
  175. err := sf.zipWriter.Close()
  176. if err != nil {
  177. sf.err = err
  178. }
  179. return err
  180. }
  181. // writeSheetStart will write the start of the Sheet's XML
  182. func (sf *StreamFile) writeSheetStart() error {
  183. if sf.currentSheet == nil {
  184. return NoCurrentSheetError
  185. }
  186. return sf.currentSheet.write(sf.sheetXmlPrefix[sf.currentSheet.index-1])
  187. }
  188. // writeSheetEnd will write the end of the Sheet's XML
  189. func (sf *StreamFile) writeSheetEnd() error {
  190. if sf.currentSheet == nil {
  191. return NoCurrentSheetError
  192. }
  193. if err := sf.currentSheet.write(endSheetDataTag); err != nil {
  194. return err
  195. }
  196. return sf.currentSheet.write(sf.sheetXmlSuffix[sf.currentSheet.index-1])
  197. }
  198. func (ss *streamSheet) write(data string) error {
  199. _, err := ss.writer.Write([]byte(data))
  200. return err
  201. }