sheet_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. package excelize
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "strconv"
  6. "strings"
  7. "testing"
  8. "github.com/mohae/deepcopy"
  9. "github.com/stretchr/testify/assert"
  10. )
  11. func ExampleFile_SetPageLayout() {
  12. f := NewFile()
  13. if err := f.SetPageLayout(
  14. "Sheet1",
  15. BlackAndWhite(true),
  16. FirstPageNumber(2),
  17. PageLayoutOrientation(OrientationLandscape),
  18. PageLayoutPaperSize(10),
  19. FitToHeight(2),
  20. FitToWidth(2),
  21. PageLayoutScale(50),
  22. ); err != nil {
  23. fmt.Println(err)
  24. }
  25. // Output:
  26. }
  27. func ExampleFile_GetPageLayout() {
  28. f := NewFile()
  29. var (
  30. blackAndWhite BlackAndWhite
  31. firstPageNumber FirstPageNumber
  32. orientation PageLayoutOrientation
  33. paperSize PageLayoutPaperSize
  34. fitToHeight FitToHeight
  35. fitToWidth FitToWidth
  36. scale PageLayoutScale
  37. )
  38. if err := f.GetPageLayout("Sheet1", &blackAndWhite); err != nil {
  39. fmt.Println(err)
  40. }
  41. if err := f.GetPageLayout("Sheet1", &firstPageNumber); err != nil {
  42. fmt.Println(err)
  43. }
  44. if err := f.GetPageLayout("Sheet1", &orientation); err != nil {
  45. fmt.Println(err)
  46. }
  47. if err := f.GetPageLayout("Sheet1", &paperSize); err != nil {
  48. fmt.Println(err)
  49. }
  50. if err := f.GetPageLayout("Sheet1", &fitToHeight); err != nil {
  51. fmt.Println(err)
  52. }
  53. if err := f.GetPageLayout("Sheet1", &fitToWidth); err != nil {
  54. fmt.Println(err)
  55. }
  56. if err := f.GetPageLayout("Sheet1", &scale); err != nil {
  57. fmt.Println(err)
  58. }
  59. fmt.Println("Defaults:")
  60. fmt.Printf("- print black and white: %t\n", blackAndWhite)
  61. fmt.Printf("- page number for first printed page: %d\n", firstPageNumber)
  62. fmt.Printf("- orientation: %q\n", orientation)
  63. fmt.Printf("- paper size: %d\n", paperSize)
  64. fmt.Printf("- fit to height: %d\n", fitToHeight)
  65. fmt.Printf("- fit to width: %d\n", fitToWidth)
  66. fmt.Printf("- scale: %d\n", scale)
  67. // Output:
  68. // Defaults:
  69. // - print black and white: false
  70. // - page number for first printed page: 1
  71. // - orientation: "portrait"
  72. // - paper size: 1
  73. // - fit to height: 1
  74. // - fit to width: 1
  75. // - scale: 100
  76. }
  77. func TestNewSheet(t *testing.T) {
  78. f := NewFile()
  79. sheetID := f.NewSheet("Sheet2")
  80. f.SetActiveSheet(sheetID)
  81. // delete original sheet
  82. f.DeleteSheet(f.GetSheetName(f.GetSheetIndex("Sheet1")))
  83. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestNewSheet.xlsx")))
  84. // create new worksheet with already exists name
  85. assert.Equal(t, f.GetSheetIndex("Sheet2"), f.NewSheet("Sheet2"))
  86. }
  87. func TestSetPane(t *testing.T) {
  88. f := NewFile()
  89. assert.NoError(t, f.SetPanes("Sheet1", `{"freeze":false,"split":false}`))
  90. f.NewSheet("Panes 2")
  91. assert.NoError(t, f.SetPanes("Panes 2", `{"freeze":true,"split":false,"x_split":1,"y_split":0,"top_left_cell":"B1","active_pane":"topRight","panes":[{"sqref":"K16","active_cell":"K16","pane":"topRight"}]}`))
  92. f.NewSheet("Panes 3")
  93. assert.NoError(t, f.SetPanes("Panes 3", `{"freeze":false,"split":true,"x_split":3270,"y_split":1800,"top_left_cell":"N57","active_pane":"bottomLeft","panes":[{"sqref":"I36","active_cell":"I36"},{"sqref":"G33","active_cell":"G33","pane":"topRight"},{"sqref":"J60","active_cell":"J60","pane":"bottomLeft"},{"sqref":"O60","active_cell":"O60","pane":"bottomRight"}]}`))
  94. f.NewSheet("Panes 4")
  95. assert.NoError(t, f.SetPanes("Panes 4", `{"freeze":true,"split":false,"x_split":0,"y_split":9,"top_left_cell":"A34","active_pane":"bottomLeft","panes":[{"sqref":"A11:XFD11","active_cell":"A11","pane":"bottomLeft"}]}`))
  96. assert.NoError(t, f.SetPanes("Panes 4", ""))
  97. assert.EqualError(t, f.SetPanes("SheetN", ""), "sheet SheetN is not exist")
  98. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetPane.xlsx")))
  99. }
  100. func TestPageLayoutOption(t *testing.T) {
  101. const sheet = "Sheet1"
  102. testData := []struct {
  103. container PageLayoutOptionPtr
  104. nonDefault PageLayoutOption
  105. }{
  106. {new(BlackAndWhite), BlackAndWhite(true)},
  107. {new(FirstPageNumber), FirstPageNumber(2)},
  108. {new(PageLayoutOrientation), PageLayoutOrientation(OrientationLandscape)},
  109. {new(PageLayoutPaperSize), PageLayoutPaperSize(10)},
  110. {new(FitToHeight), FitToHeight(2)},
  111. {new(FitToWidth), FitToWidth(2)},
  112. {new(PageLayoutScale), PageLayoutScale(50)},
  113. }
  114. for i, test := range testData {
  115. t.Run(fmt.Sprintf("TestData%d", i), func(t *testing.T) {
  116. opt := test.nonDefault
  117. t.Logf("option %T", opt)
  118. def := deepcopy.Copy(test.container).(PageLayoutOptionPtr)
  119. val1 := deepcopy.Copy(def).(PageLayoutOptionPtr)
  120. val2 := deepcopy.Copy(def).(PageLayoutOptionPtr)
  121. f := NewFile()
  122. // Get the default value
  123. assert.NoError(t, f.GetPageLayout(sheet, def), opt)
  124. // Get again and check
  125. assert.NoError(t, f.GetPageLayout(sheet, val1), opt)
  126. if !assert.Equal(t, val1, def, opt) {
  127. t.FailNow()
  128. }
  129. // Set the same value
  130. assert.NoError(t, f.SetPageLayout(sheet, val1), opt)
  131. // Get again and check
  132. assert.NoError(t, f.GetPageLayout(sheet, val1), opt)
  133. if !assert.Equal(t, val1, def, "%T: value should not have changed", opt) {
  134. t.FailNow()
  135. }
  136. // Set a different value
  137. assert.NoError(t, f.SetPageLayout(sheet, test.nonDefault), opt)
  138. assert.NoError(t, f.GetPageLayout(sheet, val1), opt)
  139. // Get again and compare
  140. assert.NoError(t, f.GetPageLayout(sheet, val2), opt)
  141. if !assert.Equal(t, val1, val2, "%T: value should not have changed", opt) {
  142. t.FailNow()
  143. }
  144. // Value should not be the same as the default
  145. if !assert.NotEqual(t, def, val1, "%T: value should have changed from default", opt) {
  146. t.FailNow()
  147. }
  148. // Restore the default value
  149. assert.NoError(t, f.SetPageLayout(sheet, def), opt)
  150. assert.NoError(t, f.GetPageLayout(sheet, val1), opt)
  151. if !assert.Equal(t, def, val1) {
  152. t.FailNow()
  153. }
  154. })
  155. }
  156. }
  157. func TestSearchSheet(t *testing.T) {
  158. f, err := OpenFile(filepath.Join("test", "SharedStrings.xlsx"))
  159. if !assert.NoError(t, err) {
  160. t.FailNow()
  161. }
  162. // Test search in a not exists worksheet.
  163. _, err = f.SearchSheet("Sheet4", "")
  164. assert.EqualError(t, err, "sheet Sheet4 is not exist")
  165. var expected []string
  166. // Test search a not exists value.
  167. result, err := f.SearchSheet("Sheet1", "X")
  168. assert.NoError(t, err)
  169. assert.EqualValues(t, expected, result)
  170. result, err = f.SearchSheet("Sheet1", "A")
  171. assert.NoError(t, err)
  172. assert.EqualValues(t, []string{"A1"}, result)
  173. // Test search the coordinates where the numerical value in the range of
  174. // "0-9" of Sheet1 is described by regular expression:
  175. result, err = f.SearchSheet("Sheet1", "[0-9]", true)
  176. assert.NoError(t, err)
  177. assert.EqualValues(t, expected, result)
  178. // Test search worksheet data after set cell value
  179. f = NewFile()
  180. assert.NoError(t, f.SetCellValue("Sheet1", "A1", true))
  181. _, err = f.SearchSheet("Sheet1", "")
  182. assert.NoError(t, err)
  183. }
  184. func TestSetPageLayout(t *testing.T) {
  185. f := NewFile()
  186. // Test set page layout on not exists worksheet.
  187. assert.EqualError(t, f.SetPageLayout("SheetN"), "sheet SheetN is not exist")
  188. }
  189. func TestGetPageLayout(t *testing.T) {
  190. f := NewFile()
  191. // Test get page layout on not exists worksheet.
  192. assert.EqualError(t, f.GetPageLayout("SheetN"), "sheet SheetN is not exist")
  193. }
  194. func TestSetHeaderFooter(t *testing.T) {
  195. f := NewFile()
  196. assert.NoError(t, f.SetCellStr("Sheet1", "A1", "Test SetHeaderFooter"))
  197. // Test set header and footer on not exists worksheet.
  198. assert.EqualError(t, f.SetHeaderFooter("SheetN", nil), "sheet SheetN is not exist")
  199. // Test set header and footer with illegal setting.
  200. assert.EqualError(t, f.SetHeaderFooter("Sheet1", &FormatHeaderFooter{
  201. OddHeader: strings.Repeat("c", 256),
  202. }), "field OddHeader must be less than 255 characters")
  203. assert.NoError(t, f.SetHeaderFooter("Sheet1", nil))
  204. assert.NoError(t, f.SetHeaderFooter("Sheet1", &FormatHeaderFooter{
  205. DifferentFirst: true,
  206. DifferentOddEven: true,
  207. OddHeader: "&R&P",
  208. OddFooter: "&C&F",
  209. EvenHeader: "&L&P",
  210. EvenFooter: "&L&D&R&T",
  211. FirstHeader: `&CCenter &"-,Bold"Bold&"-,Regular"HeaderU+000A&D`,
  212. }))
  213. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetHeaderFooter.xlsx")))
  214. }
  215. func TestDefinedName(t *testing.T) {
  216. f := NewFile()
  217. assert.NoError(t, f.SetDefinedName(&DefinedName{
  218. Name: "Amount",
  219. RefersTo: "Sheet1!$A$2:$D$5",
  220. Comment: "defined name comment",
  221. Scope: "Sheet1",
  222. }))
  223. assert.NoError(t, f.SetDefinedName(&DefinedName{
  224. Name: "Amount",
  225. RefersTo: "Sheet1!$A$2:$D$5",
  226. Comment: "defined name comment",
  227. }))
  228. assert.EqualError(t, f.SetDefinedName(&DefinedName{
  229. Name: "Amount",
  230. RefersTo: "Sheet1!$A$2:$D$5",
  231. Comment: "defined name comment",
  232. }), "the same name already exists on the scope")
  233. assert.EqualError(t, f.DeleteDefinedName(&DefinedName{
  234. Name: "No Exist Defined Name",
  235. }), "no defined name on the scope")
  236. assert.Exactly(t, "Sheet1!$A$2:$D$5", f.GetDefinedName()[1].RefersTo)
  237. assert.NoError(t, f.DeleteDefinedName(&DefinedName{
  238. Name: "Amount",
  239. }))
  240. assert.Exactly(t, "Sheet1!$A$2:$D$5", f.GetDefinedName()[0].RefersTo)
  241. assert.Exactly(t, 1, len(f.GetDefinedName()))
  242. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestDefinedName.xlsx")))
  243. }
  244. func TestGroupSheets(t *testing.T) {
  245. f := NewFile()
  246. sheets := []string{"Sheet2", "Sheet3"}
  247. for _, sheet := range sheets {
  248. f.NewSheet(sheet)
  249. }
  250. assert.EqualError(t, f.GroupSheets([]string{"Sheet1", "SheetN"}), "sheet SheetN is not exist")
  251. assert.EqualError(t, f.GroupSheets([]string{"Sheet2", "Sheet3"}), "group worksheet must contain an active worksheet")
  252. assert.NoError(t, f.GroupSheets([]string{"Sheet1", "Sheet2"}))
  253. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestGroupSheets.xlsx")))
  254. }
  255. func TestUngroupSheets(t *testing.T) {
  256. f := NewFile()
  257. sheets := []string{"Sheet2", "Sheet3", "Sheet4", "Sheet5"}
  258. for _, sheet := range sheets {
  259. f.NewSheet(sheet)
  260. }
  261. assert.NoError(t, f.UngroupSheets())
  262. }
  263. func TestInsertPageBreak(t *testing.T) {
  264. f := NewFile()
  265. assert.NoError(t, f.InsertPageBreak("Sheet1", "A1"))
  266. assert.NoError(t, f.InsertPageBreak("Sheet1", "B2"))
  267. assert.NoError(t, f.InsertPageBreak("Sheet1", "C3"))
  268. assert.NoError(t, f.InsertPageBreak("Sheet1", "C3"))
  269. assert.EqualError(t, f.InsertPageBreak("Sheet1", "A"), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  270. assert.EqualError(t, f.InsertPageBreak("SheetN", "C3"), "sheet SheetN is not exist")
  271. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestInsertPageBreak.xlsx")))
  272. }
  273. func TestRemovePageBreak(t *testing.T) {
  274. f := NewFile()
  275. assert.NoError(t, f.RemovePageBreak("Sheet1", "A2"))
  276. assert.NoError(t, f.InsertPageBreak("Sheet1", "A2"))
  277. assert.NoError(t, f.InsertPageBreak("Sheet1", "B2"))
  278. assert.NoError(t, f.RemovePageBreak("Sheet1", "A1"))
  279. assert.NoError(t, f.RemovePageBreak("Sheet1", "B2"))
  280. assert.NoError(t, f.InsertPageBreak("Sheet1", "C3"))
  281. assert.NoError(t, f.RemovePageBreak("Sheet1", "C3"))
  282. assert.NoError(t, f.InsertPageBreak("Sheet1", "A3"))
  283. assert.NoError(t, f.RemovePageBreak("Sheet1", "B3"))
  284. assert.NoError(t, f.RemovePageBreak("Sheet1", "A3"))
  285. f.NewSheet("Sheet2")
  286. assert.NoError(t, f.InsertPageBreak("Sheet2", "B2"))
  287. assert.NoError(t, f.InsertPageBreak("Sheet2", "C2"))
  288. assert.NoError(t, f.RemovePageBreak("Sheet2", "B2"))
  289. assert.EqualError(t, f.RemovePageBreak("Sheet1", "A"), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  290. assert.EqualError(t, f.RemovePageBreak("SheetN", "C3"), "sheet SheetN is not exist")
  291. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestRemovePageBreak.xlsx")))
  292. }
  293. func TestGetSheetName(t *testing.T) {
  294. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  295. assert.NoError(t, err)
  296. assert.Equal(t, "Sheet1", f.GetSheetName(0))
  297. assert.Equal(t, "Sheet2", f.GetSheetName(1))
  298. assert.Equal(t, "", f.GetSheetName(-1))
  299. assert.Equal(t, "", f.GetSheetName(2))
  300. }
  301. func TestGetSheetMap(t *testing.T) {
  302. expectedMap := map[int]string{
  303. 1: "Sheet1",
  304. 2: "Sheet2",
  305. }
  306. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  307. assert.NoError(t, err)
  308. sheetMap := f.GetSheetMap()
  309. for idx, name := range sheetMap {
  310. assert.Equal(t, expectedMap[idx], name)
  311. }
  312. assert.Equal(t, len(sheetMap), 2)
  313. }
  314. func TestSetActiveSheet(t *testing.T) {
  315. f := NewFile()
  316. f.WorkBook.BookViews = nil
  317. f.SetActiveSheet(1)
  318. f.WorkBook.BookViews = &xlsxBookViews{WorkBookView: []xlsxWorkBookView{}}
  319. f.Sheet["xl/worksheets/sheet1.xml"].SheetViews = &xlsxSheetViews{SheetView: []xlsxSheetView{}}
  320. f.SetActiveSheet(1)
  321. f.Sheet["xl/worksheets/sheet1.xml"].SheetViews = nil
  322. f.SetActiveSheet(1)
  323. f = NewFile()
  324. f.SetActiveSheet(-1)
  325. assert.Equal(t, f.GetActiveSheetIndex(), 0)
  326. }
  327. func TestSetSheetName(t *testing.T) {
  328. f := NewFile()
  329. // Test set workksheet with the same name.
  330. f.SetSheetName("Sheet1", "Sheet1")
  331. assert.Equal(t, "Sheet1", f.GetSheetName(0))
  332. }
  333. func TestGetWorkbookPath(t *testing.T) {
  334. f := NewFile()
  335. delete(f.XLSX, "_rels/.rels")
  336. assert.Equal(t, "", f.getWorkbookPath())
  337. }
  338. func TestGetWorkbookRelsPath(t *testing.T) {
  339. f := NewFile()
  340. delete(f.XLSX, "xl/_rels/.rels")
  341. f.XLSX["_rels/.rels"] = []byte(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://purl.oclc.org/ooxml/officeDocument/relationships/officeDocument" Target="/workbook.xml"/></Relationships>`)
  342. assert.Equal(t, "_rels/workbook.xml.rels", f.getWorkbookRelsPath())
  343. }
  344. func TestDeleteSheet(t *testing.T) {
  345. f := NewFile()
  346. f.SetActiveSheet(f.NewSheet("Sheet2"))
  347. f.NewSheet("Sheet3")
  348. f.DeleteSheet("Sheet1")
  349. assert.Equal(t, "Sheet2", f.GetSheetName(f.GetActiveSheetIndex()))
  350. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestDeleteSheet.xlsx")))
  351. // Test with auto filter defined names
  352. f = NewFile()
  353. f.NewSheet("Sheet2")
  354. f.NewSheet("Sheet3")
  355. assert.NoError(t, f.SetCellValue("Sheet1", "A1", "A"))
  356. assert.NoError(t, f.SetCellValue("Sheet2", "A1", "A"))
  357. assert.NoError(t, f.SetCellValue("Sheet3", "A1", "A"))
  358. assert.NoError(t, f.AutoFilter("Sheet1", "A1", "A1", ""))
  359. assert.NoError(t, f.AutoFilter("Sheet2", "A1", "A1", ""))
  360. assert.NoError(t, f.AutoFilter("Sheet3", "A1", "A1", ""))
  361. f.DeleteSheet("Sheet2")
  362. f.DeleteSheet("Sheet1")
  363. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestDeleteSheet2.xlsx")))
  364. }
  365. func BenchmarkNewSheet(b *testing.B) {
  366. b.RunParallel(func(pb *testing.PB) {
  367. for pb.Next() {
  368. newSheetWithSet()
  369. }
  370. })
  371. }
  372. func newSheetWithSet() {
  373. file := NewFile()
  374. file.NewSheet("sheet1")
  375. for i := 0; i < 1000; i++ {
  376. _ = file.SetCellInt("sheet1", "A"+strconv.Itoa(i+1), i)
  377. }
  378. file = nil
  379. }
  380. func BenchmarkFile_SaveAs(b *testing.B) {
  381. b.RunParallel(func(pb *testing.PB) {
  382. for pb.Next() {
  383. newSheetWithSave()
  384. }
  385. })
  386. }
  387. func newSheetWithSave() {
  388. file := NewFile()
  389. file.NewSheet("sheet1")
  390. for i := 0; i < 1000; i++ {
  391. _ = file.SetCellInt("sheet1", "A"+strconv.Itoa(i+1), i)
  392. }
  393. _ = file.Save()
  394. }