file.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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. "archive/zip"
  14. "bytes"
  15. "fmt"
  16. "io"
  17. "os"
  18. )
  19. // NewFile provides a function to create new file by default template. For
  20. // example:
  21. //
  22. // f := NewFile()
  23. //
  24. func NewFile() *File {
  25. file := make(map[string][]byte)
  26. file["_rels/.rels"] = []byte(XMLHeader + templateRels)
  27. file["docProps/app.xml"] = []byte(XMLHeader + templateDocpropsApp)
  28. file["docProps/core.xml"] = []byte(XMLHeader + templateDocpropsCore)
  29. file["xl/_rels/workbook.xml.rels"] = []byte(XMLHeader + templateWorkbookRels)
  30. file["xl/theme/theme1.xml"] = []byte(XMLHeader + templateTheme)
  31. file["xl/worksheets/sheet1.xml"] = []byte(XMLHeader + templateSheet)
  32. file["xl/styles.xml"] = []byte(XMLHeader + templateStyles)
  33. file["xl/workbook.xml"] = []byte(XMLHeader + templateWorkbook)
  34. file["[Content_Types].xml"] = []byte(XMLHeader + templateContentTypes)
  35. f := newFile()
  36. f.SheetCount, f.XLSX = 1, file
  37. f.CalcChain = f.calcChainReader()
  38. f.Comments = make(map[string]*xlsxComments)
  39. f.ContentTypes = f.contentTypesReader()
  40. f.Drawings = make(map[string]*xlsxWsDr)
  41. f.Styles = f.stylesReader()
  42. f.DecodeVMLDrawing = make(map[string]*decodeVmlDrawing)
  43. f.VMLDrawing = make(map[string]*vmlDrawing)
  44. f.WorkBook = f.workbookReader()
  45. f.Relationships = make(map[string]*xlsxRelationships)
  46. f.Relationships["xl/_rels/workbook.xml.rels"] = f.relsReader("xl/_rels/workbook.xml.rels")
  47. f.Sheet["xl/worksheets/sheet1.xml"], _ = f.workSheetReader("Sheet1")
  48. f.sheetMap["Sheet1"] = "xl/worksheets/sheet1.xml"
  49. f.Theme = f.themeReader()
  50. return f
  51. }
  52. // Save provides a function to override the spreadsheet with origin path.
  53. func (f *File) Save() error {
  54. if f.Path == "" {
  55. return fmt.Errorf("no path defined for file, consider File.WriteTo or File.Write")
  56. }
  57. return f.SaveAs(f.Path)
  58. }
  59. // SaveAs provides a function to create or update to an spreadsheet at the
  60. // provided path.
  61. func (f *File) SaveAs(name string, opt ...Options) error {
  62. if len(name) > MaxFileNameLength {
  63. return ErrMaxFileNameLength
  64. }
  65. file, err := os.OpenFile(name, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
  66. if err != nil {
  67. return err
  68. }
  69. defer file.Close()
  70. f.options = nil
  71. for _, o := range opt {
  72. f.options = &o
  73. }
  74. return f.Write(file)
  75. }
  76. // Write provides a function to write to an io.Writer.
  77. func (f *File) Write(w io.Writer) error {
  78. _, err := f.WriteTo(w)
  79. return err
  80. }
  81. // WriteTo implements io.WriterTo to write the file.
  82. func (f *File) WriteTo(w io.Writer) (int64, error) {
  83. buf, err := f.WriteToBuffer()
  84. if err != nil {
  85. return 0, err
  86. }
  87. return buf.WriteTo(w)
  88. }
  89. // WriteToBuffer provides a function to get bytes.Buffer from the saved file.
  90. func (f *File) WriteToBuffer() (*bytes.Buffer, error) {
  91. buf := new(bytes.Buffer)
  92. zw := zip.NewWriter(buf)
  93. f.calcChainWriter()
  94. f.commentsWriter()
  95. f.contentTypesWriter()
  96. f.drawingsWriter()
  97. f.vmlDrawingWriter()
  98. f.workBookWriter()
  99. f.workSheetWriter()
  100. f.relsWriter()
  101. f.sharedStringsWriter()
  102. f.styleSheetWriter()
  103. for path, stream := range f.streams {
  104. fi, err := zw.Create(path)
  105. if err != nil {
  106. zw.Close()
  107. return buf, err
  108. }
  109. var from io.Reader
  110. from, err = stream.rawData.Reader()
  111. if err != nil {
  112. stream.rawData.Close()
  113. return buf, err
  114. }
  115. _, err = io.Copy(fi, from)
  116. if err != nil {
  117. zw.Close()
  118. return buf, err
  119. }
  120. stream.rawData.Close()
  121. }
  122. for path, content := range f.XLSX {
  123. if _, ok := f.streams[path]; ok {
  124. continue
  125. }
  126. fi, err := zw.Create(path)
  127. if err != nil {
  128. zw.Close()
  129. return buf, err
  130. }
  131. _, err = fi.Write(content)
  132. if err != nil {
  133. zw.Close()
  134. return buf, err
  135. }
  136. }
  137. if f.options != nil && f.options.Password != "" {
  138. if err := zw.Close(); err != nil {
  139. return buf, err
  140. }
  141. b, err := Encrypt(buf.Bytes(), f.options)
  142. if err != nil {
  143. return buf, err
  144. }
  145. buf.Reset()
  146. buf.Write(b)
  147. return buf, nil
  148. }
  149. return buf, zw.Close()
  150. }