sheet.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. package excelize
  2. import (
  3. "bytes"
  4. "encoding/xml"
  5. "fmt"
  6. "strconv"
  7. "strings"
  8. )
  9. // Define the empty element and self-close XML tags hack rules for
  10. // xl/workbook.xml and xl/worksheets/sheet%d.xml.
  11. var (
  12. WorkbookRules = []map[string]string{
  13. {`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id="`: `r:id="`},
  14. {`></sheet>`: ` />`},
  15. {`></workbookView>`: ` />`},
  16. {`></fileVersion>`: ` />`},
  17. {`></workbookPr>`: ` />`},
  18. {`></calcPr>`: ` />`},
  19. {`></workbookProtection>`: ` />`},
  20. {`></fileRecoveryPr>`: ` />`},
  21. {`></hyperlink>`: ` />`},
  22. {`></tabColor>`: ` />`},
  23. {`></pageSetUpPr>`: ` />`},
  24. {`></pane>`: ` />`},
  25. {`<extLst></extLst>`: ``},
  26. {`<fileRecoveryPr />`: ``},
  27. {`<workbookProtection />`: ``},
  28. {`<pivotCaches></pivotCaches>`: ``},
  29. {`<externalReferences></externalReferences>`: ``},
  30. {`<workbookProtection></workbookProtection>`: ``},
  31. {`<definedNames></definedNames>`: ``},
  32. {`<fileRecoveryPr></fileRecoveryPr>`: ``},
  33. {`<workbookPr />`: ``},
  34. }
  35. SheetRules = []map[string]string{
  36. {`xmlns:relationships="http://schemas.openxmlformats.org/officeDocument/2006/relationships" relationships:id="`: `r:id="`},
  37. {`<drawing></drawing>`: ``},
  38. {`<drawing />`: ``},
  39. {`<hyperlinks></hyperlinks>`: ``},
  40. {`<tableParts count="0"></tableParts>`: ``},
  41. {`<picture></picture>`: ``},
  42. {`<legacyDrawing></legacyDrawing>`: ``},
  43. {`<tabColor></tabColor>`: ``},
  44. {`<sheetProtection></sheetProtection>`: ``},
  45. {`<conditionalFormatting></conditionalFormatting>`: ``},
  46. {`<extLst></extLst>`: ``},
  47. {`></tablePart>`: ` />`},
  48. {`></dimension>`: ` />`},
  49. {`></selection>`: ` />`},
  50. {`></sheetFormatPr>`: ` />`},
  51. {`></printOptions>`: ` />`},
  52. {`></pageSetup>`: ` />`},
  53. {`></pageMargins>`: ` />`},
  54. {`></mergeCell>`: ` />`},
  55. }
  56. )
  57. // NewSheet provice function to greate a new sheet by given index, when
  58. // creating a new XLSX file, the default sheet will be create, when you
  59. // create a new file, you need to ensure that the index is continuous.
  60. func (f *File) NewSheet(index int, name string) {
  61. // Update docProps/app.xml
  62. f.setAppXML()
  63. // Update [Content_Types].xml
  64. f.setContentTypes(index)
  65. // Create new sheet /xl/worksheets/sheet%d.xml
  66. f.setSheet(index)
  67. // Update xl/_rels/workbook.xml.rels
  68. rid := f.addXlsxWorkbookRels(index)
  69. // Update xl/workbook.xml
  70. f.setWorkbook(name, rid)
  71. }
  72. // Read and update property of contents type of XLSX.
  73. func (f *File) setContentTypes(index int) {
  74. var content xlsxTypes
  75. xml.Unmarshal([]byte(f.readXML(`[Content_Types].xml`)), &content)
  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. output, err := xml.Marshal(content)
  81. if err != nil {
  82. fmt.Println(err)
  83. }
  84. f.saveFileList(`[Content_Types].xml`, string(output))
  85. }
  86. // Update sheet property by given index.
  87. func (f *File) setSheet(index int) {
  88. var xlsx xlsxWorksheet
  89. xlsx.Dimension.Ref = `A1`
  90. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  91. WorkbookViewID: 0,
  92. })
  93. output, err := xml.Marshal(xlsx)
  94. if err != nil {
  95. fmt.Println(err)
  96. }
  97. path := `xl/worksheets/sheet` + strconv.Itoa(index) + `.xml`
  98. f.saveFileList(path, replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(output))))
  99. }
  100. // Update workbook property of XLSX. Maximum 31 characters allowed in sheet title.
  101. func (f *File) setWorkbook(name string, rid int) {
  102. var content xlsxWorkbook
  103. if len(name) > 31 {
  104. name = name[0:31]
  105. }
  106. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  107. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  108. Name: name,
  109. SheetID: strconv.Itoa(rid),
  110. ID: `rId` + strconv.Itoa(rid),
  111. })
  112. output, err := xml.Marshal(content)
  113. if err != nil {
  114. fmt.Println(err)
  115. }
  116. f.saveFileList(`xl/workbook.xml`, workBookCompatibility(replaceRelationshipsNameSpace(string(output))))
  117. }
  118. // Read and unmarshal workbook relationships of XLSX.
  119. func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
  120. var content xlsxWorkbookRels
  121. xml.Unmarshal([]byte(f.readXML(`xl/_rels/workbook.xml.rels`)), &content)
  122. return content
  123. }
  124. // Update workbook relationships property of XLSX.
  125. func (f *File) addXlsxWorkbookRels(sheet int) int {
  126. content := f.readXlsxWorkbookRels()
  127. rID := len(content.Relationships) + 1
  128. ID := bytes.Buffer{}
  129. ID.WriteString(`rId`)
  130. ID.WriteString(strconv.Itoa(rID))
  131. target := bytes.Buffer{}
  132. target.WriteString(`worksheets/sheet`)
  133. target.WriteString(strconv.Itoa(sheet))
  134. target.WriteString(`.xml`)
  135. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  136. ID: ID.String(),
  137. Target: target.String(),
  138. Type: `http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet`,
  139. })
  140. output, err := xml.Marshal(content)
  141. if err != nil {
  142. fmt.Println(err)
  143. }
  144. f.saveFileList(`xl/_rels/workbook.xml.rels`, string(output))
  145. return rID
  146. }
  147. // Update docProps/app.xml file of XML.
  148. func (f *File) setAppXML() {
  149. f.saveFileList(`docProps/app.xml`, templateDocpropsApp)
  150. }
  151. // Some tools that read XLSX files have very strict requirements about
  152. // the structure of the input XML. In particular both Numbers on the Mac
  153. // and SAS dislike inline XML namespace declarations, or namespace
  154. // prefixes that don't match the ones that Excel itself uses. This is a
  155. // problem because the Go XML library doesn't multiple namespace
  156. // declarations in a single element of a document. This function is a
  157. // horrible hack to fix that after the XML marshalling is completed.
  158. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  159. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  160. 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">`
  161. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  162. }
  163. // SetActiveSheet provide function to set default active sheet of XLSX by given index.
  164. func (f *File) SetActiveSheet(index int) {
  165. var content xlsxWorkbook
  166. if index < 1 {
  167. index = 1
  168. }
  169. index--
  170. xml.Unmarshal([]byte(f.readXML(`xl/workbook.xml`)), &content)
  171. if len(content.BookViews.WorkBookView) > 0 {
  172. content.BookViews.WorkBookView[0].ActiveTab = index
  173. } else {
  174. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  175. ActiveTab: index,
  176. })
  177. }
  178. sheets := len(content.Sheets.Sheet)
  179. output, err := xml.Marshal(content)
  180. if err != nil {
  181. fmt.Println(err)
  182. }
  183. f.saveFileList(`xl/workbook.xml`, workBookCompatibility(replaceRelationshipsNameSpace(string(output))))
  184. index++
  185. buffer := bytes.Buffer{}
  186. for i := 0; i < sheets; i++ {
  187. xlsx := xlsxWorksheet{}
  188. sheetIndex := i + 1
  189. buffer.WriteString(`xl/worksheets/sheet`)
  190. buffer.WriteString(strconv.Itoa(sheetIndex))
  191. buffer.WriteString(`.xml`)
  192. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  193. if index == sheetIndex {
  194. if len(xlsx.SheetViews.SheetView) > 0 {
  195. xlsx.SheetViews.SheetView[0].TabSelected = true
  196. } else {
  197. xlsx.SheetViews.SheetView = append(xlsx.SheetViews.SheetView, xlsxSheetView{
  198. TabSelected: true,
  199. })
  200. }
  201. } else {
  202. if len(xlsx.SheetViews.SheetView) > 0 {
  203. xlsx.SheetViews.SheetView[0].TabSelected = false
  204. }
  205. }
  206. sheet, err := xml.Marshal(xlsx)
  207. if err != nil {
  208. fmt.Println(err)
  209. }
  210. f.saveFileList(buffer.String(), replaceRelationshipsID(replaceWorkSheetsRelationshipsNameSpace(string(sheet))))
  211. buffer.Reset()
  212. }
  213. return
  214. }
  215. // Replace xl/workbook.xml XML tags to self-closing for compatible Office Excel 2007.
  216. func workBookCompatibility(workbookMarshal string) string {
  217. for _, rules := range WorkbookRules {
  218. for k, v := range rules {
  219. workbookMarshal = strings.Replace(workbookMarshal, k, v, -1)
  220. }
  221. }
  222. return workbookMarshal
  223. }
  224. // replace relationships ID in worksheets/sheet%d.xml
  225. func replaceRelationshipsID(workbookMarshal string) string {
  226. for _, rules := range SheetRules {
  227. for k, v := range rules {
  228. workbookMarshal = strings.Replace(workbookMarshal, k, v, -1)
  229. }
  230. }
  231. return workbookMarshal
  232. }