sheet.go 9.4 KB

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