sheet.go 8.6 KB

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