excelize.go 12 KB

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