sheet.go 15 KB

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