sheet.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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. path := "xl/worksheets/sheet" + strconv.Itoa(index) + ".xml"
  49. f.Sheet[path] = &xlsx
  50. }
  51. // setWorkbook update workbook property of XLSX. Maximum 31 characters are
  52. // allowed in sheet title.
  53. func (f *File) setWorkbook(name string, rid int) {
  54. var content xlsxWorkbook
  55. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  56. name = r.Replace(name)
  57. if len(name) > 31 {
  58. name = name[0:31]
  59. }
  60. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  61. content.Sheets.Sheet = append(content.Sheets.Sheet, xlsxSheet{
  62. Name: name,
  63. SheetID: strconv.Itoa(rid),
  64. ID: "rId" + strconv.Itoa(rid),
  65. })
  66. output, err := xml.Marshal(content)
  67. if err != nil {
  68. fmt.Println(err)
  69. }
  70. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  71. }
  72. // readXlsxWorkbookRels read and unmarshal workbook relationships of XLSX file.
  73. func (f *File) readXlsxWorkbookRels() xlsxWorkbookRels {
  74. var content xlsxWorkbookRels
  75. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  76. return content
  77. }
  78. // addXlsxWorkbookRels update workbook relationships property of XLSX.
  79. func (f *File) addXlsxWorkbookRels(sheet int) int {
  80. content := f.readXlsxWorkbookRels()
  81. rID := 0
  82. for _, v := range content.Relationships {
  83. t, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  84. if t > rID {
  85. rID = t
  86. }
  87. }
  88. rID++
  89. ID := bytes.Buffer{}
  90. ID.WriteString("rId")
  91. ID.WriteString(strconv.Itoa(rID))
  92. target := bytes.Buffer{}
  93. target.WriteString("worksheets/sheet")
  94. target.WriteString(strconv.Itoa(sheet))
  95. target.WriteString(".xml")
  96. content.Relationships = append(content.Relationships, xlsxWorkbookRelation{
  97. ID: ID.String(),
  98. Target: target.String(),
  99. Type: SourceRelationshipWorkSheet,
  100. })
  101. output, err := xml.Marshal(content)
  102. if err != nil {
  103. fmt.Println(err)
  104. }
  105. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  106. return rID
  107. }
  108. // setAppXML update docProps/app.xml file of XML.
  109. func (f *File) setAppXML() {
  110. f.saveFileList("docProps/app.xml", templateDocpropsApp)
  111. }
  112. // Some tools that read XLSX files have very strict requirements about the
  113. // structure of the input XML. In particular both Numbers on the Mac and SAS
  114. // dislike inline XML namespace declarations, or namespace prefixes that don't
  115. // match the ones that Excel itself uses. This is a problem because the Go XML
  116. // library doesn't multiple namespace declarations in a single element of a
  117. // document. This function is a horrible hack to fix that after the XML
  118. // marshalling is completed.
  119. func replaceRelationshipsNameSpace(workbookMarshal string) string {
  120. oldXmlns := `<workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">`
  121. 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">`
  122. return strings.Replace(workbookMarshal, oldXmlns, newXmlns, -1)
  123. }
  124. // SetActiveSheet provides function to set default active sheet of XLSX by given
  125. // index.
  126. func (f *File) SetActiveSheet(index int) {
  127. var content xlsxWorkbook
  128. if index < 1 {
  129. index = 1
  130. }
  131. index--
  132. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  133. if len(content.BookViews.WorkBookView) > 0 {
  134. content.BookViews.WorkBookView[0].ActiveTab = index
  135. } else {
  136. content.BookViews.WorkBookView = append(content.BookViews.WorkBookView, xlsxWorkBookView{
  137. ActiveTab: index,
  138. })
  139. }
  140. sheets := len(content.Sheets.Sheet)
  141. output, err := xml.Marshal(content)
  142. if err != nil {
  143. fmt.Println(err)
  144. }
  145. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  146. index++
  147. for i := 0; i < sheets; i++ {
  148. sheetIndex := i + 1
  149. xlsx := f.workSheetReader("sheet" + strconv.Itoa(sheetIndex))
  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. }
  164. return
  165. }
  166. // GetActiveSheetIndex provides function to get active sheet of XLSX. If not
  167. // found the active sheet will be return integer 0.
  168. func (f *File) GetActiveSheetIndex() int {
  169. content := xlsxWorkbook{}
  170. buffer := bytes.Buffer{}
  171. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  172. for _, v := range content.Sheets.Sheet {
  173. xlsx := xlsxWorksheet{}
  174. buffer.WriteString("xl/worksheets/sheet")
  175. buffer.WriteString(strings.TrimPrefix(v.ID, "rId"))
  176. buffer.WriteString(".xml")
  177. xml.Unmarshal([]byte(f.readXML(buffer.String())), &xlsx)
  178. for _, sheetView := range xlsx.SheetViews.SheetView {
  179. if sheetView.TabSelected {
  180. ID, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  181. return ID
  182. }
  183. }
  184. buffer.Reset()
  185. }
  186. return 0
  187. }
  188. // SetSheetName provides function to set the sheet name be given old and new
  189. // sheet name. Maximum 31 characters are allowed in sheet title and this
  190. // function only changes the name of the sheet and will not update the sheet
  191. // name in the formula or reference associated with the cell. So there may be
  192. // problem formula error or reference missing.
  193. func (f *File) SetSheetName(oldName, newName string) {
  194. var content = xlsxWorkbook{}
  195. r := strings.NewReplacer(":", "", "\\", "", "/", "", "?", "", "*", "", "[", "", "]", "")
  196. newName = r.Replace(newName)
  197. if len(newName) > 31 {
  198. newName = newName[0:31]
  199. }
  200. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  201. for k, v := range content.Sheets.Sheet {
  202. if v.Name == oldName {
  203. content.Sheets.Sheet[k].Name = newName
  204. }
  205. }
  206. output, _ := xml.Marshal(content)
  207. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  208. }
  209. // GetSheetName provides function to get sheet name of XLSX by given sheet
  210. // index. If given sheet index is invalid, will return an empty string.
  211. func (f *File) GetSheetName(index int) string {
  212. var content = xlsxWorkbook{}
  213. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  214. for _, v := range content.Sheets.Sheet {
  215. if v.ID == "rId"+strconv.Itoa(index) {
  216. return v.Name
  217. }
  218. }
  219. return ""
  220. }
  221. // GetSheetMap provides function to get sheet map of XLSX. For example:
  222. //
  223. // xlsx, err := excelize.OpenFile("/tmp/Workbook.xlsx")
  224. // if err != nil {
  225. // fmt.Println(err)
  226. // os.Exit(1)
  227. // }
  228. // for k, v := range xlsx.GetSheetMap()
  229. // fmt.Println(k, v)
  230. // }
  231. //
  232. func (f *File) GetSheetMap() map[int]string {
  233. content := xlsxWorkbook{}
  234. sheetMap := map[int]string{}
  235. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  236. for _, v := range content.Sheets.Sheet {
  237. id, _ := strconv.Atoi(strings.TrimPrefix(v.ID, "rId"))
  238. sheetMap[id] = v.Name
  239. }
  240. return sheetMap
  241. }
  242. // SetSheetBackground provides function to set background picture by given sheet
  243. // index.
  244. func (f *File) SetSheetBackground(sheet, picture string) error {
  245. var err error
  246. // Check picture exists first.
  247. if _, err = os.Stat(picture); os.IsNotExist(err) {
  248. return err
  249. }
  250. ext, ok := supportImageTypes[path.Ext(picture)]
  251. if !ok {
  252. return errors.New("Unsupported image extension")
  253. }
  254. pictureID := f.countMedia() + 1
  255. rID := f.addSheetRelationships(sheet, SourceRelationshipImage, "../media/image"+strconv.Itoa(pictureID)+ext, "")
  256. f.addSheetPicture(sheet, rID)
  257. f.addMedia(picture, ext)
  258. f.setContentTypePartImageExtensions()
  259. return err
  260. }
  261. // DeleteSheet provides function to detele worksheet in a workbook by given
  262. // sheet name. Use this method with caution, which will affect changes in
  263. // references such as formulas, charts, and so on. If there is any referenced
  264. // value of the deleted worksheet, it will cause a file error when you open it.
  265. // This function will be invalid when only the one worksheet is left.
  266. func (f *File) DeleteSheet(name string) {
  267. var content xlsxWorkbook
  268. xml.Unmarshal([]byte(f.readXML("xl/workbook.xml")), &content)
  269. for k, v := range content.Sheets.Sheet {
  270. if v.Name != name || len(content.Sheets.Sheet) < 2 {
  271. continue
  272. }
  273. content.Sheets.Sheet = append(content.Sheets.Sheet[:k], content.Sheets.Sheet[k+1:]...)
  274. output, _ := xml.Marshal(content)
  275. f.saveFileList("xl/workbook.xml", replaceRelationshipsNameSpace(string(output)))
  276. sheet := "xl/worksheets/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml"
  277. rels := "xl/worksheets/_rels/sheet" + strings.TrimPrefix(v.ID, "rId") + ".xml.rels"
  278. target := f.deteleSheetFromWorkbookRels(v.ID)
  279. f.deteleSheetFromContentTypes(target)
  280. _, ok := f.XLSX[sheet]
  281. if ok {
  282. delete(f.XLSX, sheet)
  283. }
  284. _, ok = f.XLSX[rels]
  285. if ok {
  286. delete(f.XLSX, rels)
  287. }
  288. _, ok = f.Sheet[sheet]
  289. if ok {
  290. delete(f.Sheet, sheet)
  291. }
  292. }
  293. }
  294. // deteleSheetFromWorkbookRels provides function to remove worksheet
  295. // relationships by given relationships ID in the file
  296. // xl/_rels/workbook.xml.rels.
  297. func (f *File) deteleSheetFromWorkbookRels(rID string) string {
  298. var content xlsxWorkbookRels
  299. xml.Unmarshal([]byte(f.readXML("xl/_rels/workbook.xml.rels")), &content)
  300. for k, v := range content.Relationships {
  301. if v.ID != rID {
  302. continue
  303. }
  304. content.Relationships = append(content.Relationships[:k], content.Relationships[k+1:]...)
  305. output, _ := xml.Marshal(content)
  306. f.saveFileList("xl/_rels/workbook.xml.rels", string(output))
  307. return v.Target
  308. }
  309. return ""
  310. }
  311. // deteleSheetFromContentTypes provides function to remove worksheet
  312. // relationships by given target name in the file [Content_Types].xml.
  313. func (f *File) deteleSheetFromContentTypes(target string) {
  314. var content xlsxTypes
  315. xml.Unmarshal([]byte(f.readXML("[Content_Types].xml")), &content)
  316. for k, v := range content.Overrides {
  317. if v.PartName != "/xl/"+target {
  318. continue
  319. }
  320. content.Overrides = append(content.Overrides[:k], content.Overrides[k+1:]...)
  321. output, _ := xml.Marshal(content)
  322. f.saveFileList("[Content_Types].xml", string(output))
  323. }
  324. }