stream.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. // Copyright 2016 - 2021 The excelize Authors. All rights reserved. Use of
  2. // this source code is governed by a BSD-style license that can be found in
  3. // the LICENSE file.
  4. //
  5. // Package excelize providing a set of functions that allow you to write to
  6. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  7. // spreadsheet documents generated by Microsoft Exce™ 2007 and later. Supports
  8. // complex components by high compatibility, and provided streaming API for
  9. // generating or reading data from a worksheet with huge amounts of data. This
  10. // library needs Go version 1.10 or later.
  11. package excelize
  12. import (
  13. "bytes"
  14. "encoding/xml"
  15. "fmt"
  16. "io"
  17. "io/ioutil"
  18. "os"
  19. "reflect"
  20. "strconv"
  21. "strings"
  22. "time"
  23. )
  24. // StreamWriter defined the type of stream writer.
  25. type StreamWriter struct {
  26. File *File
  27. Sheet string
  28. SheetID int
  29. worksheet *xlsxWorksheet
  30. rawData bufferedWriter
  31. tableParts string
  32. }
  33. // NewStreamWriter return stream writer struct by given worksheet name for
  34. // generate new worksheet with large amounts of data. Note that after set
  35. // rows, you must call the 'Flush' method to end the streaming writing
  36. // process and ensure that the order of line numbers is ascending, the common
  37. // API and stream API can't be work mixed to writing data on the worksheets.
  38. // For example, set data for worksheet of size 102400 rows x 50 columns with
  39. // numbers and style:
  40. //
  41. // file := excelize.NewFile()
  42. // streamWriter, err := file.NewStreamWriter("Sheet1")
  43. // if err != nil {
  44. // fmt.Println(err)
  45. // }
  46. // styleID, err := file.NewStyle(`{"font":{"color":"#777777"}}`)
  47. // if err != nil {
  48. // fmt.Println(err)
  49. // }
  50. // if err := streamWriter.SetRow("A1", []interface{}{excelize.Cell{StyleID: styleID, Value: "Data"}}); err != nil {
  51. // fmt.Println(err)
  52. // }
  53. // for rowID := 2; rowID <= 102400; rowID++ {
  54. // row := make([]interface{}, 50)
  55. // for colID := 0; colID < 50; colID++ {
  56. // row[colID] = rand.Intn(640000)
  57. // }
  58. // cell, _ := excelize.CoordinatesToCellName(1, rowID)
  59. // if err := streamWriter.SetRow(cell, row); err != nil {
  60. // fmt.Println(err)
  61. // }
  62. // }
  63. // if err := streamWriter.Flush(); err != nil {
  64. // fmt.Println(err)
  65. // }
  66. // if err := file.SaveAs("Book1.xlsx"); err != nil {
  67. // fmt.Println(err)
  68. // }
  69. //
  70. func (f *File) NewStreamWriter(sheet string) (*StreamWriter, error) {
  71. sheetID := f.getSheetID(sheet)
  72. if sheetID == -1 {
  73. return nil, fmt.Errorf("sheet %s is not exist", sheet)
  74. }
  75. sw := &StreamWriter{
  76. File: f,
  77. Sheet: sheet,
  78. SheetID: sheetID,
  79. }
  80. var err error
  81. sw.worksheet, err = f.workSheetReader(sheet)
  82. if err != nil {
  83. return nil, err
  84. }
  85. sheetXML := fmt.Sprintf("xl/worksheets/sheet%d.xml", sw.SheetID)
  86. if f.streams == nil {
  87. f.streams = make(map[string]*StreamWriter)
  88. }
  89. f.streams[sheetXML] = sw
  90. _, _ = sw.rawData.WriteString(XMLHeader + `<worksheet` + templateNamespaceIDMap)
  91. bulkAppendFields(&sw.rawData, sw.worksheet, 2, 6)
  92. _, _ = sw.rawData.WriteString(`<sheetData>`)
  93. return sw, err
  94. }
  95. // AddTable creates an Excel table for the StreamWriter using the given
  96. // coordinate area and format set. For example, create a table of A1:D5:
  97. //
  98. // err := sw.AddTable("A1", "D5", ``)
  99. //
  100. // Create a table of F2:H6 with format set:
  101. //
  102. // err := sw.AddTable("F2", "H6", `{"table_name":"table","table_style":"TableStyleMedium2","show_first_column":true,"show_last_column":true,"show_row_stripes":false,"show_column_stripes":true}`)
  103. //
  104. // Note that the table must be at least two lines including the header. The
  105. // header cells must contain strings and must be unique.
  106. //
  107. // Currently only one table is allowed for a StreamWriter. AddTable must be
  108. // called after the rows are written but before Flush.
  109. //
  110. // See File.AddTable for details on the table format.
  111. func (sw *StreamWriter) AddTable(hcell, vcell, format string) error {
  112. formatSet, err := parseFormatTableSet(format)
  113. if err != nil {
  114. return err
  115. }
  116. coordinates, err := areaRangeToCoordinates(hcell, vcell)
  117. if err != nil {
  118. return err
  119. }
  120. _ = sortCoordinates(coordinates)
  121. // Correct the minimum number of rows, the table at least two lines.
  122. if coordinates[1] == coordinates[3] {
  123. coordinates[3]++
  124. }
  125. // Correct table reference coordinate area, such correct C1:B3 to B1:C3.
  126. ref, err := sw.File.coordinatesToAreaRef(coordinates)
  127. if err != nil {
  128. return err
  129. }
  130. // create table columns using the first row
  131. tableHeaders, err := sw.getRowValues(coordinates[1], coordinates[0], coordinates[2])
  132. if err != nil {
  133. return err
  134. }
  135. tableColumn := make([]*xlsxTableColumn, len(tableHeaders))
  136. for i, name := range tableHeaders {
  137. tableColumn[i] = &xlsxTableColumn{
  138. ID: i + 1,
  139. Name: name,
  140. }
  141. }
  142. tableID := sw.File.countTables() + 1
  143. name := formatSet.TableName
  144. if name == "" {
  145. name = "Table" + strconv.Itoa(tableID)
  146. }
  147. table := xlsxTable{
  148. XMLNS: NameSpaceSpreadSheet.Value,
  149. ID: tableID,
  150. Name: name,
  151. DisplayName: name,
  152. Ref: ref,
  153. AutoFilter: &xlsxAutoFilter{
  154. Ref: ref,
  155. },
  156. TableColumns: &xlsxTableColumns{
  157. Count: len(tableColumn),
  158. TableColumn: tableColumn,
  159. },
  160. TableStyleInfo: &xlsxTableStyleInfo{
  161. Name: formatSet.TableStyle,
  162. ShowFirstColumn: formatSet.ShowFirstColumn,
  163. ShowLastColumn: formatSet.ShowLastColumn,
  164. ShowRowStripes: formatSet.ShowRowStripes,
  165. ShowColumnStripes: formatSet.ShowColumnStripes,
  166. },
  167. }
  168. sheetRelationshipsTableXML := "../tables/table" + strconv.Itoa(tableID) + ".xml"
  169. tableXML := strings.Replace(sheetRelationshipsTableXML, "..", "xl", -1)
  170. // Add first table for given sheet.
  171. sheetPath := sw.File.sheetMap[trimSheetName(sw.Sheet)]
  172. sheetRels := "xl/worksheets/_rels/" + strings.TrimPrefix(sheetPath, "xl/worksheets/") + ".rels"
  173. rID := sw.File.addRels(sheetRels, SourceRelationshipTable, sheetRelationshipsTableXML, "")
  174. sw.tableParts = fmt.Sprintf(`<tableParts count="1"><tablePart r:id="rId%d"></tablePart></tableParts>`, rID)
  175. sw.File.addContentTypePart(tableID, "table")
  176. b, _ := xml.Marshal(table)
  177. sw.File.saveFileList(tableXML, b)
  178. return nil
  179. }
  180. // Extract values from a row in the StreamWriter.
  181. func (sw *StreamWriter) getRowValues(hrow, hcol, vcol int) (res []string, err error) {
  182. res = make([]string, vcol-hcol+1)
  183. r, err := sw.rawData.Reader()
  184. if err != nil {
  185. return nil, err
  186. }
  187. dec := sw.File.xmlNewDecoder(r)
  188. for {
  189. token, err := dec.Token()
  190. if err == io.EOF {
  191. return res, nil
  192. }
  193. if err != nil {
  194. return nil, err
  195. }
  196. startElement, ok := getRowElement(token, hrow)
  197. if !ok {
  198. continue
  199. }
  200. // decode cells
  201. var row xlsxRow
  202. if err := dec.DecodeElement(&row, &startElement); err != nil {
  203. return nil, err
  204. }
  205. for _, c := range row.C {
  206. col, _, err := CellNameToCoordinates(c.R)
  207. if err != nil {
  208. return nil, err
  209. }
  210. if col < hcol || col > vcol {
  211. continue
  212. }
  213. res[col-hcol] = c.V
  214. }
  215. return res, nil
  216. }
  217. }
  218. // Check if the token is an XLSX row with the matching row number.
  219. func getRowElement(token xml.Token, hrow int) (startElement xml.StartElement, ok bool) {
  220. startElement, ok = token.(xml.StartElement)
  221. if !ok {
  222. return
  223. }
  224. ok = startElement.Name.Local == "row"
  225. if !ok {
  226. return
  227. }
  228. ok = false
  229. for _, attr := range startElement.Attr {
  230. if attr.Name.Local != "r" {
  231. continue
  232. }
  233. row, _ := strconv.Atoi(attr.Value)
  234. if row == hrow {
  235. ok = true
  236. return
  237. }
  238. }
  239. return
  240. }
  241. // Cell can be used directly in StreamWriter.SetRow to specify a style and
  242. // a value.
  243. type Cell struct {
  244. StyleID int
  245. Value interface{}
  246. }
  247. // SetRow writes an array to stream rows by giving a worksheet name, starting
  248. // coordinate and a pointer to an array of values. Note that you must call the
  249. // 'Flush' method to end the streaming writing process.
  250. //
  251. // As a special case, if Cell is used as a value, then the Cell.StyleID will be
  252. // applied to that cell.
  253. func (sw *StreamWriter) SetRow(axis string, values []interface{}) error {
  254. col, row, err := CellNameToCoordinates(axis)
  255. if err != nil {
  256. return err
  257. }
  258. fmt.Fprintf(&sw.rawData, `<row r="%d">`, row)
  259. for i, val := range values {
  260. axis, err := CoordinatesToCellName(col+i, row)
  261. if err != nil {
  262. return err
  263. }
  264. c := xlsxC{R: axis}
  265. if v, ok := val.(Cell); ok {
  266. c.S = v.StyleID
  267. val = v.Value
  268. } else if v, ok := val.(*Cell); ok && v != nil {
  269. c.S = v.StyleID
  270. val = v.Value
  271. }
  272. if err = setCellValFunc(&c, val); err != nil {
  273. _, _ = sw.rawData.WriteString(`</row>`)
  274. return err
  275. }
  276. writeCell(&sw.rawData, c)
  277. }
  278. _, _ = sw.rawData.WriteString(`</row>`)
  279. return sw.rawData.Sync()
  280. }
  281. // setCellValFunc provides a function to set value of a cell.
  282. func setCellValFunc(c *xlsxC, val interface{}) (err error) {
  283. switch val := val.(type) {
  284. case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
  285. err = setCellIntFunc(c, val)
  286. case float32:
  287. c.T, c.V = setCellFloat(float64(val), -1, 32)
  288. case float64:
  289. c.T, c.V = setCellFloat(val, -1, 64)
  290. case string:
  291. c.T, c.V, c.XMLSpace = setCellStr(val)
  292. case []byte:
  293. c.T, c.V, c.XMLSpace = setCellStr(string(val))
  294. case time.Duration:
  295. c.T, c.V = setCellDuration(val)
  296. case time.Time:
  297. c.T, c.V, _, err = setCellTime(val)
  298. case bool:
  299. c.T, c.V = setCellBool(val)
  300. case nil:
  301. c.T, c.V, c.XMLSpace = setCellStr("")
  302. default:
  303. c.T, c.V, c.XMLSpace = setCellStr(fmt.Sprint(val))
  304. }
  305. return err
  306. }
  307. // setCellIntFunc is a wrapper of SetCellInt.
  308. func setCellIntFunc(c *xlsxC, val interface{}) (err error) {
  309. switch val := val.(type) {
  310. case int:
  311. c.T, c.V = setCellInt(val)
  312. case int8:
  313. c.T, c.V = setCellInt(int(val))
  314. case int16:
  315. c.T, c.V = setCellInt(int(val))
  316. case int32:
  317. c.T, c.V = setCellInt(int(val))
  318. case int64:
  319. c.T, c.V = setCellInt(int(val))
  320. case uint:
  321. c.T, c.V = setCellInt(int(val))
  322. case uint8:
  323. c.T, c.V = setCellInt(int(val))
  324. case uint16:
  325. c.T, c.V = setCellInt(int(val))
  326. case uint32:
  327. c.T, c.V = setCellInt(int(val))
  328. case uint64:
  329. c.T, c.V = setCellInt(int(val))
  330. default:
  331. }
  332. return
  333. }
  334. func writeCell(buf *bufferedWriter, c xlsxC) {
  335. _, _ = buf.WriteString(`<c`)
  336. if c.XMLSpace.Value != "" {
  337. fmt.Fprintf(buf, ` xml:%s="%s"`, c.XMLSpace.Name.Local, c.XMLSpace.Value)
  338. }
  339. fmt.Fprintf(buf, ` r="%s"`, c.R)
  340. if c.S != 0 {
  341. fmt.Fprintf(buf, ` s="%d"`, c.S)
  342. }
  343. if c.T != "" {
  344. fmt.Fprintf(buf, ` t="%s"`, c.T)
  345. }
  346. _, _ = buf.WriteString(`>`)
  347. if c.V != "" {
  348. _, _ = buf.WriteString(`<v>`)
  349. _ = xml.EscapeText(buf, []byte(c.V))
  350. _, _ = buf.WriteString(`</v>`)
  351. }
  352. _, _ = buf.WriteString(`</c>`)
  353. }
  354. // Flush ending the streaming writing process.
  355. func (sw *StreamWriter) Flush() error {
  356. _, _ = sw.rawData.WriteString(`</sheetData>`)
  357. bulkAppendFields(&sw.rawData, sw.worksheet, 8, 38)
  358. _, _ = sw.rawData.WriteString(sw.tableParts)
  359. bulkAppendFields(&sw.rawData, sw.worksheet, 40, 40)
  360. _, _ = sw.rawData.WriteString(`</worksheet>`)
  361. if err := sw.rawData.Flush(); err != nil {
  362. return err
  363. }
  364. sheetXML := fmt.Sprintf("xl/worksheets/sheet%d.xml", sw.SheetID)
  365. delete(sw.File.Sheet, sheetXML)
  366. delete(sw.File.checked, sheetXML)
  367. delete(sw.File.XLSX, sheetXML)
  368. return nil
  369. }
  370. // bulkAppendFields bulk-appends fields in a worksheet by specified field
  371. // names order range.
  372. func bulkAppendFields(w io.Writer, ws *xlsxWorksheet, from, to int) {
  373. s := reflect.ValueOf(ws).Elem()
  374. enc := xml.NewEncoder(w)
  375. for i := 0; i < s.NumField(); i++ {
  376. if from <= i && i <= to {
  377. _ = enc.Encode(s.Field(i).Interface())
  378. }
  379. }
  380. }
  381. // bufferedWriter uses a temp file to store an extended buffer. Writes are
  382. // always made to an in-memory buffer, which will always succeed. The buffer
  383. // is written to the temp file with Sync, which may return an error.
  384. // Therefore, Sync should be periodically called and the error checked.
  385. type bufferedWriter struct {
  386. tmp *os.File
  387. buf bytes.Buffer
  388. }
  389. // Write to the in-memory buffer. The err is always nil.
  390. func (bw *bufferedWriter) Write(p []byte) (n int, err error) {
  391. return bw.buf.Write(p)
  392. }
  393. // WriteString wites to the in-memory buffer. The err is always nil.
  394. func (bw *bufferedWriter) WriteString(p string) (n int, err error) {
  395. return bw.buf.WriteString(p)
  396. }
  397. // Reader provides read-access to the underlying buffer/file.
  398. func (bw *bufferedWriter) Reader() (io.Reader, error) {
  399. if bw.tmp == nil {
  400. return bytes.NewReader(bw.buf.Bytes()), nil
  401. }
  402. if err := bw.Flush(); err != nil {
  403. return nil, err
  404. }
  405. fi, err := bw.tmp.Stat()
  406. if err != nil {
  407. return nil, err
  408. }
  409. // os.File.ReadAt does not affect the cursor position and is safe to use here
  410. return io.NewSectionReader(bw.tmp, 0, fi.Size()), nil
  411. }
  412. // Sync will write the in-memory buffer to a temp file, if the in-memory
  413. // buffer has grown large enough. Any error will be returned.
  414. func (bw *bufferedWriter) Sync() (err error) {
  415. // Try to use local storage
  416. const chunk = 1 << 24
  417. if bw.buf.Len() < chunk {
  418. return nil
  419. }
  420. if bw.tmp == nil {
  421. bw.tmp, err = ioutil.TempFile(os.TempDir(), "excelize-")
  422. if err != nil {
  423. // can not use local storage
  424. return nil
  425. }
  426. }
  427. return bw.Flush()
  428. }
  429. // Flush the entire in-memory buffer to the temp file, if a temp file is being
  430. // used.
  431. func (bw *bufferedWriter) Flush() error {
  432. if bw.tmp == nil {
  433. return nil
  434. }
  435. _, err := bw.buf.WriteTo(bw.tmp)
  436. if err != nil {
  437. return err
  438. }
  439. bw.buf.Reset()
  440. return nil
  441. }
  442. // Close the underlying temp file and reset the in-memory buffer.
  443. func (bw *bufferedWriter) Close() error {
  444. bw.buf.Reset()
  445. if bw.tmp == nil {
  446. return nil
  447. }
  448. defer os.Remove(bw.tmp.Name())
  449. return bw.tmp.Close()
  450. }