excelize.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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][]byte
  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(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. func replaceWorkSheetsRelationshipsNameSpaceBytes(workbookMarshal []byte) []byte {
  134. var oldXmlns = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`)
  135. 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">`)
  136. workbookMarshal = bytes.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  137. return workbookMarshal
  138. }
  139. // UpdateLinkedValue fix linked values within a spreadsheet are not updating in
  140. // Office Excel 2007 and 2010. This function will be remove value tag when met a
  141. // cell have a linked value. Reference
  142. // https://social.technet.microsoft.com/Forums/office/en-US/e16bae1f-6a2c-4325-8013-e989a3479066/excel-2010-linked-cells-not-updating?forum=excel
  143. //
  144. // Notice: after open XLSX file Excel will be update linked value and generate
  145. // new value and will prompt save file or not.
  146. //
  147. // For example:
  148. //
  149. // <row r="19" spans="2:2">
  150. // <c r="B19">
  151. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  152. // <v>100</v>
  153. // </c>
  154. // </row>
  155. //
  156. // to
  157. //
  158. // <row r="19" spans="2:2">
  159. // <c r="B19">
  160. // <f>SUM(Sheet2!D2,Sheet2!D11)</f>
  161. // </c>
  162. // </row>
  163. //
  164. func (f *File) UpdateLinkedValue() {
  165. for _, name := range f.GetSheetMap() {
  166. xlsx := f.workSheetReader(name)
  167. for indexR := range xlsx.SheetData.Row {
  168. for indexC, col := range xlsx.SheetData.Row[indexR].C {
  169. if col.F != nil && col.V != "" {
  170. xlsx.SheetData.Row[indexR].C[indexC].V = ""
  171. xlsx.SheetData.Row[indexR].C[indexC].T = ""
  172. }
  173. }
  174. }
  175. }
  176. }
  177. // adjustHelper provides function to adjust rows and columns dimensions,
  178. // hyperlinks, merged cells and auto filter when inserting or deleting rows or
  179. // columns.
  180. //
  181. // sheet: Worksheet name that we're editing
  182. // column: Index number of the column we're inserting/deleting before
  183. // row: Index number of the row we're inserting/deleting before
  184. // offset: Number of rows/column to insert/delete negative values indicate deletion
  185. //
  186. // TODO: adjustPageBreaks, adjustComments, adjustDataValidations, adjustProtectedCells
  187. //
  188. func (f *File) adjustHelper(sheet string, column, row, offset int) {
  189. xlsx := f.workSheetReader(sheet)
  190. f.adjustRowDimensions(xlsx, row, offset)
  191. f.adjustColDimensions(xlsx, column, offset)
  192. f.adjustHyperlinks(sheet, column, row, offset)
  193. f.adjustMergeCells(xlsx, column, row, offset)
  194. f.adjustAutoFilter(xlsx, column, row, offset)
  195. checkSheet(xlsx)
  196. checkRow(xlsx)
  197. }
  198. // adjustColDimensions provides function to update column dimensions when
  199. // inserting or deleting rows or columns.
  200. func (f *File) adjustColDimensions(xlsx *xlsxWorksheet, column, offset int) {
  201. for i, r := range xlsx.SheetData.Row {
  202. for k, v := range r.C {
  203. axis := v.R
  204. col := string(strings.Map(letterOnlyMapF, axis))
  205. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  206. yAxis := TitleToNumber(col)
  207. if yAxis >= column && column != -1 {
  208. xlsx.SheetData.Row[i].C[k].R = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  209. }
  210. }
  211. }
  212. }
  213. // adjustRowDimensions provides function to update row dimensions when inserting
  214. // or deleting rows or columns.
  215. func (f *File) adjustRowDimensions(xlsx *xlsxWorksheet, rowIndex, offset int) {
  216. if rowIndex == -1 {
  217. return
  218. }
  219. for i, r := range xlsx.SheetData.Row {
  220. if r.R >= rowIndex {
  221. xlsx.SheetData.Row[i].R += offset
  222. for k, v := range xlsx.SheetData.Row[i].C {
  223. axis := v.R
  224. col := string(strings.Map(letterOnlyMapF, axis))
  225. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  226. xAxis := row + offset
  227. xlsx.SheetData.Row[i].C[k].R = col + strconv.Itoa(xAxis)
  228. }
  229. }
  230. }
  231. }
  232. // adjustHyperlinks provides function to update hyperlinks when inserting or
  233. // deleting rows or columns.
  234. func (f *File) adjustHyperlinks(sheet string, column, rowIndex, offset int) {
  235. xlsx := f.workSheetReader(sheet)
  236. // order is important
  237. if xlsx.Hyperlinks != nil && offset < 0 {
  238. for i, v := range xlsx.Hyperlinks.Hyperlink {
  239. axis := v.Ref
  240. col := string(strings.Map(letterOnlyMapF, axis))
  241. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  242. yAxis := TitleToNumber(col)
  243. if row == rowIndex || yAxis == column {
  244. f.deleteSheetRelationships(sheet, v.RID)
  245. if len(xlsx.Hyperlinks.Hyperlink) > 1 {
  246. xlsx.Hyperlinks.Hyperlink = append(xlsx.Hyperlinks.Hyperlink[:i], xlsx.Hyperlinks.Hyperlink[i+1:]...)
  247. } else {
  248. xlsx.Hyperlinks = nil
  249. }
  250. }
  251. }
  252. }
  253. if xlsx.Hyperlinks != nil {
  254. for i, v := range xlsx.Hyperlinks.Hyperlink {
  255. axis := v.Ref
  256. col := string(strings.Map(letterOnlyMapF, axis))
  257. row, _ := strconv.Atoi(strings.Map(intOnlyMapF, axis))
  258. xAxis := row + offset
  259. yAxis := TitleToNumber(col)
  260. if rowIndex != -1 && row >= rowIndex {
  261. xlsx.Hyperlinks.Hyperlink[i].Ref = col + strconv.Itoa(xAxis)
  262. }
  263. if column != -1 && yAxis >= column {
  264. xlsx.Hyperlinks.Hyperlink[i].Ref = ToAlphaString(yAxis+offset) + strconv.Itoa(row)
  265. }
  266. }
  267. }
  268. }
  269. // adjustMergeCellsHelper provides function to update merged cells when inserting or
  270. // deleting rows or columns.
  271. func (f *File) adjustMergeCellsHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  272. if xlsx.MergeCells != nil {
  273. for k, v := range xlsx.MergeCells.Cells {
  274. beg := strings.Split(v.Ref, ":")[0]
  275. end := strings.Split(v.Ref, ":")[1]
  276. begcol := string(strings.Map(letterOnlyMapF, beg))
  277. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  278. begxAxis := begrow + offset
  279. begyAxis := TitleToNumber(begcol)
  280. endcol := string(strings.Map(letterOnlyMapF, end))
  281. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  282. endxAxis := endrow + offset
  283. endyAxis := TitleToNumber(endcol)
  284. if rowIndex != -1 {
  285. if begrow > 1 && begrow >= rowIndex {
  286. beg = begcol + strconv.Itoa(begxAxis)
  287. }
  288. if endrow > 1 && endrow >= rowIndex {
  289. end = endcol + strconv.Itoa(endxAxis)
  290. }
  291. }
  292. if column != -1 {
  293. if begyAxis >= column {
  294. beg = ToAlphaString(begyAxis+offset) + strconv.Itoa(endrow)
  295. }
  296. if endyAxis >= column {
  297. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  298. }
  299. }
  300. xlsx.MergeCells.Cells[k].Ref = beg + ":" + end
  301. }
  302. }
  303. }
  304. // adjustMergeCells provides function to update merged cells when inserting or
  305. // deleting rows or columns.
  306. func (f *File) adjustMergeCells(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  307. f.adjustMergeCellsHelper(xlsx, column, rowIndex, offset)
  308. if xlsx.MergeCells != nil && offset < 0 {
  309. for k, v := range xlsx.MergeCells.Cells {
  310. beg := strings.Split(v.Ref, ":")[0]
  311. end := strings.Split(v.Ref, ":")[1]
  312. if beg == end {
  313. xlsx.MergeCells.Count += offset
  314. if len(xlsx.MergeCells.Cells) > 1 {
  315. xlsx.MergeCells.Cells = append(xlsx.MergeCells.Cells[:k], xlsx.MergeCells.Cells[k+1:]...)
  316. } else {
  317. xlsx.MergeCells = nil
  318. }
  319. }
  320. }
  321. }
  322. }
  323. // adjustAutoFilter provides function to update the auto filter when inserting
  324. // or deleting rows or columns.
  325. func (f *File) adjustAutoFilter(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  326. f.adjustAutoFilterHelper(xlsx, column, rowIndex, offset)
  327. if xlsx.AutoFilter != nil {
  328. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  329. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  330. begcol := string(strings.Map(letterOnlyMapF, beg))
  331. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  332. begxAxis := begrow + offset
  333. endcol := string(strings.Map(letterOnlyMapF, end))
  334. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  335. endxAxis := endrow + offset
  336. endyAxis := TitleToNumber(endcol)
  337. if rowIndex != -1 {
  338. if begrow >= rowIndex {
  339. beg = begcol + strconv.Itoa(begxAxis)
  340. }
  341. if endrow >= rowIndex {
  342. end = endcol + strconv.Itoa(endxAxis)
  343. }
  344. }
  345. if column != -1 && endyAxis >= column {
  346. end = ToAlphaString(endyAxis+offset) + strconv.Itoa(endrow)
  347. }
  348. xlsx.AutoFilter.Ref = beg + ":" + end
  349. }
  350. }
  351. // adjustAutoFilterHelper provides function to update the auto filter when
  352. // inserting or deleting rows or columns.
  353. func (f *File) adjustAutoFilterHelper(xlsx *xlsxWorksheet, column, rowIndex, offset int) {
  354. if xlsx.AutoFilter != nil {
  355. beg := strings.Split(xlsx.AutoFilter.Ref, ":")[0]
  356. end := strings.Split(xlsx.AutoFilter.Ref, ":")[1]
  357. begcol := string(strings.Map(letterOnlyMapF, beg))
  358. begrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, beg))
  359. begyAxis := TitleToNumber(begcol)
  360. endcol := string(strings.Map(letterOnlyMapF, end))
  361. endyAxis := TitleToNumber(endcol)
  362. endrow, _ := strconv.Atoi(strings.Map(intOnlyMapF, end))
  363. if (begrow == rowIndex && offset < 0) || (column == begyAxis && column == endyAxis) {
  364. xlsx.AutoFilter = nil
  365. for i, r := range xlsx.SheetData.Row {
  366. if begrow < r.R && r.R <= endrow {
  367. xlsx.SheetData.Row[i].Hidden = false
  368. }
  369. }
  370. }
  371. }
  372. }