sheet.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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
  10. // creating a new XLSX file, the default sheet will be create, when you
  11. // create a new 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. // Update workbook property of XLSX. Maximum 31 characters allowed in sheet title.
  53. func (f *File) setWorkbook(name string, rid int) {
  54. var content xlsxWorkbook
  55. if len(name) > 31 {
  56. name = name[0:31]
  57. }
  58. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  59. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  60. Name: name,
  61. SheetID: strconv.Itoa(rid),
  62. ID: `rId` + strconv.Itoa(rid),
  63. })
  64. output, err := xml.Marshal(content)
  65. if err != nil {
  66. fmt.Println(err)
  67. }
  68. f.saveFileList(`xl/workbook.xml`, replaceRelationshipsNameSpace(string(output)))
  69. }
  70. // Read and unmarshal workbook relationships of XLSX.
  71. func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
  72. var content xlsxWorkbookRels
  73. xml.Unmarshal([]byte(f.readXML(`xl/_rels/workbook.xml.rels`)), &content)
  74. return content
  75. }
  76. // Update workbook relationships property of XLSX.
  77. func (f *File) addXlsxWorkbookRels(sheet int) int {
  78. content := f.readXlsxWorkbookRels()
  79. rID := len(content.Relationships) + 1
  80. ID := bytes.Buffer{}
  81. ID.WriteString(`rId`)
  82. ID.WriteString(strconv.Itoa(rID))
  83. target := bytes.Buffer{}
  84. target.WriteString(`worksheets/sheet`)
  85. target.WriteString(strconv.Itoa(sheet))
  86. target.WriteString(`.xml`)
  87. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  88. ID: ID.String(),
  89. Target: target.String(),
  90. Type: `http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,
  91. })
  92. output, err := xml.Marshal(content)
  93. if err != nil {
  94. fmt.Println(err)
  95. }
  96. f.saveFileList(`xl/_rels/workbook.xml.rels`, string(output))
  97. return rID
  98. }
  99. // Update docProps/app.xml file of XML.
  100. func (f *File) setAppXML() {
  101. f.saveFileList(`docProps/app.xml`, templateDocpropsApp)
  102. }
  103. // Some tools that read XLSX files have very strict requirements about
  104. // the structure of the input XML. In particular both Numbers on the Mac
  105. // and SAS dislike inline XML namespace declarations, or namespace
  106. // prefixes that don't match the ones that Excel itself uses. This is a
  107. // problem because the Go XML library doesn't multiple namespace
  108. // declarations in a single element of a document. This function is a
  109. // horrible hack to fix that after the XML marshalling is completed.
  110. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  111. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  112. 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">`
  113. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  114. }
  115. // SetActiveSheet provide function to set default active sheet of XLSX by given index.
  116. func (f *File) SetActiveSheet(index int) {
  117. var content xlsxWorkbook
  118. if index < 1 {
  119. index = 1
  120. }
  121. index--
  122. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  123. if len(content.BookViews.WorkBookView) > 0 {
  124. content.BookViews.WorkBookView[0].ActiveTab = index
  125. } else {
  126. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  127. ActiveTab: index,
  128. })
  129. }
  130. sheets := len(content.Sheets.Sheet)
  131. output, err := xml.Marshal(content)
  132. if err != nil {
  133. fmt.Println(err)
  134. }
  135. f.saveFileList(`xl/workbook.xml`, replaceRelationshipsNameSpace(string(output)))
  136. index++
  137. buffer := bytes.Buffer{}
  138. for i := 0; i < sheets; i++ {
  139. xlsx := xlsxWorksheet{}
  140. sheetIndex := i + 1
  141. buffer.WriteString(`xl/worksheets/sheet`)
  142. buffer.WriteString(strconv.Itoa(sheetIndex))
  143. buffer.WriteString(`.xml`)
  144. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  145. if index == sheetIndex {
  146. if len(xlsx.SheetViews.SheetView) > 0 {
  147. xlsx.SheetViews.SheetView[0].TabSelected = true
  148. } else {
  149. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  150. TabSelected: true,
  151. })
  152. }
  153. } else {
  154. if len(xlsx.SheetViews.SheetView) > 0 {
  155. xlsx.SheetViews.SheetView[0].TabSelected = false
  156. }
  157. }
  158. sheet, err := xml.Marshal(xlsx)
  159. if err != nil {
  160. fmt.Println(err)
  161. }
  162. f.saveFileList(buffer.String(), replaceWorkSheetsRelationshipsNameSpace(string(sheet)))
  163. buffer.Reset()
  164. }
  165. return
  166. }
  167. // GetActiveSheetIndex provide function to get active sheet of XLSX. If not found
  168. // the active sheet will be return integer 0.
  169. func (f *File) GetActiveSheetIndex() int {
  170. content := xlsxWorkbook{}
  171. buffer := bytes.Buffer{}
  172. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  173. for _, v := range content.Sheets.Sheet {
  174. xlsx := xlsxWorksheet{}
  175. buffer.WriteString(`xl/worksheets/sheet`)
  176. buffer.WriteString(strings.TrimPrefix(v.ID, `rId`))
  177. buffer.WriteString(`.xml`)
  178. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  179. for _, sheetView := range xlsx.SheetViews.SheetView {
  180. if sheetView.TabSelected {
  181. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, `rId`))
  182. return id
  183. }
  184. }
  185. buffer.Reset()
  186. }
  187. return 0
  188. }
  189. // GetSheetName provide function to get sheet name of XLSX by given sheet index.
  190. // If given sheet index is invalid, will return an empty string.
  191. func (f *File) GetSheetName(index int) string {
  192. content := xlsxWorkbook{}
  193. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  194. for _, v := range content.Sheets.Sheet {
  195. if v.ID == `rId`+strconv.Itoa(index) {
  196. return v.Name
  197. }
  198. }
  199. return ``
  200. }
  201. // GetSheetMap provide function to get sheet map of XLSX. For example:
  202. //
  203. // xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
  204. // if err != nil {
  205. // fmt.Println(err)
  206. // os.Exit(1)
  207. // }
  208. // for k, v := range xlsx.GetSheetMap()
  209. // fmt.Println(k, v)
  210. // }
  211. //
  212. func (f *File) GetSheetMap() map[int]string {
  213. content := xlsxWorkbook{}
  214. sheetMap := map[int]string{}
  215. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  216. for _, v := range content.Sheets.Sheet {
  217. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, `rId`))
  218. sheetMap[id] = v.Name
  219. }
  220. return sheetMap
  221. }