excelize.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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. // Package excelize providing a set of functions that allow you to write to
  5. // and read from XLSX / XLSM / XLTM files. Supports reading and writing
  6. // spreadsheet documents generated by Microsoft Excel™ 2007 and later. Supports
  7. // complex components by high compatibility, and provided streaming API for
  8. // generating or reading data from a worksheet with huge amounts of data. This
  9. // library needs Go version 1.15 or later.
  10. //
  11. // See https://xuri.me/excelize for more information about this package.
  12. package excelize
  13. import (
  14. "archive/zip"
  15. "bytes"
  16. "encoding/xml"
  17. "fmt"
  18. "io"
  19. "io/ioutil"
  20. "os"
  21. "path"
  22. "strconv"
  23. "strings"
  24. "sync"
  25. "golang.org/x/net/html/charset"
  26. )
  27. // File define a populated spreadsheet file struct.
  28. type File struct {
  29. sync.Mutex
  30. options *Options
  31. xmlAttr map[string][]xml.Attr
  32. checked map[string]bool
  33. sheetMap map[string]string
  34. streams map[string]*StreamWriter
  35. CalcChain *xlsxCalcChain
  36. Comments map[string]*xlsxComments
  37. ContentTypes *xlsxTypes
  38. Drawings map[string]*xlsxWsDr
  39. Path string
  40. SharedStrings *xlsxSST
  41. sharedStringsMap map[string]int
  42. Sheet map[string]*xlsxWorksheet
  43. SheetCount int
  44. Styles *xlsxStyleSheet
  45. Theme *xlsxTheme
  46. DecodeVMLDrawing map[string]*decodeVmlDrawing
  47. VMLDrawing map[string]*vmlDrawing
  48. WorkBook *xlsxWorkbook
  49. Relationships map[string]*xlsxRelationships
  50. XLSX map[string][]byte
  51. CharsetReader charsetTranscoderFn
  52. }
  53. type charsetTranscoderFn func(charset string, input io.Reader) (rdr io.Reader, err error)
  54. // Options define the options for open spreadsheet.
  55. type Options struct {
  56. Password string
  57. }
  58. // OpenFile take the name of an spreadsheet file and returns a populated spreadsheet file struct
  59. // for it. For example, open spreadsheet with password protection:
  60. //
  61. // f, err := excelize.OpenFile("Book1.xlsx", excelize.Options{Password: "password"})
  62. // if err != nil {
  63. // return
  64. // }
  65. //
  66. // Note that the excelize just support decrypt and not support encrypt currently, the spreadsheet
  67. // saved by Save and SaveAs will be without password unprotected.
  68. func OpenFile(filename string, opt ...Options) (*File, error) {
  69. file, err := os.Open(filename)
  70. if err != nil {
  71. return nil, err
  72. }
  73. defer file.Close()
  74. f, err := OpenReader(file, opt...)
  75. if err != nil {
  76. return nil, err
  77. }
  78. f.Path = filename
  79. return f, nil
  80. }
  81. // newFile is object builder
  82. func newFile() *File {
  83. return &File{
  84. xmlAttr: make(map[string][]xml.Attr),
  85. checked: make(map[string]bool),
  86. sheetMap: make(map[string]string),
  87. Comments: make(map[string]*xlsxComments),
  88. Drawings: make(map[string]*xlsxWsDr),
  89. sharedStringsMap: make(map[string]int),
  90. Sheet: make(map[string]*xlsxWorksheet),
  91. DecodeVMLDrawing: make(map[string]*decodeVmlDrawing),
  92. VMLDrawing: make(map[string]*vmlDrawing),
  93. Relationships: make(map[string]*xlsxRelationships),
  94. CharsetReader: charset.NewReaderLabel,
  95. }
  96. }
  97. // OpenReader read data stream from io.Reader and return a populated
  98. // spreadsheet file.
  99. func OpenReader(r io.Reader, opt ...Options) (*File, error) {
  100. b, err := ioutil.ReadAll(r)
  101. if err != nil {
  102. return nil, err
  103. }
  104. f := newFile()
  105. if bytes.Contains(b, oleIdentifier) && len(opt) > 0 {
  106. for _, o := range opt {
  107. f.options = &o
  108. }
  109. b, err = Decrypt(b, f.options)
  110. if err != nil {
  111. return nil, fmt.Errorf("decrypted file failed")
  112. }
  113. }
  114. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  115. if err != nil {
  116. return nil, err
  117. }
  118. file, sheetCount, err := ReadZipReader(zr)
  119. if err != nil {
  120. return nil, err
  121. }
  122. f.SheetCount, f.XLSX = sheetCount, file
  123. f.CalcChain = f.calcChainReader()
  124. f.sheetMap = f.getSheetMap()
  125. f.Styles = f.stylesReader()
  126. f.Theme = f.themeReader()
  127. return f, nil
  128. }
  129. // CharsetTranscoder Set user defined codepage transcoder function for open
  130. // XLSX from non UTF-8 encoding.
  131. func (f *File) CharsetTranscoder(fn charsetTranscoderFn) *File { f.CharsetReader = fn; return f }
  132. // Creates new XML decoder with charset reader.
  133. func (f *File) xmlNewDecoder(rdr io.Reader) (ret *xml.Decoder) {
  134. ret = xml.NewDecoder(rdr)
  135. ret.CharsetReader = f.CharsetReader
  136. return
  137. }
  138. // setDefaultTimeStyle provides a function to set default numbers format for
  139. // time.Time type cell value by given worksheet name, cell coordinates and
  140. // number format code.
  141. func (f *File) setDefaultTimeStyle(sheet, axis string, format int) error {
  142. s, err := f.GetCellStyle(sheet, axis)
  143. if err != nil {
  144. return err
  145. }
  146. if s == 0 {
  147. style, _ := f.NewStyle(&Style{NumFmt: format})
  148. err = f.SetCellStyle(sheet, axis, axis, style)
  149. }
  150. return err
  151. }
  152. // workSheetReader provides a function to get the pointer to the structure
  153. // after deserialization by given worksheet name.
  154. func (f *File) workSheetReader(sheet string) (ws *xlsxWorksheet, err error) {
  155. f.Lock()
  156. defer f.Unlock()
  157. var (
  158. name string
  159. ok bool
  160. )
  161. if name, ok = f.sheetMap[trimSheetName(sheet)]; !ok {
  162. err = fmt.Errorf("sheet %s is not exist", sheet)
  163. return
  164. }
  165. if ws = f.Sheet[name]; f.Sheet[name] == nil {
  166. if strings.HasPrefix(name, "xl/chartsheets") {
  167. err = fmt.Errorf("sheet %s is chart sheet", sheet)
  168. return
  169. }
  170. ws = new(xlsxWorksheet)
  171. if _, ok := f.xmlAttr[name]; !ok {
  172. d := f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(name))))
  173. f.xmlAttr[name] = append(f.xmlAttr[name], getRootElement(d)...)
  174. }
  175. if err = f.xmlNewDecoder(bytes.NewReader(namespaceStrictToTransitional(f.readXML(name)))).
  176. Decode(ws); err != nil && err != io.EOF {
  177. err = fmt.Errorf("xml decode error: %s", err)
  178. return
  179. }
  180. err = nil
  181. if f.checked == nil {
  182. f.checked = make(map[string]bool)
  183. }
  184. if ok = f.checked[name]; !ok {
  185. checkSheet(ws)
  186. if err = checkRow(ws); err != nil {
  187. return
  188. }
  189. f.checked[name] = true
  190. }
  191. f.Sheet[name] = ws
  192. }
  193. return
  194. }
  195. // checkSheet provides a function to fill each row element and make that is
  196. // continuous in a worksheet of XML.
  197. func checkSheet(ws *xlsxWorksheet) {
  198. var row int
  199. for _, r := range ws.SheetData.Row {
  200. if r.R != 0 && r.R > row {
  201. row = r.R
  202. continue
  203. }
  204. if r.R != row {
  205. row++
  206. }
  207. }
  208. sheetData := xlsxSheetData{Row: make([]xlsxRow, row)}
  209. row = 0
  210. for _, r := range ws.SheetData.Row {
  211. if r.R == row {
  212. sheetData.Row[r.R-1].C = append(sheetData.Row[r.R-1].C, r.C...)
  213. continue
  214. }
  215. if r.R != 0 {
  216. sheetData.Row[r.R-1] = r
  217. row = r.R
  218. continue
  219. }
  220. row++
  221. r.R = row
  222. sheetData.Row[row-1] = r
  223. }
  224. for i := 1; i <= row; i++ {
  225. sheetData.Row[i-1].R = i
  226. }
  227. ws.SheetData = sheetData
  228. }
  229. // addRels provides a function to add relationships by given XML path,
  230. // relationship type, target and target mode.
  231. func (f *File) addRels(relPath, relType, target, targetMode string) int {
  232. var uniqPart = map[string]string{
  233. SourceRelationshipSharedStrings: "/xl/sharedStrings.xml",
  234. }
  235. rels := f.relsReader(relPath)
  236. if rels == nil {
  237. rels = &xlsxRelationships{}
  238. }
  239. var rID int
  240. for idx, rel := range rels.Relationships {
  241. ID, _ := strconv.Atoi(strings.TrimPrefix(rel.ID, "rId"))
  242. if ID > rID {
  243. rID = ID
  244. }
  245. if relType == rel.Type {
  246. if partName, ok := uniqPart[rel.Type]; ok {
  247. rels.Relationships[idx].Target = partName
  248. return rID
  249. }
  250. }
  251. }
  252. rID++
  253. var ID bytes.Buffer
  254. ID.WriteString("rId")
  255. ID.WriteString(strconv.Itoa(rID))
  256. rels.Relationships = append(rels.Relationships, xlsxRelationship{
  257. ID: ID.String(),
  258. Type: relType,
  259. Target: target,
  260. TargetMode: targetMode,
  261. })
  262. f.Relationships[relPath] = rels
  263. return rID
  264. }
  265. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  266. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  267. // cell have a linked value. Reference
  268. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating
  269. //
  270. // Notice: after open XLSX file Excel will be update linked value and generate
  271. // new value and will prompt save file or not.
  272. //
  273. // For example:
  274. //
  275. // <row r="19" spans="2:2">
  276. // <c r="B19">
  277. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  278. // <v>100</v>
  279. // </c>
  280. // </row>
  281. //
  282. // to
  283. //
  284. // <row r="19" spans="2:2">
  285. // <c r="B19">
  286. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  287. // </c>
  288. // </row>
  289. //
  290. func (f *File) UpdateLinkedValue() error {
  291. wb := f.workbookReader()
  292. // recalculate formulas
  293. wb.CalcPr = nil
  294. for _, name := range f.GetSheetList() {
  295. xlsx, err := f.workSheetReader(name)
  296. if err != nil {
  297. if err.Error() == fmt.Sprintf("sheet %s is chart sheet", trimSheetName(name)) {
  298. continue
  299. }
  300. return err
  301. }
  302. for indexR := range xlsx.SheetData.Row {
  303. for indexC, col := range xlsx.SheetData.Row[indexR].C {
  304. if col.F != nil && col.V != "" {
  305. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  306. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  307. }
  308. }
  309. }
  310. }
  311. return nil
  312. }
  313. // AddVBAProject provides the method to add vbaProject.bin file which contains
  314. // functions and/or macros. The file extension should be .xlsm. For example:
  315. //
  316. // if err := f.SetSheetPrOptions("Sheet1", excelize.CodeName("Sheet1")); err != nil {
  317. // fmt.Println(err)
  318. // }
  319. // if err := f.AddVBAProject("vbaProject.bin"); err != nil {
  320. // fmt.Println(err)
  321. // }
  322. // if err := f.SaveAs("macros.xlsm"); err != nil {
  323. // fmt.Println(err)
  324. // }
  325. //
  326. func (f *File) AddVBAProject(bin string) error {
  327. var err error
  328. // Check vbaProject.bin exists first.
  329. if _, err = os.Stat(bin); os.IsNotExist(err) {
  330. return fmt.Errorf("stat %s: no such file or directory", bin)
  331. }
  332. if path.Ext(bin) != ".bin" {
  333. return ErrAddVBAProject
  334. }
  335. f.setContentTypePartVBAProjectExtensions()
  336. wb := f.relsReader(f.getWorkbookRelsPath())
  337. var rID int
  338. var ok bool
  339. for _, rel := range wb.Relationships {
  340. if rel.Target == "vbaProject.bin" && rel.Type == SourceRelationshipVBAProject {
  341. ok = true
  342. continue
  343. }
  344. t, _ := strconv.Atoi(strings.TrimPrefix(rel.ID, "rId"))
  345. if t > rID {
  346. rID = t
  347. }
  348. }
  349. rID++
  350. if !ok {
  351. wb.Relationships = append(wb.Relationships, xlsxRelationship{
  352. ID: "rId" + strconv.Itoa(rID),
  353. Target: "vbaProject.bin",
  354. Type: SourceRelationshipVBAProject,
  355. })
  356. }
  357. file, _ := ioutil.ReadFile(bin)
  358. f.XLSX["xl/vbaProject.bin"] = file
  359. return err
  360. }
  361. // setContentTypePartVBAProjectExtensions provides a function to set the
  362. // content type for relationship parts and the main document part.
  363. func (f *File) setContentTypePartVBAProjectExtensions() {
  364. var ok bool
  365. content := f.contentTypesReader()
  366. for _, v := range content.Defaults {
  367. if v.Extension == "bin" {
  368. ok = true
  369. }
  370. }
  371. for idx, o := range content.Overrides {
  372. if o.PartName == "/xl/workbook.xml" {
  373. content.Overrides[idx].ContentType = ContentTypeMacro
  374. }
  375. }
  376. if !ok {
  377. content.Defaults = append(content.Defaults, xlsxDefault{
  378. Extension: "bin",
  379. ContentType: ContentTypeVBA,
  380. })
  381. }
  382. }