excelize_test.go 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346
  1. package excelize
  2. import (
  3. "bytes"
  4. "compress/gzip"
  5. "encoding/xml"
  6. "fmt"
  7. "image/color"
  8. _ "image/gif"
  9. _ "image/jpeg"
  10. _ "image/png"
  11. "io/ioutil"
  12. "math"
  13. "os"
  14. "path/filepath"
  15. "strconv"
  16. "strings"
  17. "testing"
  18. "time"
  19. "github.com/stretchr/testify/assert"
  20. )
  21. func TestOpenFile(t *testing.T) {
  22. // Test update the spreadsheet file.
  23. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  24. assert.NoError(t, err)
  25. // Test get all the rows in a not exists worksheet.
  26. _, err = f.GetRows("Sheet4")
  27. assert.EqualError(t, err, "sheet Sheet4 is not exist")
  28. // Test get all the rows in a worksheet.
  29. rows, err := f.GetRows("Sheet2")
  30. assert.NoError(t, err)
  31. for _, row := range rows {
  32. for _, cell := range row {
  33. t.Log(cell, "\t")
  34. }
  35. t.Log("\r\n")
  36. }
  37. assert.NoError(t, f.UpdateLinkedValue())
  38. assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(100.1588), 'f', -1, 32)))
  39. assert.NoError(t, f.SetCellDefault("Sheet2", "A1", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64)))
  40. // Test set cell value with illegal row number.
  41. assert.EqualError(t, f.SetCellDefault("Sheet2", "A", strconv.FormatFloat(float64(-100.1588), 'f', -1, 64)),
  42. `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  43. assert.NoError(t, f.SetCellInt("Sheet2", "A1", 100))
  44. // Test set cell integer value with illegal row number.
  45. assert.EqualError(t, f.SetCellInt("Sheet2", "A", 100), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  46. assert.NoError(t, f.SetCellStr("Sheet2", "C11", "Knowns"))
  47. // Test max characters in a cell.
  48. assert.NoError(t, f.SetCellStr("Sheet2", "D11", strings.Repeat("c", 32769)))
  49. f.NewSheet(":\\/?*[]Maximum 31 characters allowed in sheet title.")
  50. // Test set worksheet name with illegal name.
  51. f.SetSheetName("Maximum 31 characters allowed i", "[Rename]:\\/?* Maximum 31 characters allowed in sheet title.")
  52. assert.EqualError(t, f.SetCellInt("Sheet3", "A23", 10), "sheet Sheet3 is not exist")
  53. assert.EqualError(t, f.SetCellStr("Sheet3", "b230", "10"), "sheet Sheet3 is not exist")
  54. assert.EqualError(t, f.SetCellStr("Sheet10", "b230", "10"), "sheet Sheet10 is not exist")
  55. // Test set cell string value with illegal row number.
  56. assert.EqualError(t, f.SetCellStr("Sheet1", "A", "10"), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  57. f.SetActiveSheet(2)
  58. // Test get cell formula with given rows number.
  59. _, err = f.GetCellFormula("Sheet1", "B19")
  60. assert.NoError(t, err)
  61. // Test get cell formula with illegal worksheet name.
  62. _, err = f.GetCellFormula("Sheet2", "B20")
  63. assert.NoError(t, err)
  64. _, err = f.GetCellFormula("Sheet1", "B20")
  65. assert.NoError(t, err)
  66. // Test get cell formula with illegal rows number.
  67. _, err = f.GetCellFormula("Sheet1", "B")
  68. assert.EqualError(t, err, `cannot convert cell "B" to coordinates: invalid cell name "B"`)
  69. // Test get shared cell formula
  70. _, err = f.GetCellFormula("Sheet2", "H11")
  71. assert.NoError(t, err)
  72. _, err = f.GetCellFormula("Sheet2", "I11")
  73. assert.NoError(t, err)
  74. getSharedForumula(&xlsxWorksheet{}, "")
  75. // Test read cell value with given illegal rows number.
  76. _, err = f.GetCellValue("Sheet2", "a-1")
  77. assert.EqualError(t, err, `cannot convert cell "A-1" to coordinates: invalid cell name "A-1"`)
  78. _, err = f.GetCellValue("Sheet2", "A")
  79. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  80. // Test read cell value with given lowercase column number.
  81. _, err = f.GetCellValue("Sheet2", "a5")
  82. assert.NoError(t, err)
  83. _, err = f.GetCellValue("Sheet2", "C11")
  84. assert.NoError(t, err)
  85. _, err = f.GetCellValue("Sheet2", "D11")
  86. assert.NoError(t, err)
  87. _, err = f.GetCellValue("Sheet2", "D12")
  88. assert.NoError(t, err)
  89. // Test SetCellValue function.
  90. assert.NoError(t, f.SetCellValue("Sheet2", "F1", " Hello"))
  91. assert.NoError(t, f.SetCellValue("Sheet2", "G1", []byte("World")))
  92. assert.NoError(t, f.SetCellValue("Sheet2", "F2", 42))
  93. assert.NoError(t, f.SetCellValue("Sheet2", "F3", int8(1<<8/2-1)))
  94. assert.NoError(t, f.SetCellValue("Sheet2", "F4", int16(1<<16/2-1)))
  95. assert.NoError(t, f.SetCellValue("Sheet2", "F5", int32(1<<32/2-1)))
  96. assert.NoError(t, f.SetCellValue("Sheet2", "F6", int64(1<<32/2-1)))
  97. assert.NoError(t, f.SetCellValue("Sheet2", "F7", float32(42.65418)))
  98. assert.NoError(t, f.SetCellValue("Sheet2", "F8", float64(-42.65418)))
  99. assert.NoError(t, f.SetCellValue("Sheet2", "F9", float32(42)))
  100. assert.NoError(t, f.SetCellValue("Sheet2", "F10", float64(42)))
  101. assert.NoError(t, f.SetCellValue("Sheet2", "F11", uint(1<<32-1)))
  102. assert.NoError(t, f.SetCellValue("Sheet2", "F12", uint8(1<<8-1)))
  103. assert.NoError(t, f.SetCellValue("Sheet2", "F13", uint16(1<<16-1)))
  104. assert.NoError(t, f.SetCellValue("Sheet2", "F14", uint32(1<<32-1)))
  105. assert.NoError(t, f.SetCellValue("Sheet2", "F15", uint64(1<<32-1)))
  106. assert.NoError(t, f.SetCellValue("Sheet2", "F16", true))
  107. assert.NoError(t, f.SetCellValue("Sheet2", "F17", complex64(5+10i)))
  108. // Test on not exists worksheet.
  109. assert.EqualError(t, f.SetCellDefault("SheetN", "A1", ""), "sheet SheetN is not exist")
  110. assert.EqualError(t, f.SetCellFloat("SheetN", "A1", 42.65418, 2, 32), "sheet SheetN is not exist")
  111. assert.EqualError(t, f.SetCellBool("SheetN", "A1", true), "sheet SheetN is not exist")
  112. assert.EqualError(t, f.SetCellFormula("SheetN", "A1", ""), "sheet SheetN is not exist")
  113. assert.EqualError(t, f.SetCellHyperLink("SheetN", "A1", "Sheet1!A40", "Location"), "sheet SheetN is not exist")
  114. // Test boolean write
  115. booltest := []struct {
  116. value bool
  117. expected string
  118. }{
  119. {false, "0"},
  120. {true, "1"},
  121. }
  122. for _, test := range booltest {
  123. assert.NoError(t, f.SetCellValue("Sheet2", "F16", test.value))
  124. val, err := f.GetCellValue("Sheet2", "F16")
  125. assert.NoError(t, err)
  126. assert.Equal(t, test.expected, val)
  127. }
  128. assert.NoError(t, f.SetCellValue("Sheet2", "G2", nil))
  129. assert.EqualError(t, f.SetCellValue("Sheet2", "G4", time.Now()), "only UTC time expected")
  130. assert.NoError(t, f.SetCellValue("Sheet2", "G4", time.Now().UTC()))
  131. // 02:46:40
  132. assert.NoError(t, f.SetCellValue("Sheet2", "G5", time.Duration(1e13)))
  133. // Test completion column.
  134. assert.NoError(t, f.SetCellValue("Sheet2", "M2", nil))
  135. // Test read cell value with given axis large than exists row.
  136. _, err = f.GetCellValue("Sheet2", "E231")
  137. assert.NoError(t, err)
  138. // Test get active worksheet of spreadsheet and get worksheet name of spreadsheet by given worksheet index.
  139. f.GetSheetName(f.GetActiveSheetIndex())
  140. // Test get worksheet index of spreadsheet by given worksheet name.
  141. f.GetSheetIndex("Sheet1")
  142. // Test get worksheet name of spreadsheet by given invalid worksheet index.
  143. f.GetSheetName(4)
  144. // Test get worksheet map of workbook.
  145. f.GetSheetMap()
  146. for i := 1; i <= 300; i++ {
  147. assert.NoError(t, f.SetCellStr("Sheet2", "c"+strconv.Itoa(i), strconv.Itoa(i)))
  148. }
  149. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestOpenFile.xlsx")))
  150. assert.EqualError(t, f.SaveAs(filepath.Join("test", strings.Repeat("c", 199), ".xlsx")), "file name length exceeds maximum limit")
  151. }
  152. func TestSaveFile(t *testing.T) {
  153. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  154. if !assert.NoError(t, err) {
  155. t.FailNow()
  156. }
  157. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSaveFile.xlsx")))
  158. f, err = OpenFile(filepath.Join("test", "TestSaveFile.xlsx"))
  159. if !assert.NoError(t, err) {
  160. t.FailNow()
  161. }
  162. assert.NoError(t, f.Save())
  163. }
  164. func TestSaveAsWrongPath(t *testing.T) {
  165. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  166. if assert.NoError(t, err) {
  167. // Test write file to not exist directory.
  168. err = f.SaveAs("")
  169. if assert.Error(t, err) {
  170. assert.True(t, os.IsNotExist(err), "Error: %v: Expected os.IsNotExists(err) == true", err)
  171. }
  172. }
  173. }
  174. func TestCharsetTranscoder(t *testing.T) {
  175. f := NewFile()
  176. f.CharsetTranscoder(*new(charsetTranscoderFn))
  177. }
  178. func TestOpenReader(t *testing.T) {
  179. _, err := OpenReader(strings.NewReader(""))
  180. assert.EqualError(t, err, "zip: not a valid zip file")
  181. _, err = OpenReader(bytes.NewReader(oleIdentifier), Options{Password: "password"})
  182. assert.EqualError(t, err, "decrypted file failed")
  183. // Test open password protected spreadsheet created by Microsoft Office Excel 2010.
  184. f, err := OpenFile(filepath.Join("test", "encryptSHA1.xlsx"), Options{Password: "password"})
  185. assert.NoError(t, err)
  186. val, err := f.GetCellValue("Sheet1", "A1")
  187. assert.NoError(t, err)
  188. assert.Equal(t, "SECRET", val)
  189. // Test open password protected spreadsheet created by LibreOffice 7.0.0.3.
  190. f, err = OpenFile(filepath.Join("test", "encryptAES.xlsx"), Options{Password: "password"})
  191. assert.NoError(t, err)
  192. val, err = f.GetCellValue("Sheet1", "A1")
  193. assert.NoError(t, err)
  194. assert.Equal(t, "SECRET", val)
  195. // Test unexpected EOF.
  196. var b bytes.Buffer
  197. w := gzip.NewWriter(&b)
  198. defer w.Close()
  199. w.Flush()
  200. r, _ := gzip.NewReader(&b)
  201. defer r.Close()
  202. _, err = OpenReader(r)
  203. assert.EqualError(t, err, "unexpected EOF")
  204. _, err = OpenReader(bytes.NewReader([]byte{
  205. 0x50, 0x4b, 0x03, 0x04, 0x0a, 0x00, 0x09, 0x00, 0x63, 0x00, 0x47, 0xa3, 0xb6, 0x50, 0x00, 0x00,
  206. 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x70, 0x61,
  207. 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x01, 0x99, 0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00,
  208. 0x00, 0x21, 0x06, 0x59, 0xc0, 0x12, 0xf3, 0x19, 0xc7, 0x51, 0xd1, 0xc9, 0x31, 0xcb, 0xcc, 0x8a,
  209. 0xe1, 0x44, 0xe1, 0x56, 0x20, 0x24, 0x1f, 0xba, 0x09, 0xda, 0x53, 0xd5, 0xef, 0x50, 0x4b, 0x07,
  210. 0x08, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x4b, 0x01,
  211. 0x02, 0x1f, 0x00, 0x0a, 0x00, 0x09, 0x00, 0x63, 0x00, 0x47, 0xa3, 0xb6, 0x50, 0x00, 0x00, 0x00,
  212. 0x00, 0x1c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x0b, 0x00, 0x00, 0x00, 0x00,
  213. 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x61, 0x73, 0x73, 0x77,
  214. 0x6f, 0x72, 0x64, 0x01, 0x99, 0x07, 0x00, 0x02, 0x00, 0x41, 0x45, 0x03, 0x00, 0x00, 0x50, 0x4b,
  215. 0x05, 0x06, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x41, 0x00, 0x00, 0x00, 0x5d, 0x00,
  216. 0x00, 0x00, 0x00, 0x00,
  217. }))
  218. assert.EqualError(t, err, "zip: unsupported compression algorithm")
  219. }
  220. func TestBrokenFile(t *testing.T) {
  221. // Test write file with broken file struct.
  222. f := File{}
  223. t.Run("SaveWithoutName", func(t *testing.T) {
  224. assert.EqualError(t, f.Save(), "no path defined for file, consider File.WriteTo or File.Write")
  225. })
  226. t.Run("SaveAsEmptyStruct", func(t *testing.T) {
  227. // Test write file with broken file struct with given path.
  228. assert.NoError(t, f.SaveAs(filepath.Join("test", "BadWorkbook.SaveAsEmptyStruct.xlsx")))
  229. })
  230. t.Run("OpenBadWorkbook", func(t *testing.T) {
  231. // Test set active sheet without BookViews and Sheets maps in xl/workbook.xml.
  232. f3, err := OpenFile(filepath.Join("test", "BadWorkbook.xlsx"))
  233. f3.GetActiveSheetIndex()
  234. f3.SetActiveSheet(1)
  235. assert.NoError(t, err)
  236. })
  237. t.Run("OpenNotExistsFile", func(t *testing.T) {
  238. // Test open a spreadsheet file with given illegal path.
  239. _, err := OpenFile(filepath.Join("test", "NotExistsFile.xlsx"))
  240. if assert.Error(t, err) {
  241. assert.True(t, os.IsNotExist(err), "Expected os.IsNotExists(err) == true")
  242. }
  243. })
  244. }
  245. func TestNewFile(t *testing.T) {
  246. // Test create a spreadsheet file.
  247. f := NewFile()
  248. f.NewSheet("Sheet1")
  249. f.NewSheet("XLSXSheet2")
  250. f.NewSheet("XLSXSheet3")
  251. assert.NoError(t, f.SetCellInt("XLSXSheet2", "A23", 56))
  252. assert.NoError(t, f.SetCellStr("Sheet1", "B20", "42"))
  253. f.SetActiveSheet(0)
  254. // Test add picture to sheet with scaling and positioning.
  255. err := f.AddPicture("Sheet1", "H2", filepath.Join("test", "images", "excel.gif"),
  256. `{"x_scale": 0.5, "y_scale": 0.5, "positioning": "absolute"}`)
  257. if !assert.NoError(t, err) {
  258. t.FailNow()
  259. }
  260. // Test add picture to worksheet without formatset.
  261. err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), "")
  262. if !assert.NoError(t, err) {
  263. t.FailNow()
  264. }
  265. // Test add picture to worksheet with invalid formatset.
  266. err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), `{`)
  267. if !assert.Error(t, err) {
  268. t.FailNow()
  269. }
  270. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestNewFile.xlsx")))
  271. }
  272. func TestAddDrawingVML(t *testing.T) {
  273. // Test addDrawingVML with illegal cell coordinates.
  274. f := NewFile()
  275. assert.EqualError(t, f.addDrawingVML(0, "", "*", 0, 0), `cannot convert cell "*" to coordinates: invalid cell name "*"`)
  276. }
  277. func TestSetCellHyperLink(t *testing.T) {
  278. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  279. if err != nil {
  280. t.Log(err)
  281. }
  282. // Test set cell hyperlink in a work sheet already have hyperlinks.
  283. assert.NoError(t, f.SetCellHyperLink("Sheet1", "B19", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))
  284. // Test add first hyperlink in a work sheet.
  285. assert.NoError(t, f.SetCellHyperLink("Sheet2", "C1", "https://github.com/360EntSecGroup-Skylar/excelize", "External"))
  286. // Test add Location hyperlink in a work sheet.
  287. assert.NoError(t, f.SetCellHyperLink("Sheet2", "D6", "Sheet1!D8", "Location"))
  288. // Test add Location hyperlink with display & tooltip in a work sheet.
  289. display := "Display value"
  290. tooltip := "Hover text"
  291. assert.NoError(t, f.SetCellHyperLink("Sheet2", "D7", "Sheet1!D9", "Location", HyperlinkOpts{
  292. Display: &display,
  293. Tooltip: &tooltip,
  294. }))
  295. assert.EqualError(t, f.SetCellHyperLink("Sheet2", "C3", "Sheet1!D8", ""), `invalid link type ""`)
  296. assert.EqualError(t, f.SetCellHyperLink("Sheet2", "", "Sheet1!D60", "Location"), `invalid cell name ""`)
  297. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellHyperLink.xlsx")))
  298. f = NewFile()
  299. _, err = f.workSheetReader("Sheet1")
  300. assert.NoError(t, err)
  301. f.Sheet["xl/worksheets/sheet1.xml"].Hyperlinks = &xlsxHyperlinks{Hyperlink: make([]xlsxHyperlink, 65530)}
  302. assert.EqualError(t, f.SetCellHyperLink("Sheet1", "A65531", "https://github.com/360EntSecGroup-Skylar/excelize", "External"), "over maximum limit hyperlinks in a worksheet")
  303. f = NewFile()
  304. _, err = f.workSheetReader("Sheet1")
  305. assert.NoError(t, err)
  306. f.Sheet["xl/worksheets/sheet1.xml"].MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}
  307. err = f.SetCellHyperLink("Sheet1", "A1", "https://github.com/360EntSecGroup-Skylar/excelize", "External")
  308. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  309. }
  310. func TestGetCellHyperLink(t *testing.T) {
  311. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  312. if !assert.NoError(t, err) {
  313. t.FailNow()
  314. }
  315. _, _, err = f.GetCellHyperLink("Sheet1", "")
  316. assert.EqualError(t, err, `invalid cell name ""`)
  317. link, target, err := f.GetCellHyperLink("Sheet1", "A22")
  318. assert.NoError(t, err)
  319. t.Log(link, target)
  320. link, target, err = f.GetCellHyperLink("Sheet2", "D6")
  321. assert.NoError(t, err)
  322. t.Log(link, target)
  323. link, target, err = f.GetCellHyperLink("Sheet3", "H3")
  324. assert.EqualError(t, err, "sheet Sheet3 is not exist")
  325. t.Log(link, target)
  326. f = NewFile()
  327. _, err = f.workSheetReader("Sheet1")
  328. assert.NoError(t, err)
  329. f.Sheet["xl/worksheets/sheet1.xml"].Hyperlinks = &xlsxHyperlinks{
  330. Hyperlink: []xlsxHyperlink{{Ref: "A1"}},
  331. }
  332. link, target, err = f.GetCellHyperLink("Sheet1", "A1")
  333. assert.NoError(t, err)
  334. assert.Equal(t, link, true)
  335. assert.Equal(t, target, "")
  336. f.Sheet["xl/worksheets/sheet1.xml"].MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}
  337. link, target, err = f.GetCellHyperLink("Sheet1", "A1")
  338. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  339. assert.Equal(t, link, false)
  340. assert.Equal(t, target, "")
  341. }
  342. func TestSetCellFormula(t *testing.T) {
  343. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  344. if !assert.NoError(t, err) {
  345. t.FailNow()
  346. }
  347. assert.NoError(t, f.SetCellFormula("Sheet1", "B19", "SUM(Sheet2!D2,Sheet2!D11)"))
  348. assert.NoError(t, f.SetCellFormula("Sheet1", "C19", "SUM(Sheet2!D2,Sheet2!D9)"))
  349. // Test set cell formula with illegal rows number.
  350. assert.EqualError(t, f.SetCellFormula("Sheet1", "C", "SUM(Sheet2!D2,Sheet2!D9)"), `cannot convert cell "C" to coordinates: invalid cell name "C"`)
  351. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula1.xlsx")))
  352. f, err = OpenFile(filepath.Join("test", "CalcChain.xlsx"))
  353. if !assert.NoError(t, err) {
  354. t.FailNow()
  355. }
  356. // Test remove cell formula.
  357. assert.NoError(t, f.SetCellFormula("Sheet1", "A1", ""))
  358. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula2.xlsx")))
  359. // Test remove all cell formula.
  360. assert.NoError(t, f.SetCellFormula("Sheet1", "B1", ""))
  361. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula3.xlsx")))
  362. }
  363. func TestSetSheetBackground(t *testing.T) {
  364. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  365. if !assert.NoError(t, err) {
  366. t.FailNow()
  367. }
  368. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))
  369. if !assert.NoError(t, err) {
  370. t.FailNow()
  371. }
  372. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))
  373. if !assert.NoError(t, err) {
  374. t.FailNow()
  375. }
  376. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetBackground.xlsx")))
  377. }
  378. func TestSetSheetBackgroundErrors(t *testing.T) {
  379. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  380. if !assert.NoError(t, err) {
  381. t.FailNow()
  382. }
  383. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "not_exists", "not_exists.png"))
  384. if assert.Error(t, err) {
  385. assert.True(t, os.IsNotExist(err), "Expected os.IsNotExists(err) == true")
  386. }
  387. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "Book1.xlsx"))
  388. assert.EqualError(t, err, "unsupported image extension")
  389. }
  390. // TestWriteArrayFormula tests the extended options of SetCellFormula by writing an array function
  391. // to a workbook. In the resulting file, the lines 2 and 3 as well as 4 and 5 should have matching
  392. // contents.
  393. func TestWriteArrayFormula(t *testing.T) {
  394. cell := func(col, row int) string {
  395. c, err := CoordinatesToCellName(col, row)
  396. if err != nil {
  397. t.Fatal(err)
  398. }
  399. return c
  400. }
  401. f := NewFile()
  402. sample := []string{"Sample 1", "Sample 2", "Sample 3"}
  403. values := []int{1855, 1709, 1462, 1115, 1524, 625, 773, 126, 1027, 1696, 1078, 1917, 1109, 1753, 1884, 659, 994, 1911, 1925, 899, 196, 244, 1488, 1056, 1986, 66, 784, 725, 767, 1722, 1541, 1026, 1455, 264, 1538, 877, 1581, 1098, 383, 762, 237, 493, 29, 1923, 474, 430, 585, 688, 308, 200, 1259, 622, 798, 1048, 996, 601, 582, 332, 377, 805, 250, 1860, 1360, 840, 911, 1346, 1651, 1651, 665, 584, 1057, 1145, 925, 1752, 202, 149, 1917, 1398, 1894, 818, 714, 624, 1085, 1566, 635, 78, 313, 1686, 1820, 494, 614, 1913, 271, 1016, 338, 1301, 489, 1733, 1483, 1141}
  404. assoc := []int{2, 0, 0, 0, 0, 1, 1, 0, 0, 1, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 2, 0, 2, 1, 2, 2, 2, 1, 0, 1, 0, 1, 1, 2, 0, 2, 1, 0, 2, 1, 0, 1, 0, 0, 2, 0, 2, 2, 1, 2, 2, 1, 2, 2, 1, 2, 1, 2, 2, 1, 1, 1, 0, 1, 0, 2, 0, 0, 1, 2, 1, 0, 1, 0, 0, 2, 1, 1, 2, 0, 2, 1, 0, 2, 2, 2, 1, 0, 0, 1, 1, 1, 2, 0, 2, 0, 1, 1}
  405. if len(values) != len(assoc) {
  406. t.Fatal("values and assoc must be of same length")
  407. }
  408. // Average calculates the average of the n-th sample (0 <= n < len(sample)).
  409. average := func(n int) int {
  410. sum := 0
  411. count := 0
  412. for i := 0; i != len(values); i++ {
  413. if assoc[i] == n {
  414. sum += values[i]
  415. count++
  416. }
  417. }
  418. return int(math.Round(float64(sum) / float64(count)))
  419. }
  420. // Stdev calculates the standard deviation of the n-th sample (0 <= n < len(sample)).
  421. stdev := func(n int) int {
  422. avg := average(n)
  423. sum := 0
  424. count := 0
  425. for i := 0; i != len(values); i++ {
  426. if assoc[i] == n {
  427. sum += (values[i] - avg) * (values[i] - avg)
  428. count++
  429. }
  430. }
  431. return int(math.Round(math.Sqrt(float64(sum) / float64(count))))
  432. }
  433. // Line 2 contains the results of AVERAGEIF
  434. assert.NoError(t, f.SetCellStr("Sheet1", "A2", "Average"))
  435. // Line 3 contains the average that was calculated in Go
  436. assert.NoError(t, f.SetCellStr("Sheet1", "A3", "Average (calculated)"))
  437. // Line 4 contains the results of the array function that calculates the standard deviation
  438. assert.NoError(t, f.SetCellStr("Sheet1", "A4", "Std. deviation"))
  439. // Line 5 contains the standard deviations calculated in Go
  440. assert.NoError(t, f.SetCellStr("Sheet1", "A5", "Std. deviation (calculated)"))
  441. assert.NoError(t, f.SetCellStr("Sheet1", "B1", sample[0]))
  442. assert.NoError(t, f.SetCellStr("Sheet1", "C1", sample[1]))
  443. assert.NoError(t, f.SetCellStr("Sheet1", "D1", sample[2]))
  444. firstResLine := 8
  445. assert.NoError(t, f.SetCellStr("Sheet1", cell(1, firstResLine-1), "Result Values"))
  446. assert.NoError(t, f.SetCellStr("Sheet1", cell(2, firstResLine-1), "Sample"))
  447. for i := 0; i != len(values); i++ {
  448. valCell := cell(1, i+firstResLine)
  449. assocCell := cell(2, i+firstResLine)
  450. assert.NoError(t, f.SetCellInt("Sheet1", valCell, values[i]))
  451. assert.NoError(t, f.SetCellStr("Sheet1", assocCell, sample[assoc[i]]))
  452. }
  453. valRange := fmt.Sprintf("$A$%d:$A$%d", firstResLine, len(values)+firstResLine-1)
  454. assocRange := fmt.Sprintf("$B$%d:$B$%d", firstResLine, len(values)+firstResLine-1)
  455. for i := 0; i != len(sample); i++ {
  456. nameCell := cell(i+2, 1)
  457. avgCell := cell(i+2, 2)
  458. calcAvgCell := cell(i+2, 3)
  459. stdevCell := cell(i+2, 4)
  460. calcStdevCell := cell(i+2, 5)
  461. assert.NoError(t, f.SetCellInt("Sheet1", calcAvgCell, average(i)))
  462. assert.NoError(t, f.SetCellInt("Sheet1", calcStdevCell, stdev(i)))
  463. // Average can be done with AVERAGEIF
  464. assert.NoError(t, f.SetCellFormula("Sheet1", avgCell, fmt.Sprintf("ROUND(AVERAGEIF(%s,%s,%s),0)", assocRange, nameCell, valRange)))
  465. ref := stdevCell + ":" + stdevCell
  466. arr := STCellFormulaTypeArray
  467. // Use an array formula for standard deviation
  468. assert.NoError(t, f.SetCellFormula("Sheet1", stdevCell, fmt.Sprintf("ROUND(STDEVP(IF(%s=%s,%s)),0)", assocRange, nameCell, valRange),
  469. FormulaOpts{}, FormulaOpts{Type: &arr}, FormulaOpts{Ref: &ref}))
  470. }
  471. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestWriteArrayFormula.xlsx")))
  472. }
  473. func TestSetCellStyleAlignment(t *testing.T) {
  474. f, err := prepareTestBook1()
  475. if !assert.NoError(t, err) {
  476. t.FailNow()
  477. }
  478. var style int
  479. style, err = f.NewStyle(`{"alignment":{"horizontal":"center","ident":1,"justify_last_line":true,"reading_order":0,"relative_indent":1,"shrink_to_fit":true,"text_rotation":45,"vertical":"top","wrap_text":true}}`)
  480. if !assert.NoError(t, err) {
  481. t.FailNow()
  482. }
  483. assert.NoError(t, f.SetCellStyle("Sheet1", "A22", "A22", style))
  484. // Test set cell style with given illegal rows number.
  485. assert.EqualError(t, f.SetCellStyle("Sheet1", "A", "A22", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  486. assert.EqualError(t, f.SetCellStyle("Sheet1", "A22", "A", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  487. // Test get cell style with given illegal rows number.
  488. index, err := f.GetCellStyle("Sheet1", "A")
  489. assert.Equal(t, 0, index)
  490. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  491. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleAlignment.xlsx")))
  492. }
  493. func TestSetCellStyleBorder(t *testing.T) {
  494. f, err := prepareTestBook1()
  495. if !assert.NoError(t, err) {
  496. t.FailNow()
  497. }
  498. var style int
  499. // Test set border on overlapping area with vertical variants shading styles gradient fill.
  500. style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":12},{"type":"bottom","color":"FFFF00","style":5},{"type":"right","color":"FF0000","style":6},{"type":"diagonalDown","color":"A020F0","style":9},{"type":"diagonalUp","color":"A020F0","style":8}]}`)
  501. if !assert.NoError(t, err) {
  502. t.FailNow()
  503. }
  504. assert.NoError(t, f.SetCellStyle("Sheet1", "J21", "L25", style))
  505. style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":3},{"type":"bottom","color":"FFFF00","style":4},{"type":"right","color":"FF0000","style":5},{"type":"diagonalDown","color":"A020F0","style":6},{"type":"diagonalUp","color":"A020F0","style":7}],"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":1}}`)
  506. if !assert.NoError(t, err) {
  507. t.FailNow()
  508. }
  509. assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))
  510. style, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":2},{"type":"top","color":"00FF00","style":3},{"type":"bottom","color":"FFFF00","style":4},{"type":"right","color":"FF0000","style":5},{"type":"diagonalDown","color":"A020F0","style":6},{"type":"diagonalUp","color":"A020F0","style":7}],"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":4}}`)
  511. if !assert.NoError(t, err) {
  512. t.FailNow()
  513. }
  514. assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))
  515. // Test set border and solid style pattern fill for a single cell.
  516. style, err = f.NewStyle(&Style{
  517. Border: []Border{
  518. {
  519. Type: "left",
  520. Color: "0000FF",
  521. Style: 8,
  522. },
  523. {
  524. Type: "top",
  525. Color: "00FF00",
  526. Style: 9,
  527. },
  528. {
  529. Type: "bottom",
  530. Color: "FFFF00",
  531. Style: 10,
  532. },
  533. {
  534. Type: "right",
  535. Color: "FF0000",
  536. Style: 11,
  537. },
  538. {
  539. Type: "diagonalDown",
  540. Color: "A020F0",
  541. Style: 12,
  542. },
  543. {
  544. Type: "diagonalUp",
  545. Color: "A020F0",
  546. Style: 13,
  547. },
  548. },
  549. Fill: Fill{
  550. Type: "pattern",
  551. Color: []string{"#E0EBF5"},
  552. Pattern: 1,
  553. },
  554. })
  555. if !assert.NoError(t, err) {
  556. t.FailNow()
  557. }
  558. assert.NoError(t, f.SetCellStyle("Sheet1", "O22", "O22", style))
  559. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleBorder.xlsx")))
  560. }
  561. func TestSetCellStyleBorderErrors(t *testing.T) {
  562. f, err := prepareTestBook1()
  563. if !assert.NoError(t, err) {
  564. t.FailNow()
  565. }
  566. // Set border with invalid style parameter.
  567. _, err = f.NewStyle("")
  568. if !assert.EqualError(t, err, "unexpected end of JSON input") {
  569. t.FailNow()
  570. }
  571. // Set border with invalid style index number.
  572. _, err = f.NewStyle(`{"border":[{"type":"left","color":"0000FF","style":-1},{"type":"top","color":"00FF00","style":14},{"type":"bottom","color":"FFFF00","style":5},{"type":"right","color":"FF0000","style":6},{"type":"diagonalDown","color":"A020F0","style":9},{"type":"diagonalUp","color":"A020F0","style":8}]}`)
  573. if !assert.NoError(t, err) {
  574. t.FailNow()
  575. }
  576. }
  577. func TestSetCellStyleNumberFormat(t *testing.T) {
  578. f, err := prepareTestBook1()
  579. if !assert.NoError(t, err) {
  580. t.FailNow()
  581. }
  582. // Test only set fill and number format for a cell.
  583. col := []string{"L", "M", "N", "O", "P"}
  584. data := []int{0, 1, 2, 3, 4, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49}
  585. value := []string{"37947.7500001", "-37947.7500001", "0.007", "2.1", "String"}
  586. for i, v := range value {
  587. for k, d := range data {
  588. c := col[i] + strconv.Itoa(k+1)
  589. var val float64
  590. val, err = strconv.ParseFloat(v, 64)
  591. if err != nil {
  592. assert.NoError(t, f.SetCellValue("Sheet2", c, v))
  593. } else {
  594. assert.NoError(t, f.SetCellValue("Sheet2", c, val))
  595. }
  596. style, err := f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":5},"number_format": ` + strconv.Itoa(d) + `}`)
  597. if !assert.NoError(t, err) {
  598. t.FailNow()
  599. }
  600. assert.NoError(t, f.SetCellStyle("Sheet2", c, c, style))
  601. t.Log(f.GetCellValue("Sheet2", c))
  602. }
  603. }
  604. var style int
  605. style, err = f.NewStyle(`{"number_format":-1}`)
  606. if !assert.NoError(t, err) {
  607. t.FailNow()
  608. }
  609. assert.NoError(t, f.SetCellStyle("Sheet2", "L33", "L33", style))
  610. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleNumberFormat.xlsx")))
  611. }
  612. func TestSetCellStyleCurrencyNumberFormat(t *testing.T) {
  613. t.Run("TestBook3", func(t *testing.T) {
  614. f, err := prepareTestBook3()
  615. if !assert.NoError(t, err) {
  616. t.FailNow()
  617. }
  618. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 56))
  619. assert.NoError(t, f.SetCellValue("Sheet1", "A2", -32.3))
  620. var style int
  621. style, err = f.NewStyle(`{"number_format": 188, "decimal_places": -1}`)
  622. if !assert.NoError(t, err) {
  623. t.FailNow()
  624. }
  625. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  626. style, err = f.NewStyle(`{"number_format": 188, "decimal_places": 31, "negred": true}`)
  627. if !assert.NoError(t, err) {
  628. t.FailNow()
  629. }
  630. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  631. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook3.xlsx")))
  632. })
  633. t.Run("TestBook4", func(t *testing.T) {
  634. f, err := prepareTestBook4()
  635. if !assert.NoError(t, err) {
  636. t.FailNow()
  637. }
  638. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))
  639. assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))
  640. _, err = f.NewStyle(`{"number_format": 26, "lang": "zh-tw"}`)
  641. if !assert.NoError(t, err) {
  642. t.FailNow()
  643. }
  644. style, err := f.NewStyle(`{"number_format": 27}`)
  645. if !assert.NoError(t, err) {
  646. t.FailNow()
  647. }
  648. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  649. style, err = f.NewStyle(`{"number_format": 31, "lang": "ko-kr"}`)
  650. if !assert.NoError(t, err) {
  651. t.FailNow()
  652. }
  653. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  654. style, err = f.NewStyle(`{"number_format": 71, "lang": "th-th"}`)
  655. if !assert.NoError(t, err) {
  656. t.FailNow()
  657. }
  658. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  659. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook4.xlsx")))
  660. })
  661. }
  662. func TestSetCellStyleCustomNumberFormat(t *testing.T) {
  663. f := NewFile()
  664. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))
  665. assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))
  666. style, err := f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@"}`)
  667. assert.NoError(t, err)
  668. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  669. style, err = f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@","font":{"color":"#9A0511"}}`)
  670. assert.NoError(t, err)
  671. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  672. _, err = f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yy;@"}`)
  673. assert.NoError(t, err)
  674. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCustomNumberFormat.xlsx")))
  675. }
  676. func TestSetCellStyleFill(t *testing.T) {
  677. f, err := prepareTestBook1()
  678. if !assert.NoError(t, err) {
  679. t.FailNow()
  680. }
  681. var style int
  682. // Test set fill for cell with invalid parameter.
  683. style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":6}}`)
  684. assert.NoError(t, err)
  685. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  686. style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF"],"shading":1}}`)
  687. assert.NoError(t, err)
  688. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  689. style, err = f.NewStyle(`{"fill":{"type":"pattern","color":[],"pattern":1}}`)
  690. assert.NoError(t, err)
  691. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  692. style, err = f.NewStyle(`{"fill":{"type":"pattern","color":["#E0EBF5"],"pattern":19}}`)
  693. if !assert.NoError(t, err) {
  694. t.FailNow()
  695. }
  696. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  697. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFill.xlsx")))
  698. }
  699. func TestSetCellStyleFont(t *testing.T) {
  700. f, err := prepareTestBook1()
  701. if !assert.NoError(t, err) {
  702. t.FailNow()
  703. }
  704. var style int
  705. style, err = f.NewStyle(`{"font":{"bold":true,"italic":true,"family":"Times New Roman","size":36,"color":"#777777","underline":"single"}}`)
  706. if !assert.NoError(t, err) {
  707. t.FailNow()
  708. }
  709. assert.NoError(t, f.SetCellStyle("Sheet2", "A1", "A1", style))
  710. style, err = f.NewStyle(`{"font":{"italic":true,"underline":"double"}}`)
  711. if !assert.NoError(t, err) {
  712. t.FailNow()
  713. }
  714. assert.NoError(t, f.SetCellStyle("Sheet2", "A2", "A2", style))
  715. style, err = f.NewStyle(`{"font":{"bold":true}}`)
  716. if !assert.NoError(t, err) {
  717. t.FailNow()
  718. }
  719. assert.NoError(t, f.SetCellStyle("Sheet2", "A3", "A3", style))
  720. style, err = f.NewStyle(`{"font":{"bold":true,"family":"","size":0,"color":"","underline":""}}`)
  721. if !assert.NoError(t, err) {
  722. t.FailNow()
  723. }
  724. assert.NoError(t, f.SetCellStyle("Sheet2", "A4", "A4", style))
  725. style, err = f.NewStyle(`{"font":{"color":"#777777","strike":true}}`)
  726. if !assert.NoError(t, err) {
  727. t.FailNow()
  728. }
  729. assert.NoError(t, f.SetCellStyle("Sheet2", "A5", "A5", style))
  730. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFont.xlsx")))
  731. }
  732. func TestSetCellStyleProtection(t *testing.T) {
  733. f, err := prepareTestBook1()
  734. if !assert.NoError(t, err) {
  735. t.FailNow()
  736. }
  737. var style int
  738. style, err = f.NewStyle(`{"protection":{"hidden":true, "locked":true}}`)
  739. if !assert.NoError(t, err) {
  740. t.FailNow()
  741. }
  742. assert.NoError(t, f.SetCellStyle("Sheet2", "A6", "A6", style))
  743. err = f.SaveAs(filepath.Join("test", "TestSetCellStyleProtection.xlsx"))
  744. if !assert.NoError(t, err) {
  745. t.FailNow()
  746. }
  747. }
  748. func TestSetDeleteSheet(t *testing.T) {
  749. t.Run("TestBook3", func(t *testing.T) {
  750. f, err := prepareTestBook3()
  751. if !assert.NoError(t, err) {
  752. t.FailNow()
  753. }
  754. f.DeleteSheet("XLSXSheet3")
  755. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook3.xlsx")))
  756. })
  757. t.Run("TestBook4", func(t *testing.T) {
  758. f, err := prepareTestBook4()
  759. if !assert.NoError(t, err) {
  760. t.FailNow()
  761. }
  762. f.DeleteSheet("Sheet1")
  763. assert.EqualError(t, f.AddComment("Sheet1", "A1", ""), "unexpected end of JSON input")
  764. assert.NoError(t, f.AddComment("Sheet1", "A1", `{"author":"Excelize: ","text":"This is a comment."}`))
  765. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook4.xlsx")))
  766. })
  767. }
  768. func TestSheetVisibility(t *testing.T) {
  769. f, err := prepareTestBook1()
  770. if !assert.NoError(t, err) {
  771. t.FailNow()
  772. }
  773. assert.NoError(t, f.SetSheetVisible("Sheet2", false))
  774. assert.NoError(t, f.SetSheetVisible("Sheet1", false))
  775. assert.NoError(t, f.SetSheetVisible("Sheet1", true))
  776. assert.Equal(t, true, f.GetSheetVisible("Sheet1"))
  777. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSheetVisibility.xlsx")))
  778. }
  779. func TestCopySheet(t *testing.T) {
  780. f, err := prepareTestBook1()
  781. if !assert.NoError(t, err) {
  782. t.FailNow()
  783. }
  784. idx := f.NewSheet("CopySheet")
  785. assert.NoError(t, f.CopySheet(0, idx))
  786. assert.NoError(t, f.SetCellValue("CopySheet", "F1", "Hello"))
  787. val, err := f.GetCellValue("Sheet1", "F1")
  788. assert.NoError(t, err)
  789. assert.NotEqual(t, "Hello", val)
  790. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheet.xlsx")))
  791. }
  792. func TestCopySheetError(t *testing.T) {
  793. f, err := prepareTestBook1()
  794. if !assert.NoError(t, err) {
  795. t.FailNow()
  796. }
  797. assert.EqualError(t, f.copySheet(-1, -2), "sheet is not exist")
  798. if !assert.EqualError(t, f.CopySheet(-1, -2), "invalid worksheet index") {
  799. t.FailNow()
  800. }
  801. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheetError.xlsx")))
  802. }
  803. func TestGetSheetComments(t *testing.T) {
  804. f := NewFile()
  805. assert.Equal(t, "", f.getSheetComments("sheet0"))
  806. }
  807. func TestSetSheetVisible(t *testing.T) {
  808. f := NewFile()
  809. f.WorkBook.Sheets.Sheet[0].Name = "SheetN"
  810. assert.EqualError(t, f.SetSheetVisible("Sheet1", false), "sheet SheetN is not exist")
  811. }
  812. func TestGetActiveSheetIndex(t *testing.T) {
  813. f := NewFile()
  814. f.WorkBook.BookViews = nil
  815. assert.Equal(t, 0, f.GetActiveSheetIndex())
  816. }
  817. func TestRelsWriter(t *testing.T) {
  818. f := NewFile()
  819. f.Relationships["xl/worksheets/sheet/rels/sheet1.xml.rel"] = &xlsxRelationships{}
  820. f.relsWriter()
  821. }
  822. func TestGetSheetView(t *testing.T) {
  823. f := NewFile()
  824. _, err := f.getSheetView("SheetN", 0)
  825. assert.EqualError(t, err, "sheet SheetN is not exist")
  826. }
  827. func TestConditionalFormat(t *testing.T) {
  828. f := NewFile()
  829. sheet1 := f.GetSheetName(0)
  830. fillCells(f, sheet1, 10, 15)
  831. var format1, format2, format3, format4 int
  832. var err error
  833. // Rose format for bad conditional.
  834. format1, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)
  835. if !assert.NoError(t, err) {
  836. t.FailNow()
  837. }
  838. // Light yellow format for neutral conditional.
  839. format2, err = f.NewConditionalStyle(`{"fill":{"type":"pattern","color":["#FEEAA0"],"pattern":1}}`)
  840. if !assert.NoError(t, err) {
  841. t.FailNow()
  842. }
  843. // Light green format for good conditional.
  844. format3, err = f.NewConditionalStyle(`{"font":{"color":"#09600B"},"fill":{"type":"pattern","color":["#C7EECF"],"pattern":1}}`)
  845. if !assert.NoError(t, err) {
  846. t.FailNow()
  847. }
  848. // conditional style with align and left border.
  849. format4, err = f.NewConditionalStyle(`{"alignment":{"wrap_text":true},"border":[{"type":"left","color":"#000000","style":1}]}`)
  850. if !assert.NoError(t, err) {
  851. t.FailNow()
  852. }
  853. // Color scales: 2 color.
  854. assert.NoError(t, f.SetConditionalFormat(sheet1, "A1:A10", `[{"type":"2_color_scale","criteria":"=","min_type":"min","max_type":"max","min_color":"#F8696B","max_color":"#63BE7B"}]`))
  855. // Color scales: 3 color.
  856. assert.NoError(t, f.SetConditionalFormat(sheet1, "B1:B10", `[{"type":"3_color_scale","criteria":"=","min_type":"min","mid_type":"percentile","max_type":"max","min_color":"#F8696B","mid_color":"#FFEB84","max_color":"#63BE7B"}]`))
  857. // Hightlight cells rules: between...
  858. assert.NoError(t, f.SetConditionalFormat(sheet1, "C1:C10", fmt.Sprintf(`[{"type":"cell","criteria":"between","format":%d,"minimum":"6","maximum":"8"}]`, format1)))
  859. // Hightlight cells rules: Greater Than...
  860. assert.NoError(t, f.SetConditionalFormat(sheet1, "D1:D10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"6"}]`, format3)))
  861. // Hightlight cells rules: Equal To...
  862. assert.NoError(t, f.SetConditionalFormat(sheet1, "E1:E10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d}]`, format3)))
  863. // Hightlight cells rules: Not Equal To...
  864. assert.NoError(t, f.SetConditionalFormat(sheet1, "F1:F10", fmt.Sprintf(`[{"type":"unique","criteria":"=","format":%d}]`, format2)))
  865. // Hightlight cells rules: Duplicate Values...
  866. assert.NoError(t, f.SetConditionalFormat(sheet1, "G1:G10", fmt.Sprintf(`[{"type":"duplicate","criteria":"=","format":%d}]`, format2)))
  867. // Top/Bottom rules: Top 10%.
  868. assert.NoError(t, f.SetConditionalFormat(sheet1, "H1:H10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d,"value":"6","percent":true}]`, format1)))
  869. // Top/Bottom rules: Above Average...
  870. assert.NoError(t, f.SetConditionalFormat(sheet1, "I1:I10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": true}]`, format3)))
  871. // Top/Bottom rules: Below Average...
  872. assert.NoError(t, f.SetConditionalFormat(sheet1, "J1:J10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": false}]`, format1)))
  873. // Data Bars: Gradient Fill.
  874. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  875. // Use a formula to determine which cells to format.
  876. assert.NoError(t, f.SetConditionalFormat(sheet1, "L1:L10", fmt.Sprintf(`[{"type":"formula", "criteria":"L2<3", "format":%d}]`, format1)))
  877. // Alignment/Border cells rules.
  878. assert.NoError(t, f.SetConditionalFormat(sheet1, "M1:M10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"0"}]`, format4)))
  879. // Test set invalid format set in conditional format.
  880. assert.EqualError(t, f.SetConditionalFormat(sheet1, "L1:L10", ""), "unexpected end of JSON input")
  881. // Set conditional format on not exists worksheet.
  882. assert.EqualError(t, f.SetConditionalFormat("SheetN", "L1:L10", "[]"), "sheet SheetN is not exist")
  883. err = f.SaveAs(filepath.Join("test", "TestConditionalFormat.xlsx"))
  884. if !assert.NoError(t, err) {
  885. t.FailNow()
  886. }
  887. // Set conditional format with illegal valid type.
  888. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  889. // Set conditional format with illegal criteria type.
  890. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  891. // Set conditional format with file without dxfs element shold not return error.
  892. f, err = OpenFile(filepath.Join("test", "Book1.xlsx"))
  893. if !assert.NoError(t, err) {
  894. t.FailNow()
  895. }
  896. _, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)
  897. if !assert.NoError(t, err) {
  898. t.FailNow()
  899. }
  900. }
  901. func TestConditionalFormatError(t *testing.T) {
  902. f := NewFile()
  903. sheet1 := f.GetSheetName(0)
  904. fillCells(f, sheet1, 10, 15)
  905. // Set conditional format with illegal JSON string should return error.
  906. _, err := f.NewConditionalStyle("")
  907. if !assert.EqualError(t, err, "unexpected end of JSON input") {
  908. t.FailNow()
  909. }
  910. }
  911. func TestSharedStrings(t *testing.T) {
  912. f, err := OpenFile(filepath.Join("test", "SharedStrings.xlsx"))
  913. if !assert.NoError(t, err) {
  914. t.FailNow()
  915. }
  916. rows, err := f.GetRows("Sheet1")
  917. if !assert.NoError(t, err) {
  918. t.FailNow()
  919. }
  920. assert.Equal(t, "A", rows[0][0])
  921. rows, err = f.GetRows("Sheet2")
  922. if !assert.NoError(t, err) {
  923. t.FailNow()
  924. }
  925. assert.Equal(t, "Test Weight (Kgs)", rows[0][0])
  926. }
  927. func TestSetSheetRow(t *testing.T) {
  928. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  929. if !assert.NoError(t, err) {
  930. t.FailNow()
  931. }
  932. assert.NoError(t, f.SetSheetRow("Sheet1", "B27", &[]interface{}{"cell", nil, int32(42), float64(42), time.Now().UTC()}))
  933. assert.EqualError(t, f.SetSheetRow("Sheet1", "", &[]interface{}{"cell", nil, 2}),
  934. `cannot convert cell "" to coordinates: invalid cell name ""`)
  935. assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", []interface{}{}), `pointer to slice expected`)
  936. assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", &f), `pointer to slice expected`)
  937. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetRow.xlsx")))
  938. }
  939. func TestHSL(t *testing.T) {
  940. var hsl HSL
  941. r, g, b, a := hsl.RGBA()
  942. assert.Equal(t, uint32(0), r)
  943. assert.Equal(t, uint32(0), g)
  944. assert.Equal(t, uint32(0), b)
  945. assert.Equal(t, uint32(0xffff), a)
  946. assert.Equal(t, HSL{0, 0, 0}, hslModel(hsl))
  947. assert.Equal(t, HSL{0, 0, 0}, hslModel(color.Gray16{Y: uint16(1)}))
  948. R, G, B := HSLToRGB(0, 1, 0.4)
  949. assert.Equal(t, uint8(204), R)
  950. assert.Equal(t, uint8(0), G)
  951. assert.Equal(t, uint8(0), B)
  952. R, G, B = HSLToRGB(0, 1, 0.6)
  953. assert.Equal(t, uint8(255), R)
  954. assert.Equal(t, uint8(51), G)
  955. assert.Equal(t, uint8(51), B)
  956. assert.Equal(t, 0.0, hueToRGB(0, 0, -1))
  957. assert.Equal(t, 0.0, hueToRGB(0, 0, 2))
  958. assert.Equal(t, 0.0, hueToRGB(0, 0, 1.0/7))
  959. assert.Equal(t, 0.0, hueToRGB(0, 0, 0.4))
  960. assert.Equal(t, 0.0, hueToRGB(0, 0, 2.0/4))
  961. t.Log(RGBToHSL(255, 255, 0))
  962. h, s, l := RGBToHSL(0, 255, 255)
  963. assert.Equal(t, float64(0.5), h)
  964. assert.Equal(t, float64(1), s)
  965. assert.Equal(t, float64(0.5), l)
  966. t.Log(RGBToHSL(250, 100, 50))
  967. t.Log(RGBToHSL(50, 100, 250))
  968. t.Log(RGBToHSL(250, 50, 100))
  969. }
  970. func TestProtectSheet(t *testing.T) {
  971. f := NewFile()
  972. assert.NoError(t, f.ProtectSheet("Sheet1", nil))
  973. assert.NoError(t, f.ProtectSheet("Sheet1", &FormatSheetProtection{
  974. Password: "password",
  975. EditScenarios: false,
  976. }))
  977. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestProtectSheet.xlsx")))
  978. // Test protect not exists worksheet.
  979. assert.EqualError(t, f.ProtectSheet("SheetN", nil), "sheet SheetN is not exist")
  980. }
  981. func TestUnprotectSheet(t *testing.T) {
  982. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  983. if !assert.NoError(t, err) {
  984. t.FailNow()
  985. }
  986. // Test unprotect not exists worksheet.
  987. assert.EqualError(t, f.UnprotectSheet("SheetN"), "sheet SheetN is not exist")
  988. assert.NoError(t, f.UnprotectSheet("Sheet1"))
  989. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestUnprotectSheet.xlsx")))
  990. }
  991. func TestSetDefaultTimeStyle(t *testing.T) {
  992. f := NewFile()
  993. // Test set default time style on not exists worksheet.
  994. assert.EqualError(t, f.setDefaultTimeStyle("SheetN", "", 0), "sheet SheetN is not exist")
  995. // Test set default time style on invalid cell
  996. assert.EqualError(t, f.setDefaultTimeStyle("Sheet1", "", 42), "cannot convert cell \"\" to coordinates: invalid cell name \"\"")
  997. }
  998. func TestAddVBAProject(t *testing.T) {
  999. f := NewFile()
  1000. assert.NoError(t, f.SetSheetPrOptions("Sheet1", CodeName("Sheet1")))
  1001. assert.EqualError(t, f.AddVBAProject("macros.bin"), "stat macros.bin: no such file or directory")
  1002. assert.EqualError(t, f.AddVBAProject(filepath.Join("test", "Book1.xlsx")), "unsupported VBA project extension")
  1003. assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))
  1004. // Test add VBA project twice.
  1005. assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))
  1006. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddVBAProject.xlsm")))
  1007. }
  1008. func TestContentTypesReader(t *testing.T) {
  1009. // Test unsupported charset.
  1010. f := NewFile()
  1011. f.ContentTypes = nil
  1012. f.XLSX["[Content_Types].xml"] = MacintoshCyrillicCharset
  1013. f.contentTypesReader()
  1014. }
  1015. func TestWorkbookReader(t *testing.T) {
  1016. // Test unsupported charset.
  1017. f := NewFile()
  1018. f.WorkBook = nil
  1019. f.XLSX["xl/workbook.xml"] = MacintoshCyrillicCharset
  1020. f.workbookReader()
  1021. }
  1022. func TestWorkSheetReader(t *testing.T) {
  1023. // Test unsupported charset.
  1024. f := NewFile()
  1025. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  1026. f.XLSX["xl/worksheets/sheet1.xml"] = MacintoshCyrillicCharset
  1027. _, err := f.workSheetReader("Sheet1")
  1028. assert.EqualError(t, err, "xml decode error: XML syntax error on line 1: invalid UTF-8")
  1029. // Test on no checked worksheet.
  1030. f = NewFile()
  1031. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  1032. f.XLSX["xl/worksheets/sheet1.xml"] = []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`)
  1033. f.checked = nil
  1034. _, err = f.workSheetReader("Sheet1")
  1035. assert.NoError(t, err)
  1036. }
  1037. func TestRelsReader(t *testing.T) {
  1038. // Test unsupported charset.
  1039. f := NewFile()
  1040. rels := "xl/_rels/workbook.xml.rels"
  1041. f.Relationships[rels] = nil
  1042. f.XLSX[rels] = MacintoshCyrillicCharset
  1043. f.relsReader(rels)
  1044. }
  1045. func TestDeleteSheetFromWorkbookRels(t *testing.T) {
  1046. f := NewFile()
  1047. rels := "xl/_rels/workbook.xml.rels"
  1048. f.Relationships[rels] = nil
  1049. assert.Equal(t, f.deleteSheetFromWorkbookRels("rID"), "")
  1050. }
  1051. func TestAttrValToInt(t *testing.T) {
  1052. _, err := attrValToInt("r", []xml.Attr{
  1053. {Name: xml.Name{Local: "r"}, Value: "s"}})
  1054. assert.EqualError(t, err, `strconv.Atoi: parsing "s": invalid syntax`)
  1055. }
  1056. func prepareTestBook1() (*File, error) {
  1057. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  1058. if err != nil {
  1059. return nil, err
  1060. }
  1061. err = f.AddPicture("Sheet2", "I9", filepath.Join("test", "images", "excel.jpg"),
  1062. `{"x_offset": 140, "y_offset": 120, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`)
  1063. if err != nil {
  1064. return nil, err
  1065. }
  1066. // Test add picture to worksheet with offset, external hyperlink and positioning.
  1067. err = f.AddPicture("Sheet1", "F21", filepath.Join("test", "images", "excel.png"),
  1068. `{"x_offset": 10, "y_offset": 10, "hyperlink": "https://github.com/360EntSecGroup-Skylar/excelize", "hyperlink_type": "External", "positioning": "oneCell"}`)
  1069. if err != nil {
  1070. return nil, err
  1071. }
  1072. file, err := ioutil.ReadFile(filepath.Join("test", "images", "excel.jpg"))
  1073. if err != nil {
  1074. return nil, err
  1075. }
  1076. err = f.AddPictureFromBytes("Sheet1", "Q1", "", "Excel Logo", ".jpg", file)
  1077. if err != nil {
  1078. return nil, err
  1079. }
  1080. return f, nil
  1081. }
  1082. func prepareTestBook3() (*File, error) {
  1083. f := NewFile()
  1084. f.NewSheet("Sheet1")
  1085. f.NewSheet("XLSXSheet2")
  1086. f.NewSheet("XLSXSheet3")
  1087. if err := f.SetCellInt("XLSXSheet2", "A23", 56); err != nil {
  1088. return nil, err
  1089. }
  1090. if err := f.SetCellStr("Sheet1", "B20", "42"); err != nil {
  1091. return nil, err
  1092. }
  1093. f.SetActiveSheet(0)
  1094. err := f.AddPicture("Sheet1", "H2", filepath.Join("test", "images", "excel.gif"),
  1095. `{"x_scale": 0.5, "y_scale": 0.5, "positioning": "absolute"}`)
  1096. if err != nil {
  1097. return nil, err
  1098. }
  1099. err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), "")
  1100. if err != nil {
  1101. return nil, err
  1102. }
  1103. return f, nil
  1104. }
  1105. func prepareTestBook4() (*File, error) {
  1106. f := NewFile()
  1107. if err := f.SetColWidth("Sheet1", "B", "A", 12); err != nil {
  1108. return f, err
  1109. }
  1110. if err := f.SetColWidth("Sheet1", "A", "B", 12); err != nil {
  1111. return f, err
  1112. }
  1113. if _, err := f.GetColWidth("Sheet1", "A"); err != nil {
  1114. return f, err
  1115. }
  1116. if _, err := f.GetColWidth("Sheet1", "C"); err != nil {
  1117. return f, err
  1118. }
  1119. return f, nil
  1120. }
  1121. func fillCells(f *File, sheet string, colCount, rowCount int) {
  1122. for col := 1; col <= colCount; col++ {
  1123. for row := 1; row <= rowCount; row++ {
  1124. cell, _ := CoordinatesToCellName(col, row)
  1125. if err := f.SetCellStr(sheet, cell, cell); err != nil {
  1126. fmt.Println(err)
  1127. }
  1128. }
  1129. }
  1130. }
  1131. func BenchmarkOpenFile(b *testing.B) {
  1132. for i := 0; i < b.N; i++ {
  1133. if _, err := OpenFile(filepath.Join("test", "Book1.xlsx")); err != nil {
  1134. b.Error(err)
  1135. }
  1136. }
  1137. }