excelize.go 13 KB

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