sheet.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "errors"
  6. "os"
  7. "path"
  8. "strconv"
  9. "strings"
  10. )
  11. // NewSheet provides function to create a new sheet by given index, when
  12. // creating a new XLSX file, the default sheet will be create, when you create a
  13. // new file, you need to ensure that the index is continuous.
  14. func (f *File) NewSheet(index int, name string) {
  15. // Update docProps/app.xml
  16. f.setAppXML()
  17. // Update [Content_Types].xml
  18. f.setContentTypes(index)
  19. // Create new sheet /xl/worksheets/sheet%d.xml
  20. f.setSheet(index)
  21. // Update xl/_rels/workbook.xml.rels
  22. rID := f.addXlsxWorkbookRels(index)
  23. // Update xl/workbook.xml
  24. f.setWorkbook(name, rID)
  25. f.SheetCount++
  26. }
  27. // contentTypesReader provides function to get the pointer to the
  28. // [Content_Types].xml structure after deserialization.
  29. func (f *File) contentTypesReader() *xlsxTypes {
  30. if f.ContentTypes == nil {
  31. var content xlsxTypes
  32. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  33. f.ContentTypes = &content
  34. }
  35. return f.ContentTypes
  36. }
  37. // contentTypesWriter provides function to save [Content_Types].xml after
  38. // serialize structure.
  39. func (f *File) contentTypesWriter() {
  40. if f.ContentTypes != nil {
  41. output, _ := xml.Marshal(f.ContentTypes)
  42. f.saveFileList("[Content_Types].xml", string(output))
  43. }
  44. }
  45. // workbookReader provides function to get the pointer to the xl/workbook.xml
  46. // structure after deserialization.
  47. func (f *File) workbookReader() *xlsxWorkbook {
  48. if f.WorkBook == nil {
  49. var content xlsxWorkbook
  50. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  51. f.WorkBook = &content
  52. }
  53. return f.WorkBook
  54. }
  55. // workbookWriter provides function to save xl/workbook.xml after serialize
  56. // structure.
  57. func (f *File) workbookWriter() {
  58. if f.WorkBook != nil {
  59. output, _ := xml.Marshal(f.WorkBook)
  60. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  61. }
  62. }
  63. // worksheetWriter provides function to save xl/worksheets/sheet%d.xml after
  64. // serialize structure.
  65. func (f *File) worksheetWriter() {
  66. for path, sheet := range f.Sheet {
  67. if sheet != nil {
  68. for k, v := range sheet.SheetData.Row {
  69. f.Sheet[path].SheetData.Row[k].C = trimCell(v.C)
  70. }
  71. output, _ := xml.Marshal(sheet)
  72. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  73. ok := f.checked[path]
  74. if ok {
  75. f.checked[path] = false
  76. }
  77. }
  78. }
  79. }
  80. // trimCell provides function to trim blank cells which created by completeCol.
  81. func trimCell(column []xlsxC) []xlsxC {
  82. col := []xlsxC{}
  83. for _, c := range column {
  84. if c.S == 0 && c.V == "" && c.F == nil && c.T == "" {
  85. continue
  86. }
  87. col = append(col, c)
  88. }
  89. return col
  90. }
  91. // Read and update property of contents type of XLSX.
  92. func (f *File) setContentTypes(index int) {
  93. content := f.contentTypesReader()
  94. content.Overrides = append(content.Overrides, xlsxOverride{
  95. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  96. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  97. })
  98. }
  99. // Update sheet property by given index.
  100. func (f *File) setSheet(index int) {
  101. var xlsx xlsxWorksheet
  102. xlsx.Dimension.Ref = "A1"
  103. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  104. WorkbookViewID: 0,
  105. })
  106. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  107. f.Sheet[path] = &xlsx
  108. }
  109. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  110. // allowed in sheet title.
  111. func (f *File) setWorkbook(name string, rid int) {
  112. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  113. name = r.Replace(name)
  114. if len(name) > 31 {
  115. name = name[0:31]
  116. }
  117. content := f.workbookReader()
  118. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  119. Name: name,
  120. SheetID: strconv.Itoa(rid),
  121. ID: "rId" + strconv.Itoa(rid),
  122. })
  123. }
  124. // workbookRelsReader provides function to read and unmarshal workbook
  125. // relationships of XLSX file.
  126. func (f *File) workbookRelsReader() *xlsxWorkbookRels {
  127. if f.WorkBookRels == nil {
  128. var content xlsxWorkbookRels
  129. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  130. f.WorkBookRels = &content
  131. }
  132. return f.WorkBookRels
  133. }
  134. // workbookRelsWriter provides function to save xl/_rels/workbook.xml.rels after
  135. // serialize structure.
  136. func (f *File) workbookRelsWriter() {
  137. if f.WorkBookRels != nil {
  138. output, _ := xml.Marshal(f.WorkBookRels)
  139. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  140. }
  141. }
  142. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  143. func (f *File) addXlsxWorkbookRels(sheet int) int {
  144. content := f.workbookRelsReader()
  145. rID := 0
  146. for _, v := range content.Relationships {
  147. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  148. if t > rID {
  149. rID = t
  150. }
  151. }
  152. rID++
  153. ID := bytes.Buffer{}
  154. ID.WriteString("rId")
  155. ID.WriteString(strconv.Itoa(rID))
  156. target := bytes.Buffer{}
  157. target.WriteString("worksheets/sheet")
  158. target.WriteString(strconv.Itoa(sheet))
  159. target.WriteString(".xml")
  160. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  161. ID: ID.String(),
  162. Target: target.String(),
  163. Type: SourceRelationshipWorkSheet,
  164. })
  165. return rID
  166. }
  167. // setAppXML update docProps/app.xml file of XML.
  168. func (f *File) setAppXML() {
  169. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  170. }
  171. // Some tools that read XLSX files have very strict requirements about the
  172. // structure of the input XML. In particular both Numbers on the Mac and SAS
  173. // dislike inline XML namespace declarations, or namespace prefixes that don't
  174. // match the ones that Excel itself uses. This is a problem because the Go XML
  175. // library doesn't multiple namespace declarations in a single element of a
  176. // document. This function is a horrible hack to fix that after the XML
  177. // marshalling is completed.
  178. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  179. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  180. newXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x15" xmlns:x15="http://schemas.microsoft.com/office/spreadsheetml/2010/11/main">`
  181. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  182. }
  183. // SetActiveSheet provides function to set default active sheet of XLSX by given
  184. // index.
  185. func (f *File) SetActiveSheet(index int) {
  186. if index < 1 {
  187. index = 1
  188. }
  189. index--
  190. content := f.workbookReader()
  191. if len(content.BookViews.WorkBookView) > 0 {
  192. content.BookViews.WorkBookView[0].ActiveTab = index
  193. } else {
  194. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  195. ActiveTab: index,
  196. })
  197. }
  198. sheets := len(content.Sheets.Sheet)
  199. index++
  200. for i := 0; i < sheets; i++ {
  201. sheetIndex := i + 1
  202. xlsx := f.workSheetReader("sheet" + strconv.Itoa(sheetIndex))
  203. if index == sheetIndex {
  204. if len(xlsx.SheetViews.SheetView) > 0 {
  205. xlsx.SheetViews.SheetView[0].TabSelected = true
  206. } else {
  207. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  208. TabSelected: true,
  209. })
  210. }
  211. } else {
  212. if len(xlsx.SheetViews.SheetView) > 0 {
  213. xlsx.SheetViews.SheetView[0].TabSelected = false
  214. }
  215. }
  216. }
  217. return
  218. }
  219. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  220. // found the active sheet will be return integer 0.
  221. func (f *File) GetActiveSheetIndex() int {
  222. buffer := bytes.Buffer{}
  223. content := f.workbookReader()
  224. for _, v := range content.Sheets.Sheet {
  225. xlsx := xlsxWorksheet{}
  226. buffer.WriteString("xl/worksheets/sheet")
  227. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  228. buffer.WriteString(".xml")
  229. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  230. for _, sheetView := range xlsx.SheetViews.SheetView {
  231. if sheetView.TabSelected {
  232. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  233. return ID
  234. }
  235. }
  236. buffer.Reset()
  237. }
  238. return 0
  239. }
  240. // SetSheetName provides function to set the sheet name be given old and new
  241. // sheet name. Maximum 31 characters are allowed in sheet title and this
  242. // function only changes the name of the sheet and will not update the sheet
  243. // name in the formula or reference associated with the cell. So there may be
  244. // problem formula error or reference missing.
  245. func (f *File) SetSheetName(oldName, newName string) {
  246. oldName = trimSheetName(oldName)
  247. newName = trimSheetName(newName)
  248. content := f.workbookReader()
  249. for k, v := range content.Sheets.Sheet {
  250. if v.Name == oldName {
  251. content.Sheets.Sheet[k].Name = newName
  252. }
  253. }
  254. }
  255. // GetSheetName provides function to get sheet name of XLSX by given worksheet
  256. // index. If given sheet index is invalid, will return an empty string.
  257. func (f *File) GetSheetName(index int) string {
  258. content := f.workbookReader()
  259. rels := f.workbookRelsReader()
  260. for _, rel := range rels.Relationships {
  261. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  262. if rID == index {
  263. for _, v := range content.Sheets.Sheet {
  264. if v.ID == rel.ID {
  265. return v.Name
  266. }
  267. }
  268. }
  269. }
  270. return ""
  271. }
  272. // GetSheetIndex provides function to get worksheet index of XLSX by given sheet
  273. // name. If given sheet name is invalid, will return an integer type value 0.
  274. func (f *File) GetSheetIndex(name string) int {
  275. content := f.workbookReader()
  276. rels := f.workbookRelsReader()
  277. for _, v := range content.Sheets.Sheet {
  278. if v.Name == name {
  279. for _, rel := range rels.Relationships {
  280. if v.ID == rel.ID {
  281. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  282. return rID
  283. }
  284. }
  285. }
  286. }
  287. return 0
  288. }
  289. // GetSheetMap provides function to get sheet map of XLSX. For example:
  290. //
  291. // xlsx, err := excelize.OpenFile("./Workbook.xlsx")
  292. // if err != nil {
  293. // fmt.Println(err)
  294. // os.Exit(1)
  295. // }
  296. // for k, v := range xlsx.GetSheetMap() {
  297. // fmt.Println(k, v)
  298. // }
  299. //
  300. func (f *File) GetSheetMap() map[int]string {
  301. content := f.workbookReader()
  302. rels := f.workbookRelsReader()
  303. sheetMap := map[int]string{}
  304. for _, v := range content.Sheets.Sheet {
  305. for _, rel := range rels.Relationships {
  306. if rel.ID == v.ID {
  307. rID, _ := strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rel.Target, "worksheets/sheet"), ".xml"))
  308. sheetMap[rID] = v.Name
  309. }
  310. }
  311. }
  312. return sheetMap
  313. }
  314. // SetSheetBackground provides function to set background picture by given sheet
  315. // index.
  316. func (f *File) SetSheetBackground(sheet, picture string) error {
  317. var err error
  318. // Check picture exists first.
  319. if _, err = os.Stat(picture); os.IsNotExist(err) {
  320. return err
  321. }
  322. ext, ok := supportImageTypes[path.Ext(picture)]
  323. if !ok {
  324. return errors.New("Unsupported image extension")
  325. }
  326. pictureID := f.countMedia() + 1
  327. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  328. f.addSheetPicture(sheet, rID)
  329. f.addMedia(picture, ext)
  330. f.setContentTypePartImageExtensions()
  331. return err
  332. }
  333. // DeleteSheet provides function to delete worksheet in a workbook by given
  334. // sheet name. Use this method with caution, which will affect changes in
  335. // references such as formulas, charts, and so on. If there is any referenced
  336. // value of the deleted worksheet, it will cause a file error when you open it.
  337. // This function will be invalid when only the one worksheet is left.
  338. func (f *File) DeleteSheet(name string) {
  339. content := f.workbookReader()
  340. for k, v := range content.Sheets.Sheet {
  341. if v.Name != name || len(content.Sheets.Sheet) < 2 {
  342. continue
  343. }
  344. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  345. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  346. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  347. target := f.deleteSheetFromWorkbookRels(v.ID)
  348. f.deleteSheetFromContentTypes(target)
  349. _, ok := f.XLSX[sheet]
  350. if ok {
  351. delete(f.XLSX, sheet)
  352. }
  353. _, ok = f.XLSX[rels]
  354. if ok {
  355. delete(f.XLSX, rels)
  356. }
  357. _, ok = f.Sheet[sheet]
  358. if ok {
  359. delete(f.Sheet, sheet)
  360. }
  361. f.SheetCount--
  362. }
  363. }
  364. // deleteSheetFromWorkbookRels provides function to remove worksheet
  365. // relationships by given relationships ID in the file
  366. // xl/_rels/workbook.xml.rels.
  367. func (f *File) deleteSheetFromWorkbookRels(rID string) string {
  368. content := f.workbookRelsReader()
  369. for k, v := range content.Relationships {
  370. if v.ID != rID {
  371. continue
  372. }
  373. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  374. return v.Target
  375. }
  376. return ""
  377. }
  378. // deleteSheetFromContentTypes provides function to remove worksheet
  379. // relationships by given target name in the file [Content_Types].xml.
  380. func (f *File) deleteSheetFromContentTypes(target string) {
  381. content := f.contentTypesReader()
  382. for k, v := range content.Overrides {
  383. if v.PartName != "/xl/"+target {
  384. continue
  385. }
  386. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  387. }
  388. }
  389. // CopySheet provides function to duplicate a worksheet by gave source and
  390. // target worksheet index. Note that currently doesn't support duplicate
  391. // workbooks that contain tables, charts or pictures. For Example:
  392. //
  393. // // Sheet1 already exists...
  394. // xlsx.NewSheet(2, "sheet2")
  395. // err := xlsx.CopySheet(1, 2)
  396. // if err != nil {
  397. // fmt.Println(err)
  398. // os.Exit(1)
  399. // }
  400. //
  401. func (f *File) CopySheet(from, to int) error {
  402. if from < 1 || to < 1 || from == to || f.GetSheetName(from) == "" || f.GetSheetName(to) == "" {
  403. return errors.New("Invalid worksheet index")
  404. }
  405. f.copySheet(from, to)
  406. return nil
  407. }
  408. // copySheet provides function to duplicate a worksheet by gave source and
  409. // target worksheet index.
  410. func (f *File) copySheet(from, to int) {
  411. sheet := f.workSheetReader("sheet" + strconv.Itoa(from))
  412. worksheet := *sheet
  413. path := "xl/worksheets/sheet" + strconv.Itoa(to) + ".xml"
  414. if len(worksheet.SheetViews.SheetView) > 0 {
  415. worksheet.SheetViews.SheetView[0].TabSelected = false
  416. }
  417. worksheet.Drawing = nil
  418. worksheet.TableParts = nil
  419. worksheet.PageSetUp = nil
  420. f.Sheet[path] = &worksheet
  421. toRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(to) + ".xml.rels"
  422. fromRels := "xl/worksheets/_rels/sheet" + strconv.Itoa(from) + ".xml.rels"
  423. _, ok := f.XLSX[fromRels]
  424. if ok {
  425. f.XLSX[toRels] = f.XLSX[fromRels]
  426. }
  427. }
  428. // SetSheetVisible provides function to set worksheet visible by given worksheet
  429. // name. A workbook must contain at least one visible worksheet. If the given
  430. // worksheet has been activated, this setting will be invalidated. Sheet state
  431. // values as defined by http://msdn.microsoft.com/en-us/library/office/documentformat.openxml.spreadsheet.sheetstatevalues.aspx
  432. //
  433. // visible
  434. // hidden
  435. // veryHidden
  436. //
  437. // For example, hide Sheet1:
  438. //
  439. // xlsx.SetSheetVisible("Sheet1", false)
  440. //
  441. func (f *File) SetSheetVisible(name string, visible bool) {
  442. name = trimSheetName(name)
  443. content := f.workbookReader()
  444. if visible {
  445. for k, v := range content.Sheets.Sheet {
  446. if v.Name == name {
  447. content.Sheets.Sheet[k].State = ""
  448. }
  449. }
  450. return
  451. }
  452. count := 0
  453. for _, v := range content.Sheets.Sheet {
  454. if v.State != "hidden" {
  455. count++
  456. }
  457. }
  458. for k, v := range content.Sheets.Sheet {
  459. sheetIndex := k + 1
  460. xlsx := f.workSheetReader("sheet" + strconv.Itoa(sheetIndex))
  461. tabSelected := false
  462. if len(xlsx.SheetViews.SheetView) > 0 {
  463. tabSelected = xlsx.SheetViews.SheetView[0].TabSelected
  464. }
  465. if v.Name == name && count > 1 && !tabSelected {
  466. content.Sheets.Sheet[k].State = "hidden"
  467. }
  468. }
  469. }
  470. // GetSheetVisible provides function to get worksheet visible by given worksheet
  471. // name. For example, get visible state of Sheet1:
  472. //
  473. // xlsx.GetSheetVisible("Sheet1")
  474. //
  475. func (f *File) GetSheetVisible(name string) bool {
  476. name = trimSheetName(name)
  477. content := f.workbookReader()
  478. visible := false
  479. for k, v := range content.Sheets.Sheet {
  480. if v.Name == name {
  481. if content.Sheets.Sheet[k].State == "" || content.Sheets.Sheet[k].State == "visible" {
  482. visible = true
  483. }
  484. }
  485. }
  486. return visible
  487. }
  488. // trimSheetName provides function to trim invaild characters by given worksheet
  489. // name.
  490. func trimSheetName(name string) string {
  491. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  492. name = r.Replace(name)
  493. if len(name) > 31 {
  494. name = name[0:31]
  495. }
  496. return name
  497. }