excelize.go 13 KB

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