file.go 4.4 KB

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