stream.go 16 KB

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