sheet.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. )
  9. // NewSheet provice function to greate a new sheet by given index, when creating
  10. // a new XLSX file, the default sheet will be create, when you create a new
  11. // file, you need to ensure that the index is continuous.
  12. func (f *File) NewSheet(index int, name string) {
  13. // Update docProps/app.xml
  14. f.setAppXML()
  15. // Update [Content_Types].xml
  16. f.setContentTypes(index)
  17. // Create new sheet /xl/worksheets/sheet%d.xml
  18. f.setSheet(index)
  19. // Update xl/_rels/workbook.xml.rels
  20. rid := f.addXlsxWorkbookRels(index)
  21. // Update xl/workbook.xml
  22. f.setWorkbook(name, rid)
  23. }
  24. // Read and update property of contents type of XLSX.
  25. func (f *File) setContentTypes(index int) {
  26. var content xlsxTypes
  27. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  28. content.Overrides = append(content.Overrides, xlsxOverride{
  29. PartName: "/xl/worksheets/sheet" + strconv.Itoa(index) + ".xml",
  30. ContentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml",
  31. })
  32. output, err := xml.Marshal(content)
  33. if err != nil {
  34. fmt.Println(err)
  35. }
  36. f.saveFileList("[Content_Types].xml", string(output))
  37. }
  38. // Update sheet property by given index.
  39. func (f *File) setSheet(index int) {
  40. var xlsx xlsxWorksheet
  41. xlsx.Dimension.Ref = "A1"
  42. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  43. WorkbookViewID: 0,
  44. })
  45. output, err := xml.Marshal(xlsx)
  46. if err != nil {
  47. fmt.Println(err)
  48. }
  49. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  50. f.saveFileList(path, replaceWorkSheetsRelationshipsNameSpace(string(output)))
  51. }
  52. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  53. // allowed in sheet title.
  54. func (f *File) setWorkbook(name string, rid int) {
  55. var content xlsxWorkbook
  56. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  57. name = r.Replace(name)
  58. if len(name) > 31 {
  59. name = name[0:31]
  60. }
  61. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  62. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  63. Name: name,
  64. SheetID: strconv.Itoa(rid),
  65. ID: "rId" + strconv.Itoa(rid),
  66. })
  67. output, err := xml.Marshal(content)
  68. if err != nil {
  69. fmt.Println(err)
  70. }
  71. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  72. }
  73. // readXlsxWorkbookRels read and unmarshal workbook relationships of XLSX file.
  74. func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
  75. var content xlsxWorkbookRels
  76. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  77. return content
  78. }
  79. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  80. func (f *File) addXlsxWorkbookRels(sheet int) int {
  81. content := f.readXlsxWorkbookRels()
  82. rID := len(content.Relationships) + 1
  83. ID := bytes.Buffer{}
  84. ID.WriteString("rId")
  85. ID.WriteString(strconv.Itoa(rID))
  86. target := bytes.Buffer{}
  87. target.WriteString("worksheets/sheet")
  88. target.WriteString(strconv.Itoa(sheet))
  89. target.WriteString(".xml")
  90. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  91. ID: ID.String(),
  92. Target: target.String(),
  93. Type: SourceRelationshipWorkSheet,
  94. })
  95. output, err := xml.Marshal(content)
  96. if err != nil {
  97. fmt.Println(err)
  98. }
  99. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  100. return rID
  101. }
  102. // setAppXML update docProps/app.xml file of XML.
  103. func (f *File) setAppXML() {
  104. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  105. }
  106. // Some tools that read XLSX files have very strict requirements about the
  107. // structure of the input XML. In particular both Numbers on the Mac and SAS
  108. // dislike inline XML namespace declarations, or namespace prefixes that don't
  109. // match the ones that Excel itself uses. This is a problem because the Go XML
  110. // library doesn't multiple namespace declarations in a single element of a
  111. // document. This function is a horrible hack to fix that after the XML
  112. // marshalling is completed.
  113. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  114. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  115. 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">`
  116. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  117. }
  118. // SetActiveSheet provides function to set default active sheet of XLSX by given
  119. // index.
  120. func (f *File) SetActiveSheet(index int) {
  121. var content xlsxWorkbook
  122. if index < 1 {
  123. index = 1
  124. }
  125. index--
  126. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  127. if len(content.BookViews.WorkBookView) > 0 {
  128. content.BookViews.WorkBookView[0].ActiveTab = index
  129. } else {
  130. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  131. ActiveTab: index,
  132. })
  133. }
  134. sheets := len(content.Sheets.Sheet)
  135. output, err := xml.Marshal(content)
  136. if err != nil {
  137. fmt.Println(err)
  138. }
  139. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  140. index++
  141. buffer := bytes.Buffer{}
  142. for i := 0; i < sheets; i++ {
  143. xlsx := xlsxWorksheet{}
  144. sheetIndex := i + 1
  145. buffer.WriteString("xl/worksheets/sheet")
  146. buffer.WriteString(strconv.Itoa(sheetIndex))
  147. buffer.WriteString(".xml")
  148. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  149. if index == sheetIndex {
  150. if len(xlsx.SheetViews.SheetView) > 0 {
  151. xlsx.SheetViews.SheetView[0].TabSelected = true
  152. } else {
  153. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  154. TabSelected: true,
  155. })
  156. }
  157. } else {
  158. if len(xlsx.SheetViews.SheetView) > 0 {
  159. xlsx.SheetViews.SheetView[0].TabSelected = false
  160. }
  161. }
  162. sheet, err := xml.Marshal(xlsx)
  163. if err != nil {
  164. fmt.Println(err)
  165. }
  166. f.saveFileList(buffer.String(), replaceWorkSheetsRelationshipsNameSpace(string(sheet)))
  167. buffer.Reset()
  168. }
  169. return
  170. }
  171. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  172. // found the active sheet will be return integer 0.
  173. func (f *File) GetActiveSheetIndex() int {
  174. content := xlsxWorkbook{}
  175. buffer := bytes.Buffer{}
  176. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  177. for _, v := range content.Sheets.Sheet {
  178. xlsx := xlsxWorksheet{}
  179. buffer.WriteString("xl/worksheets/sheet")
  180. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  181. buffer.WriteString(".xml")
  182. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  183. for _, sheetView := range xlsx.SheetViews.SheetView {
  184. if sheetView.TabSelected {
  185. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  186. return id
  187. }
  188. }
  189. buffer.Reset()
  190. }
  191. return 0
  192. }
  193. // SetSheetName provides function to set the sheet name be given old and new
  194. // sheet name. Maximum 31 characters are allowed in sheet title and this
  195. // function only changes the name of the sheet and will not update the sheet
  196. // name in the formula or reference associated with the cell. So there may be
  197. // problem formula error or reference missing.
  198. func (f *File) SetSheetName(oldName, newName string) {
  199. var content = xlsxWorkbook{}
  200. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  201. newName = r.Replace(newName)
  202. if len(newName) > 31 {
  203. newName = newName[0:31]
  204. }
  205. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  206. for k, v := range content.Sheets.Sheet {
  207. if v.Name == oldName {
  208. content.Sheets.Sheet[k].Name = newName
  209. }
  210. }
  211. output, _ := xml.Marshal(content)
  212. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  213. }
  214. // GetSheetName provides function to get sheet name of XLSX by given sheet
  215. // index. If given sheet index is invalid, will return an empty string.
  216. func (f *File) GetSheetName(index int) string {
  217. var content = xlsxWorkbook{}
  218. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  219. for _, v := range content.Sheets.Sheet {
  220. if v.ID == "rId"+strconv.Itoa(index) {
  221. return v.Name
  222. }
  223. }
  224. return ""
  225. }
  226. // GetSheetMap provides function to get sheet map of XLSX. For example:
  227. //
  228. // xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
  229. // if err != nil {
  230. // fmt.Println(err)
  231. // os.Exit(1)
  232. // }
  233. // for k, v := range xlsx.GetSheetMap()
  234. // fmt.Println(k, v)
  235. // }
  236. //
  237. func (f *File) GetSheetMap() map[int]string {
  238. content := xlsxWorkbook{}
  239. sheetMap := map[int]string{}
  240. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  241. for _, v := range content.Sheets.Sheet {
  242. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  243. sheetMap[id] = v.Name
  244. }
  245. return sheetMap
  246. }