stream.go 14 KB

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