stream.go 14 KB

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