excelize.go 13 KB

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