stream.go 14 KB

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