excelize.go 12 KB

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