excelize.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  1. /*
  2. Package excelize providing a set of functions that allow you to write to
  3. and read from XLSX files. Support reads and writes XLSX file generated by
  4. Microsoft Excel™ 2007 and later. Support save file without losing original
  5. charts of XLSX. This library needs Go version 1.8 or later.
  6. Copyright 2016 - 2018 The excelize Authors. All rights reserved. Use of
  7. this source code is governed by a BSD-style license that can be found in
  8. the LICENSE file.
  9. */
  10. package excelize
  11. import (
  12. "archive/zip"
  13. "bytes"
  14. "encoding/xml"
  15. "io"
  16. "io/ioutil"
  17. "os"
  18. "strconv"
  19. "strings"
  20. )
  21. // File define a populated XLSX file struct.
  22. type File struct {
  23. checked map[string]bool
  24. sheetMap map[string]string
  25. ContentTypes *xlsxTypes
  26. Path string
  27. SharedStrings *xlsxSST
  28. Sheet map[string]*xlsxWorksheet
  29. SheetCount int
  30. Styles *xlsxStyleSheet
  31. Theme *xlsxTheme
  32. WorkBook *xlsxWorkbook
  33. WorkBookRels *xlsxWorkbookRels
  34. XLSX map[string][]byte
  35. }
  36. // OpenFile take the name of an XLSX file and returns a populated XLSX file
  37. // struct for it.
  38. func OpenFile(filename string) (*File, error) {
  39. file, err := os.Open(filename)
  40. if err != nil {
  41. return nil, err
  42. }
  43. defer file.Close()
  44. f, err := OpenReader(file)
  45. if err != nil {
  46. return nil, err
  47. }
  48. f.Path = filename
  49. return f, nil
  50. }
  51. // OpenReader take an io.Reader and return a populated XLSX file.
  52. func OpenReader(r io.Reader) (*File, error) {
  53. b, err := ioutil.ReadAll(r)
  54. if err != nil {
  55. return nil, err
  56. }
  57. zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
  58. if err != nil {
  59. return nil, err
  60. }
  61. file, sheetCount, err := ReadZipReader(zr)
  62. if err != nil {
  63. return nil, err
  64. }
  65. f := &File{
  66. checked: make(map[string]bool),
  67. Sheet: make(map[string]*xlsxWorksheet),
  68. SheetCount: sheetCount,
  69. XLSX: file,
  70. }
  71. f.sheetMap = f.getSheetMap()
  72. f.Styles = f.stylesReader()
  73. f.Theme = f.themeReader()
  74. return f, nil
  75. }
  76. // setDefaultTimeStyle provides a function to set default numbers format for
  77. // time.Time type cell value by given worksheet name, cell coordinates and
  78. // number format code.
  79. func (f *File) setDefaultTimeStyle(sheet, axis string, format int) {
  80. if f.GetCellStyle(sheet, axis) == 0 {
  81. style, _ := f.NewStyle(`{"number_format": ` + strconv.Itoa(format) + `}`)
  82. f.SetCellStyle(sheet, axis, axis, style)
  83. }
  84. }
  85. // workSheetReader provides a function to get the pointer to the structure
  86. // after deserialization by given worksheet name.
  87. func (f *File) workSheetReader(sheet string) *xlsxWorksheet {
  88. name, ok := f.sheetMap[trimSheetName(sheet)]
  89. if !ok {
  90. name = "xl/worksheets/" + strings.ToLower(sheet) + ".xml"
  91. }
  92. if f.Sheet[name] == nil {
  93. var xlsx xlsxWorksheet
  94. _ = xml.Unmarshal(f.readXML(name), &xlsx)
  95. if f.checked == nil {
  96. f.checked = make(map[string]bool)
  97. }
  98. ok := f.checked[name]
  99. if !ok {
  100. checkSheet(&xlsx)
  101. checkRow(&xlsx)
  102. f.checked[name] = true
  103. }
  104. f.Sheet[name] = &xlsx
  105. }
  106. return f.Sheet[name]
  107. }
  108. // checkSheet provides a function to fill each row element and make that is
  109. // continuous in a worksheet of XML.
  110. func checkSheet(xlsx *xlsxWorksheet) {
  111. row := len(xlsx.SheetData.Row)
  112. if row >= 1 {
  113. lastRow := xlsx.SheetData.Row[row-1].R
  114. if lastRow >= row {
  115. row = lastRow
  116. }
  117. }
  118. sheetData := xlsxSheetData{}
  119. existsRows := map[int]int{}
  120. for k := range xlsx.SheetData.Row {
  121. existsRows[xlsx.SheetData.Row[k].R] = k
  122. }
  123. for i := 0; i < row; i++ {
  124. _, ok := existsRows[i+1]
  125. if ok {
  126. sheetData.Row = append(sheetData.Row, xlsx.SheetData.Row[existsRows[i+1]])
  127. } else {
  128. sheetData.Row = append(sheetData.Row, xlsxRow{
  129. R: i + 1,
  130. })
  131. }
  132. }
  133. xlsx.SheetData = sheetData
  134. }
  135. // replaceWorkSheetsRelationshipsNameSpaceBytes provides a function to replace
  136. // xl/worksheets/sheet%d.xml XML tags to self-closing for compatible Microsoft
  137. // Office Excel 2007.
  138. func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  139. var oldXmlns = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  140. var newXmlns = []byte(`<worksheet xr:uid="{00000000-0001-0000-0000-000000000000}" xmlns:xr3="http://schemas.microsoft.com/office/spreadsheetml/2016/revision3" xmlns:xr2="http://schemas.microsoft.com/office/spreadsheetml/2015/revision2" xmlns:xr="http://schemas.microsoft.com/office/spreadsheetml/2014/revision" xmlns:x14="http://schemas.microsoft.com/office/spreadsheetml/2009/9/main" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac" mc:Ignorable="x14ac xr xr2 xr3" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mx="http://schemas.microsoft.com/office/mac/excel/2008/main" xmlns:mv="urn:schemas-microsoft-com:mac:vml" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  141. workbookMarshal = bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  142. return workbookMarshal
  143. }
  144. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  145. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  146. // cell have a linked value. Reference
  147. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  148. //
  149. // Notice: after open XLSX file Excel will be update linked value and generate
  150. // new value and will prompt save file or not.
  151. //
  152. // For example:
  153. //
  154. // <row r="19" spans="2:2">
  155. // <c r="B19">
  156. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  157. // <v>100</v>
  158. // </c>
  159. // </row>
  160. //
  161. // to
  162. //
  163. // <row r="19" spans="2:2">
  164. // <c r="B19">
  165. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  166. // </c>
  167. // </row>
  168. //
  169. func (f *File) UpdateLinkedValue() {
  170. for _, name := range f.GetSheetMap() {
  171. xlsx := f.workSheetReader(name)
  172. for indexR := range xlsx.SheetData.Row {
  173. for indexC, col := range xlsx.SheetData.Row[indexR].C {
  174. if col.F != nil && col.V != "" {
  175. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  176. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  177. }
  178. }
  179. }
  180. }
  181. }
  182. // adjustHelper provides a function to adjust rows and columns dimensions,
  183. // hyperlinks, merged cells and auto filter when inserting or deleting rows or
  184. // columns.
  185. //
  186. // sheet: Worksheet name that we're editing
  187. // column: Index number of the column we're inserting/deleting before
  188. // row: Index number of the row we're inserting/deleting before
  189. // offset: Number of rows/column to insert/delete negative values indicate deletion
  190. //
  191. // TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
  192. //
  193. func (f *File) adjustHelper(sheet string, column, row, offset int) {
  194. xlsx := f.workSheetReader(sheet)
  195. f.adjustRowDimensions(xlsx, row, offset)
  196. f.adjustColDimensions(xlsx, column, offset)
  197. f.adjustHyperlinks(sheet, column, row, offset)
  198. f.adjustMergeCells(xlsx, column, row, offset)
  199. f.adjustAutoFilter(xlsx, column, row, offset)
  200. checkSheet(xlsx)
  201. checkRow(xlsx)
  202. }
  203. // adjustColDimensions provides a function to update column dimensions when
  204. // inserting or deleting rows or columns.
  205. func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
  206. for i, r := range xlsx.SheetData.Row {
  207. for k, v := range r.C {
  208. axis := v.R
  209. col := string(strings.Map(letterOnlyMapF, axis))
  210. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  211. yAxis := TitleToNumber(col)
  212. if yAxis >= column && column != -1 {
  213. xlsx.SheetData.Row[i].C[k].R = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  214. }
  215. }
  216. }
  217. }
  218. // adjustRowDimensions provides a function to update row dimensions when
  219. // inserting or deleting rows or columns.
  220. func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
  221. if rowIndex == -1 {
  222. return
  223. }
  224. for i, r := range xlsx.SheetData.Row {
  225. if r.R >= rowIndex {
  226. xlsx.SheetData.Row[i].R += offset
  227. for k, v := range xlsx.SheetData.Row[i].C {
  228. axis := v.R
  229. col := string(strings.Map(letterOnlyMapF, axis))
  230. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  231. xAxis := row + offset
  232. xlsx.SheetData.Row[i].C[k].R = col + strconv.Itoa(xAxis)
  233. }
  234. }
  235. }
  236. }
  237. // adjustHyperlinks provides a function to update hyperlinks when inserting or
  238. // deleting rows or columns.
  239. func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
  240. xlsx := f.workSheetReader(sheet)
  241. // order is important
  242. if xlsx.Hyperlinks != nil && offset < 0 {
  243. for i, v := range xlsx.Hyperlinks.Hyperlink {
  244. axis := v.Ref
  245. col := string(strings.Map(letterOnlyMapF, axis))
  246. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  247. yAxis := TitleToNumber(col)
  248. if row == rowIndex || yAxis == column {
  249. f.deleteSheetRelationships(sheet, v.RID)
  250. if len(xlsx.Hyperlinks.Hyperlink) > 1 {
  251. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i], xlsx.Hyperlinks.Hyperlink[i+1:]...)
  252. } else {
  253. xlsx.Hyperlinks = nil
  254. }
  255. }
  256. }
  257. }
  258. if xlsx.Hyperlinks != nil {
  259. for i, v := range xlsx.Hyperlinks.Hyperlink {
  260. axis := v.Ref
  261. col := string(strings.Map(letterOnlyMapF, axis))
  262. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  263. xAxis := row + offset
  264. yAxis := TitleToNumber(col)
  265. if rowIndex != -1 && row >= rowIndex {
  266. xlsx.Hyperlinks.Hyperlink[i].Ref = col + strconv.Itoa(xAxis)
  267. }
  268. if column != -1 && yAxis >= column {
  269. xlsx.Hyperlinks.Hyperlink[i].Ref = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  270. }
  271. }
  272. }
  273. }
  274. // adjustMergeCellsHelper provides a function to update merged cells when
  275. // inserting or deleting rows or columns.
  276. func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  277. if xlsx.MergeCells != nil {
  278. for k, v := range xlsx.MergeCells.Cells {
  279. beg := strings.Split(v.Ref, ":")[0]
  280. end := strings.Split(v.Ref, ":")[1]
  281. begcol := string(strings.Map(letterOnlyMapF, beg))
  282. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  283. begxAxis := begrow + offset
  284. begyAxis := TitleToNumber(begcol)
  285. endcol := string(strings.Map(letterOnlyMapF, end))
  286. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  287. endxAxis := endrow + offset
  288. endyAxis := TitleToNumber(endcol)
  289. if rowIndex != -1 {
  290. if begrow > 1 && begrow >= rowIndex {
  291. beg = begcol + strconv.Itoa(begxAxis)
  292. }
  293. if endrow > 1 && endrow >= rowIndex {
  294. end = endcol + strconv.Itoa(endxAxis)
  295. }
  296. }
  297. if column != -1 {
  298. if begyAxis >= column {
  299. beg = ToAlphaString(begyAxis+offset) + strconv.Itoa(endrow)
  300. }
  301. if endyAxis >= column {
  302. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  303. }
  304. }
  305. xlsx.MergeCells.Cells[k].Ref = beg + ":" + end
  306. }
  307. }
  308. }
  309. // adjustMergeCells provides a function to update merged cells when inserting
  310. // or deleting rows or columns.
  311. func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  312. f.adjustMergeCellsHelper(xlsx, column, rowIndex, offset)
  313. if xlsx.MergeCells != nil && offset < 0 {
  314. for k, v := range xlsx.MergeCells.Cells {
  315. beg := strings.Split(v.Ref, ":")[0]
  316. end := strings.Split(v.Ref, ":")[1]
  317. if beg == end {
  318. xlsx.MergeCells.Count += offset
  319. if len(xlsx.MergeCells.Cells) > 1 {
  320. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:k], xlsx.MergeCells.Cells[k+1:]...)
  321. } else {
  322. xlsx.MergeCells = nil
  323. }
  324. }
  325. }
  326. }
  327. }
  328. // adjustAutoFilter provides a function to update the auto filter when
  329. // inserting or deleting rows or columns.
  330. func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  331. f.adjustAutoFilterHelper(xlsx, column, rowIndex, offset)
  332. if xlsx.AutoFilter != nil {
  333. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  334. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  335. begcol := string(strings.Map(letterOnlyMapF, beg))
  336. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  337. begxAxis := begrow + offset
  338. endcol := string(strings.Map(letterOnlyMapF, end))
  339. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  340. endxAxis := endrow + offset
  341. endyAxis := TitleToNumber(endcol)
  342. if rowIndex != -1 {
  343. if begrow >= rowIndex {
  344. beg = begcol + strconv.Itoa(begxAxis)
  345. }
  346. if endrow >= rowIndex {
  347. end = endcol + strconv.Itoa(endxAxis)
  348. }
  349. }
  350. if column != -1 && endyAxis >= column {
  351. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  352. }
  353. xlsx.AutoFilter.Ref = beg + ":" + end
  354. }
  355. }
  356. // adjustAutoFilterHelper provides a function to update the auto filter when
  357. // inserting or deleting rows or columns.
  358. func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  359. if xlsx.AutoFilter != nil {
  360. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  361. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  362. begcol := string(strings.Map(letterOnlyMapF, beg))
  363. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  364. begyAxis := TitleToNumber(begcol)
  365. endcol := string(strings.Map(letterOnlyMapF, end))
  366. endyAxis := TitleToNumber(endcol)
  367. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  368. if (begrow == rowIndex && offset < 0) || (column == begyAxis && column == endyAxis) {
  369. xlsx.AutoFilter = nil
  370. for i, r := range xlsx.SheetData.Row {
  371. if begrow < r.R && r.R <= endrow {
  372. xlsx.SheetData.Row[i].Hidden = false
  373. }
  374. }
  375. }
  376. }
  377. }