excelize_test.go 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355
  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", TotalCellChars+2)))
  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.NoError(t, f.SetCellValue("Sheet2", "G4", time.Now()))
  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")), ErrMaxFileNameLength.Error())
  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. assert.NoError(t, f.Save())
  272. }
  273. func TestAddDrawingVML(t *testing.T) {
  274. // Test addDrawingVML with illegal cell coordinates.
  275. f := NewFile()
  276. assert.EqualError(t, f.addDrawingVML(0, "", "*", 0, 0), `cannot convert cell "*" to coordinates: invalid cell name "*"`)
  277. }
  278. func TestSetCellHyperLink(t *testing.T) {
  279. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  280. if err != nil {
  281. t.Log(err)
  282. }
  283. // Test set cell hyperlink in a work sheet already have hyperlinks.
  284. assert.NoError(t, f.SetCellHyperLink("Sheet1", "B19", "https://github.com/xuri/excelize", "External"))
  285. // Test add first hyperlink in a work sheet.
  286. assert.NoError(t, f.SetCellHyperLink("Sheet2", "C1", "https://github.com/xuri/excelize", "External"))
  287. // Test add Location hyperlink in a work sheet.
  288. assert.NoError(t, f.SetCellHyperLink("Sheet2", "D6", "Sheet1!D8", "Location"))
  289. // Test add Location hyperlink with display & tooltip in a work sheet.
  290. display := "Display value"
  291. tooltip := "Hover text"
  292. assert.NoError(t, f.SetCellHyperLink("Sheet2", "D7", "Sheet1!D9", "Location", HyperlinkOpts{
  293. Display: &display,
  294. Tooltip: &tooltip,
  295. }))
  296. assert.EqualError(t, f.SetCellHyperLink("Sheet2", "C3", "Sheet1!D8", ""), `invalid link type ""`)
  297. assert.EqualError(t, f.SetCellHyperLink("Sheet2", "", "Sheet1!D60", "Location"), `invalid cell name ""`)
  298. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellHyperLink.xlsx")))
  299. f = NewFile()
  300. _, err = f.workSheetReader("Sheet1")
  301. assert.NoError(t, err)
  302. ws, ok := f.Sheet.Load("xl/worksheets/sheet1.xml")
  303. assert.True(t, ok)
  304. ws.(*xlsxWorksheet).Hyperlinks = &xlsxHyperlinks{Hyperlink: make([]xlsxHyperlink, 65530)}
  305. assert.EqualError(t, f.SetCellHyperLink("Sheet1", "A65531", "https://github.com/xuri/excelize", "External"), ErrTotalSheetHyperlinks.Error())
  306. f = NewFile()
  307. _, err = f.workSheetReader("Sheet1")
  308. assert.NoError(t, err)
  309. ws, ok = f.Sheet.Load("xl/worksheets/sheet1.xml")
  310. assert.True(t, ok)
  311. ws.(*xlsxWorksheet).MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}
  312. err = f.SetCellHyperLink("Sheet1", "A1", "https://github.com/xuri/excelize", "External")
  313. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  314. }
  315. func TestGetCellHyperLink(t *testing.T) {
  316. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  317. if !assert.NoError(t, err) {
  318. t.FailNow()
  319. }
  320. _, _, err = f.GetCellHyperLink("Sheet1", "")
  321. assert.EqualError(t, err, `invalid cell name ""`)
  322. link, target, err := f.GetCellHyperLink("Sheet1", "A22")
  323. assert.NoError(t, err)
  324. t.Log(link, target)
  325. link, target, err = f.GetCellHyperLink("Sheet2", "D6")
  326. assert.NoError(t, err)
  327. t.Log(link, target)
  328. link, target, err = f.GetCellHyperLink("Sheet3", "H3")
  329. assert.EqualError(t, err, "sheet Sheet3 is not exist")
  330. t.Log(link, target)
  331. f = NewFile()
  332. _, err = f.workSheetReader("Sheet1")
  333. assert.NoError(t, err)
  334. ws, ok := f.Sheet.Load("xl/worksheets/sheet1.xml")
  335. assert.True(t, ok)
  336. ws.(*xlsxWorksheet).Hyperlinks = &xlsxHyperlinks{
  337. Hyperlink: []xlsxHyperlink{{Ref: "A1"}},
  338. }
  339. link, target, err = f.GetCellHyperLink("Sheet1", "A1")
  340. assert.NoError(t, err)
  341. assert.Equal(t, link, true)
  342. assert.Equal(t, target, "")
  343. ws, ok = f.Sheet.Load("xl/worksheets/sheet1.xml")
  344. assert.True(t, ok)
  345. ws.(*xlsxWorksheet).MergeCells = &xlsxMergeCells{Cells: []*xlsxMergeCell{{Ref: "A:A"}}}
  346. link, target, err = f.GetCellHyperLink("Sheet1", "A1")
  347. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  348. assert.Equal(t, link, false)
  349. assert.Equal(t, target, "")
  350. }
  351. func TestSetCellFormula(t *testing.T) {
  352. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  353. if !assert.NoError(t, err) {
  354. t.FailNow()
  355. }
  356. assert.NoError(t, f.SetCellFormula("Sheet1", "B19", "SUM(Sheet2!D2,Sheet2!D11)"))
  357. assert.NoError(t, f.SetCellFormula("Sheet1", "C19", "SUM(Sheet2!D2,Sheet2!D9)"))
  358. // Test set cell formula with illegal rows number.
  359. assert.EqualError(t, f.SetCellFormula("Sheet1", "C", "SUM(Sheet2!D2,Sheet2!D9)"), `cannot convert cell "C" to coordinates: invalid cell name "C"`)
  360. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula1.xlsx")))
  361. f, err = OpenFile(filepath.Join("test", "CalcChain.xlsx"))
  362. if !assert.NoError(t, err) {
  363. t.FailNow()
  364. }
  365. // Test remove cell formula.
  366. assert.NoError(t, f.SetCellFormula("Sheet1", "A1", ""))
  367. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula2.xlsx")))
  368. // Test remove all cell formula.
  369. assert.NoError(t, f.SetCellFormula("Sheet1", "B1", ""))
  370. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellFormula3.xlsx")))
  371. }
  372. func TestSetSheetBackground(t *testing.T) {
  373. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  374. if !assert.NoError(t, err) {
  375. t.FailNow()
  376. }
  377. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))
  378. if !assert.NoError(t, err) {
  379. t.FailNow()
  380. }
  381. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "images", "background.jpg"))
  382. if !assert.NoError(t, err) {
  383. t.FailNow()
  384. }
  385. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetBackground.xlsx")))
  386. }
  387. func TestSetSheetBackgroundErrors(t *testing.T) {
  388. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  389. if !assert.NoError(t, err) {
  390. t.FailNow()
  391. }
  392. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "not_exists", "not_exists.png"))
  393. if assert.Error(t, err) {
  394. assert.True(t, os.IsNotExist(err), "Expected os.IsNotExists(err) == true")
  395. }
  396. err = f.SetSheetBackground("Sheet2", filepath.Join("test", "Book1.xlsx"))
  397. assert.EqualError(t, err, ErrImgExt.Error())
  398. }
  399. // TestWriteArrayFormula tests the extended options of SetCellFormula by writing an array function
  400. // to a workbook. In the resulting file, the lines 2 and 3 as well as 4 and 5 should have matching
  401. // contents.
  402. func TestWriteArrayFormula(t *testing.T) {
  403. cell := func(col, row int) string {
  404. c, err := CoordinatesToCellName(col, row)
  405. if err != nil {
  406. t.Fatal(err)
  407. }
  408. return c
  409. }
  410. f := NewFile()
  411. sample := []string{"Sample 1", "Sample 2", "Sample 3"}
  412. 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}
  413. 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}
  414. if len(values) != len(assoc) {
  415. t.Fatal("values and assoc must be of same length")
  416. }
  417. // Average calculates the average of the n-th sample (0 <= n < len(sample)).
  418. average := func(n int) int {
  419. sum := 0
  420. count := 0
  421. for i := 0; i != len(values); i++ {
  422. if assoc[i] == n {
  423. sum += values[i]
  424. count++
  425. }
  426. }
  427. return int(math.Round(float64(sum) / float64(count)))
  428. }
  429. // Stdev calculates the standard deviation of the n-th sample (0 <= n < len(sample)).
  430. stdev := func(n int) int {
  431. avg := average(n)
  432. sum := 0
  433. count := 0
  434. for i := 0; i != len(values); i++ {
  435. if assoc[i] == n {
  436. sum += (values[i] - avg) * (values[i] - avg)
  437. count++
  438. }
  439. }
  440. return int(math.Round(math.Sqrt(float64(sum) / float64(count))))
  441. }
  442. // Line 2 contains the results of AVERAGEIF
  443. assert.NoError(t, f.SetCellStr("Sheet1", "A2", "Average"))
  444. // Line 3 contains the average that was calculated in Go
  445. assert.NoError(t, f.SetCellStr("Sheet1", "A3", "Average (calculated)"))
  446. // Line 4 contains the results of the array function that calculates the standard deviation
  447. assert.NoError(t, f.SetCellStr("Sheet1", "A4", "Std. deviation"))
  448. // Line 5 contains the standard deviations calculated in Go
  449. assert.NoError(t, f.SetCellStr("Sheet1", "A5", "Std. deviation (calculated)"))
  450. assert.NoError(t, f.SetCellStr("Sheet1", "B1", sample[0]))
  451. assert.NoError(t, f.SetCellStr("Sheet1", "C1", sample[1]))
  452. assert.NoError(t, f.SetCellStr("Sheet1", "D1", sample[2]))
  453. firstResLine := 8
  454. assert.NoError(t, f.SetCellStr("Sheet1", cell(1, firstResLine-1), "Result Values"))
  455. assert.NoError(t, f.SetCellStr("Sheet1", cell(2, firstResLine-1), "Sample"))
  456. for i := 0; i != len(values); i++ {
  457. valCell := cell(1, i+firstResLine)
  458. assocCell := cell(2, i+firstResLine)
  459. assert.NoError(t, f.SetCellInt("Sheet1", valCell, values[i]))
  460. assert.NoError(t, f.SetCellStr("Sheet1", assocCell, sample[assoc[i]]))
  461. }
  462. valRange := fmt.Sprintf("$A$%d:$A$%d", firstResLine, len(values)+firstResLine-1)
  463. assocRange := fmt.Sprintf("$B$%d:$B$%d", firstResLine, len(values)+firstResLine-1)
  464. for i := 0; i != len(sample); i++ {
  465. nameCell := cell(i+2, 1)
  466. avgCell := cell(i+2, 2)
  467. calcAvgCell := cell(i+2, 3)
  468. stdevCell := cell(i+2, 4)
  469. calcStdevCell := cell(i+2, 5)
  470. assert.NoError(t, f.SetCellInt("Sheet1", calcAvgCell, average(i)))
  471. assert.NoError(t, f.SetCellInt("Sheet1", calcStdevCell, stdev(i)))
  472. // Average can be done with AVERAGEIF
  473. assert.NoError(t, f.SetCellFormula("Sheet1", avgCell, fmt.Sprintf("ROUND(AVERAGEIF(%s,%s,%s),0)", assocRange, nameCell, valRange)))
  474. ref := stdevCell + ":" + stdevCell
  475. arr := STCellFormulaTypeArray
  476. // Use an array formula for standard deviation
  477. assert.NoError(t, f.SetCellFormula("Sheet1", stdevCell, fmt.Sprintf("ROUND(STDEVP(IF(%s=%s,%s)),0)", assocRange, nameCell, valRange),
  478. FormulaOpts{}, FormulaOpts{Type: &arr}, FormulaOpts{Ref: &ref}))
  479. }
  480. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestWriteArrayFormula.xlsx")))
  481. }
  482. func TestSetCellStyleAlignment(t *testing.T) {
  483. f, err := prepareTestBook1()
  484. if !assert.NoError(t, err) {
  485. t.FailNow()
  486. }
  487. var style int
  488. 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}}`)
  489. if !assert.NoError(t, err) {
  490. t.FailNow()
  491. }
  492. assert.NoError(t, f.SetCellStyle("Sheet1", "A22", "A22", style))
  493. // Test set cell style with given illegal rows number.
  494. assert.EqualError(t, f.SetCellStyle("Sheet1", "A", "A22", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  495. assert.EqualError(t, f.SetCellStyle("Sheet1", "A22", "A", style), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  496. // Test get cell style with given illegal rows number.
  497. index, err := f.GetCellStyle("Sheet1", "A")
  498. assert.Equal(t, 0, index)
  499. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  500. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleAlignment.xlsx")))
  501. }
  502. func TestSetCellStyleBorder(t *testing.T) {
  503. f, err := prepareTestBook1()
  504. if !assert.NoError(t, err) {
  505. t.FailNow()
  506. }
  507. var style int
  508. // Test set border on overlapping area with vertical variants shading styles gradient fill.
  509. 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}]}`)
  510. if !assert.NoError(t, err) {
  511. t.FailNow()
  512. }
  513. assert.NoError(t, f.SetCellStyle("Sheet1", "J21", "L25", style))
  514. 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}}`)
  515. if !assert.NoError(t, err) {
  516. t.FailNow()
  517. }
  518. assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))
  519. 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}}`)
  520. if !assert.NoError(t, err) {
  521. t.FailNow()
  522. }
  523. assert.NoError(t, f.SetCellStyle("Sheet1", "M28", "K24", style))
  524. // Test set border and solid style pattern fill for a single cell.
  525. style, err = f.NewStyle(&Style{
  526. Border: []Border{
  527. {
  528. Type: "left",
  529. Color: "0000FF",
  530. Style: 8,
  531. },
  532. {
  533. Type: "top",
  534. Color: "00FF00",
  535. Style: 9,
  536. },
  537. {
  538. Type: "bottom",
  539. Color: "FFFF00",
  540. Style: 10,
  541. },
  542. {
  543. Type: "right",
  544. Color: "FF0000",
  545. Style: 11,
  546. },
  547. {
  548. Type: "diagonalDown",
  549. Color: "A020F0",
  550. Style: 12,
  551. },
  552. {
  553. Type: "diagonalUp",
  554. Color: "A020F0",
  555. Style: 13,
  556. },
  557. },
  558. Fill: Fill{
  559. Type: "pattern",
  560. Color: []string{"#E0EBF5"},
  561. Pattern: 1,
  562. },
  563. })
  564. if !assert.NoError(t, err) {
  565. t.FailNow()
  566. }
  567. assert.NoError(t, f.SetCellStyle("Sheet1", "O22", "O22", style))
  568. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleBorder.xlsx")))
  569. }
  570. func TestSetCellStyleBorderErrors(t *testing.T) {
  571. f, err := prepareTestBook1()
  572. if !assert.NoError(t, err) {
  573. t.FailNow()
  574. }
  575. // Set border with invalid style parameter.
  576. _, err = f.NewStyle("")
  577. if !assert.EqualError(t, err, "unexpected end of JSON input") {
  578. t.FailNow()
  579. }
  580. // Set border with invalid style index number.
  581. _, 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}]}`)
  582. if !assert.NoError(t, err) {
  583. t.FailNow()
  584. }
  585. }
  586. func TestSetCellStyleNumberFormat(t *testing.T) {
  587. f, err := prepareTestBook1()
  588. if !assert.NoError(t, err) {
  589. t.FailNow()
  590. }
  591. // Test only set fill and number format for a cell.
  592. col := []string{"L", "M", "N", "O", "P"}
  593. 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}
  594. value := []string{"37947.7500001", "-37947.7500001", "0.007", "2.1", "String"}
  595. for i, v := range value {
  596. for k, d := range data {
  597. c := col[i] + strconv.Itoa(k+1)
  598. var val float64
  599. val, err = strconv.ParseFloat(v, 64)
  600. if err != nil {
  601. assert.NoError(t, f.SetCellValue("Sheet2", c, v))
  602. } else {
  603. assert.NoError(t, f.SetCellValue("Sheet2", c, val))
  604. }
  605. style, err := f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":5},"number_format": ` + strconv.Itoa(d) + `}`)
  606. if !assert.NoError(t, err) {
  607. t.FailNow()
  608. }
  609. assert.NoError(t, f.SetCellStyle("Sheet2", c, c, style))
  610. t.Log(f.GetCellValue("Sheet2", c))
  611. }
  612. }
  613. var style int
  614. style, err = f.NewStyle(`{"number_format":-1}`)
  615. if !assert.NoError(t, err) {
  616. t.FailNow()
  617. }
  618. assert.NoError(t, f.SetCellStyle("Sheet2", "L33", "L33", style))
  619. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleNumberFormat.xlsx")))
  620. }
  621. func TestSetCellStyleCurrencyNumberFormat(t *testing.T) {
  622. t.Run("TestBook3", func(t *testing.T) {
  623. f, err := prepareTestBook3()
  624. if !assert.NoError(t, err) {
  625. t.FailNow()
  626. }
  627. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 56))
  628. assert.NoError(t, f.SetCellValue("Sheet1", "A2", -32.3))
  629. var style int
  630. style, err = f.NewStyle(`{"number_format": 188, "decimal_places": -1}`)
  631. if !assert.NoError(t, err) {
  632. t.FailNow()
  633. }
  634. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  635. style, err = f.NewStyle(`{"number_format": 188, "decimal_places": 31, "negred": true}`)
  636. if !assert.NoError(t, err) {
  637. t.FailNow()
  638. }
  639. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  640. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook3.xlsx")))
  641. })
  642. t.Run("TestBook4", func(t *testing.T) {
  643. f, err := prepareTestBook4()
  644. if !assert.NoError(t, err) {
  645. t.FailNow()
  646. }
  647. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))
  648. assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))
  649. _, err = f.NewStyle(`{"number_format": 26, "lang": "zh-tw"}`)
  650. if !assert.NoError(t, err) {
  651. t.FailNow()
  652. }
  653. style, err := f.NewStyle(`{"number_format": 27}`)
  654. if !assert.NoError(t, err) {
  655. t.FailNow()
  656. }
  657. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  658. style, err = f.NewStyle(`{"number_format": 31, "lang": "ko-kr"}`)
  659. if !assert.NoError(t, err) {
  660. t.FailNow()
  661. }
  662. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  663. style, err = f.NewStyle(`{"number_format": 71, "lang": "th-th"}`)
  664. if !assert.NoError(t, err) {
  665. t.FailNow()
  666. }
  667. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  668. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCurrencyNumberFormat.TestBook4.xlsx")))
  669. })
  670. }
  671. func TestSetCellStyleCustomNumberFormat(t *testing.T) {
  672. f := NewFile()
  673. assert.NoError(t, f.SetCellValue("Sheet1", "A1", 42920.5))
  674. assert.NoError(t, f.SetCellValue("Sheet1", "A2", 42920.5))
  675. style, err := f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@"}`)
  676. assert.NoError(t, err)
  677. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  678. style, err = f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yyyy;@","font":{"color":"#9A0511"}}`)
  679. assert.NoError(t, err)
  680. assert.NoError(t, f.SetCellStyle("Sheet1", "A2", "A2", style))
  681. _, err = f.NewStyle(`{"custom_number_format": "[$-380A]dddd\\,\\ dd\" de \"mmmm\" de \"yy;@"}`)
  682. assert.NoError(t, err)
  683. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleCustomNumberFormat.xlsx")))
  684. }
  685. func TestSetCellStyleFill(t *testing.T) {
  686. f, err := prepareTestBook1()
  687. if !assert.NoError(t, err) {
  688. t.FailNow()
  689. }
  690. var style int
  691. // Test set fill for cell with invalid parameter.
  692. style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF","#E0EBF5"],"shading":6}}`)
  693. assert.NoError(t, err)
  694. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  695. style, err = f.NewStyle(`{"fill":{"type":"gradient","color":["#FFFFFF"],"shading":1}}`)
  696. assert.NoError(t, err)
  697. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  698. style, err = f.NewStyle(`{"fill":{"type":"pattern","color":[],"pattern":1}}`)
  699. assert.NoError(t, err)
  700. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  701. style, err = f.NewStyle(`{"fill":{"type":"pattern","color":["#E0EBF5"],"pattern":19}}`)
  702. if !assert.NoError(t, err) {
  703. t.FailNow()
  704. }
  705. assert.NoError(t, f.SetCellStyle("Sheet1", "O23", "O23", style))
  706. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFill.xlsx")))
  707. }
  708. func TestSetCellStyleFont(t *testing.T) {
  709. f, err := prepareTestBook1()
  710. if !assert.NoError(t, err) {
  711. t.FailNow()
  712. }
  713. var style int
  714. style, err = f.NewStyle(`{"font":{"bold":true,"italic":true,"family":"Times New Roman","size":36,"color":"#777777","underline":"single"}}`)
  715. if !assert.NoError(t, err) {
  716. t.FailNow()
  717. }
  718. assert.NoError(t, f.SetCellStyle("Sheet2", "A1", "A1", style))
  719. style, err = f.NewStyle(`{"font":{"italic":true,"underline":"double"}}`)
  720. if !assert.NoError(t, err) {
  721. t.FailNow()
  722. }
  723. assert.NoError(t, f.SetCellStyle("Sheet2", "A2", "A2", style))
  724. style, err = f.NewStyle(`{"font":{"bold":true}}`)
  725. if !assert.NoError(t, err) {
  726. t.FailNow()
  727. }
  728. assert.NoError(t, f.SetCellStyle("Sheet2", "A3", "A3", style))
  729. style, err = f.NewStyle(`{"font":{"bold":true,"family":"","size":0,"color":"","underline":""}}`)
  730. if !assert.NoError(t, err) {
  731. t.FailNow()
  732. }
  733. assert.NoError(t, f.SetCellStyle("Sheet2", "A4", "A4", style))
  734. style, err = f.NewStyle(`{"font":{"color":"#777777","strike":true}}`)
  735. if !assert.NoError(t, err) {
  736. t.FailNow()
  737. }
  738. assert.NoError(t, f.SetCellStyle("Sheet2", "A5", "A5", style))
  739. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellStyleFont.xlsx")))
  740. }
  741. func TestSetCellStyleProtection(t *testing.T) {
  742. f, err := prepareTestBook1()
  743. if !assert.NoError(t, err) {
  744. t.FailNow()
  745. }
  746. var style int
  747. style, err = f.NewStyle(`{"protection":{"hidden":true, "locked":true}}`)
  748. if !assert.NoError(t, err) {
  749. t.FailNow()
  750. }
  751. assert.NoError(t, f.SetCellStyle("Sheet2", "A6", "A6", style))
  752. err = f.SaveAs(filepath.Join("test", "TestSetCellStyleProtection.xlsx"))
  753. if !assert.NoError(t, err) {
  754. t.FailNow()
  755. }
  756. }
  757. func TestSetDeleteSheet(t *testing.T) {
  758. t.Run("TestBook3", func(t *testing.T) {
  759. f, err := prepareTestBook3()
  760. if !assert.NoError(t, err) {
  761. t.FailNow()
  762. }
  763. f.DeleteSheet("XLSXSheet3")
  764. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook3.xlsx")))
  765. })
  766. t.Run("TestBook4", func(t *testing.T) {
  767. f, err := prepareTestBook4()
  768. if !assert.NoError(t, err) {
  769. t.FailNow()
  770. }
  771. f.DeleteSheet("Sheet1")
  772. assert.EqualError(t, f.AddComment("Sheet1", "A1", ""), "unexpected end of JSON input")
  773. assert.NoError(t, f.AddComment("Sheet1", "A1", `{"author":"Excelize: ","text":"This is a comment."}`))
  774. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetDeleteSheet.TestBook4.xlsx")))
  775. })
  776. }
  777. func TestSheetVisibility(t *testing.T) {
  778. f, err := prepareTestBook1()
  779. if !assert.NoError(t, err) {
  780. t.FailNow()
  781. }
  782. assert.NoError(t, f.SetSheetVisible("Sheet2", false))
  783. assert.NoError(t, f.SetSheetVisible("Sheet1", false))
  784. assert.NoError(t, f.SetSheetVisible("Sheet1", true))
  785. assert.Equal(t, true, f.GetSheetVisible("Sheet1"))
  786. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSheetVisibility.xlsx")))
  787. }
  788. func TestCopySheet(t *testing.T) {
  789. f, err := prepareTestBook1()
  790. if !assert.NoError(t, err) {
  791. t.FailNow()
  792. }
  793. idx := f.NewSheet("CopySheet")
  794. assert.NoError(t, f.CopySheet(0, idx))
  795. assert.NoError(t, f.SetCellValue("CopySheet", "F1", "Hello"))
  796. val, err := f.GetCellValue("Sheet1", "F1")
  797. assert.NoError(t, err)
  798. assert.NotEqual(t, "Hello", val)
  799. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheet.xlsx")))
  800. }
  801. func TestCopySheetError(t *testing.T) {
  802. f, err := prepareTestBook1()
  803. if !assert.NoError(t, err) {
  804. t.FailNow()
  805. }
  806. assert.EqualError(t, f.copySheet(-1, -2), "sheet is not exist")
  807. if !assert.EqualError(t, f.CopySheet(-1, -2), "invalid worksheet index") {
  808. t.FailNow()
  809. }
  810. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestCopySheetError.xlsx")))
  811. }
  812. func TestGetSheetComments(t *testing.T) {
  813. f := NewFile()
  814. assert.Equal(t, "", f.getSheetComments("sheet0"))
  815. }
  816. func TestSetSheetVisible(t *testing.T) {
  817. f := NewFile()
  818. f.WorkBook.Sheets.Sheet[0].Name = "SheetN"
  819. assert.EqualError(t, f.SetSheetVisible("Sheet1", false), "sheet SheetN is not exist")
  820. }
  821. func TestGetActiveSheetIndex(t *testing.T) {
  822. f := NewFile()
  823. f.WorkBook.BookViews = nil
  824. assert.Equal(t, 0, f.GetActiveSheetIndex())
  825. }
  826. func TestRelsWriter(t *testing.T) {
  827. f := NewFile()
  828. f.Relationships.Store("xl/worksheets/sheet/rels/sheet1.xml.rel", &xlsxRelationships{})
  829. f.relsWriter()
  830. }
  831. func TestGetSheetView(t *testing.T) {
  832. f := NewFile()
  833. _, err := f.getSheetView("SheetN", 0)
  834. assert.EqualError(t, err, "sheet SheetN is not exist")
  835. }
  836. func TestConditionalFormat(t *testing.T) {
  837. f := NewFile()
  838. sheet1 := f.GetSheetName(0)
  839. fillCells(f, sheet1, 10, 15)
  840. var format1, format2, format3, format4 int
  841. var err error
  842. // Rose format for bad conditional.
  843. format1, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)
  844. if !assert.NoError(t, err) {
  845. t.FailNow()
  846. }
  847. // Light yellow format for neutral conditional.
  848. format2, err = f.NewConditionalStyle(`{"fill":{"type":"pattern","color":["#FEEAA0"],"pattern":1}}`)
  849. if !assert.NoError(t, err) {
  850. t.FailNow()
  851. }
  852. // Light green format for good conditional.
  853. format3, err = f.NewConditionalStyle(`{"font":{"color":"#09600B"},"fill":{"type":"pattern","color":["#C7EECF"],"pattern":1}}`)
  854. if !assert.NoError(t, err) {
  855. t.FailNow()
  856. }
  857. // conditional style with align and left border.
  858. format4, err = f.NewConditionalStyle(`{"alignment":{"wrap_text":true},"border":[{"type":"left","color":"#000000","style":1}]}`)
  859. if !assert.NoError(t, err) {
  860. t.FailNow()
  861. }
  862. // Color scales: 2 color.
  863. 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"}]`))
  864. // Color scales: 3 color.
  865. 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"}]`))
  866. // Hightlight cells rules: between...
  867. assert.NoError(t, f.SetConditionalFormat(sheet1, "C1:C10", fmt.Sprintf(`[{"type":"cell","criteria":"between","format":%d,"minimum":"6","maximum":"8"}]`, format1)))
  868. // Hightlight cells rules: Greater Than...
  869. assert.NoError(t, f.SetConditionalFormat(sheet1, "D1:D10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"6"}]`, format3)))
  870. // Hightlight cells rules: Equal To...
  871. assert.NoError(t, f.SetConditionalFormat(sheet1, "E1:E10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d}]`, format3)))
  872. // Hightlight cells rules: Not Equal To...
  873. assert.NoError(t, f.SetConditionalFormat(sheet1, "F1:F10", fmt.Sprintf(`[{"type":"unique","criteria":"=","format":%d}]`, format2)))
  874. // Hightlight cells rules: Duplicate Values...
  875. assert.NoError(t, f.SetConditionalFormat(sheet1, "G1:G10", fmt.Sprintf(`[{"type":"duplicate","criteria":"=","format":%d}]`, format2)))
  876. // Top/Bottom rules: Top 10%.
  877. assert.NoError(t, f.SetConditionalFormat(sheet1, "H1:H10", fmt.Sprintf(`[{"type":"top","criteria":"=","format":%d,"value":"6","percent":true}]`, format1)))
  878. // Top/Bottom rules: Above Average...
  879. assert.NoError(t, f.SetConditionalFormat(sheet1, "I1:I10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": true}]`, format3)))
  880. // Top/Bottom rules: Below Average...
  881. assert.NoError(t, f.SetConditionalFormat(sheet1, "J1:J10", fmt.Sprintf(`[{"type":"average","criteria":"=","format":%d, "above_average": false}]`, format1)))
  882. // Data Bars: Gradient Fill.
  883. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  884. // Use a formula to determine which cells to format.
  885. assert.NoError(t, f.SetConditionalFormat(sheet1, "L1:L10", fmt.Sprintf(`[{"type":"formula", "criteria":"L2<3", "format":%d}]`, format1)))
  886. // Alignment/Border cells rules.
  887. assert.NoError(t, f.SetConditionalFormat(sheet1, "M1:M10", fmt.Sprintf(`[{"type":"cell","criteria":">","format":%d,"value":"0"}]`, format4)))
  888. // Test set invalid format set in conditional format.
  889. assert.EqualError(t, f.SetConditionalFormat(sheet1, "L1:L10", ""), "unexpected end of JSON input")
  890. // Set conditional format on not exists worksheet.
  891. assert.EqualError(t, f.SetConditionalFormat("SheetN", "L1:L10", "[]"), "sheet SheetN is not exist")
  892. err = f.SaveAs(filepath.Join("test", "TestConditionalFormat.xlsx"))
  893. if !assert.NoError(t, err) {
  894. t.FailNow()
  895. }
  896. // Set conditional format with illegal valid type.
  897. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"", "criteria":"=", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  898. // Set conditional format with illegal criteria type.
  899. assert.NoError(t, f.SetConditionalFormat(sheet1, "K1:K10", `[{"type":"data_bar", "criteria":"", "min_type":"min","max_type":"max","bar_color":"#638EC6"}]`))
  900. // Set conditional format with file without dxfs element shold not return error.
  901. f, err = OpenFile(filepath.Join("test", "Book1.xlsx"))
  902. if !assert.NoError(t, err) {
  903. t.FailNow()
  904. }
  905. _, err = f.NewConditionalStyle(`{"font":{"color":"#9A0511"},"fill":{"type":"pattern","color":["#FEC7CE"],"pattern":1}}`)
  906. if !assert.NoError(t, err) {
  907. t.FailNow()
  908. }
  909. }
  910. func TestConditionalFormatError(t *testing.T) {
  911. f := NewFile()
  912. sheet1 := f.GetSheetName(0)
  913. fillCells(f, sheet1, 10, 15)
  914. // Set conditional format with illegal JSON string should return error.
  915. _, err := f.NewConditionalStyle("")
  916. if !assert.EqualError(t, err, "unexpected end of JSON input") {
  917. t.FailNow()
  918. }
  919. }
  920. func TestSharedStrings(t *testing.T) {
  921. f, err := OpenFile(filepath.Join("test", "SharedStrings.xlsx"))
  922. if !assert.NoError(t, err) {
  923. t.FailNow()
  924. }
  925. rows, err := f.GetRows("Sheet1")
  926. if !assert.NoError(t, err) {
  927. t.FailNow()
  928. }
  929. assert.Equal(t, "A", rows[0][0])
  930. rows, err = f.GetRows("Sheet2")
  931. if !assert.NoError(t, err) {
  932. t.FailNow()
  933. }
  934. assert.Equal(t, "Test Weight (Kgs)", rows[0][0])
  935. }
  936. func TestSetSheetRow(t *testing.T) {
  937. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  938. if !assert.NoError(t, err) {
  939. t.FailNow()
  940. }
  941. assert.NoError(t, f.SetSheetRow("Sheet1", "B27", &[]interface{}{"cell", nil, int32(42), float64(42), time.Now().UTC()}))
  942. assert.EqualError(t, f.SetSheetRow("Sheet1", "", &[]interface{}{"cell", nil, 2}),
  943. `cannot convert cell "" to coordinates: invalid cell name ""`)
  944. assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", []interface{}{}), ErrParameterInvalid.Error())
  945. assert.EqualError(t, f.SetSheetRow("Sheet1", "B27", &f), ErrParameterInvalid.Error())
  946. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetSheetRow.xlsx")))
  947. }
  948. func TestHSL(t *testing.T) {
  949. var hsl HSL
  950. r, g, b, a := hsl.RGBA()
  951. assert.Equal(t, uint32(0), r)
  952. assert.Equal(t, uint32(0), g)
  953. assert.Equal(t, uint32(0), b)
  954. assert.Equal(t, uint32(0xffff), a)
  955. assert.Equal(t, HSL{0, 0, 0}, hslModel(hsl))
  956. assert.Equal(t, HSL{0, 0, 0}, hslModel(color.Gray16{Y: uint16(1)}))
  957. R, G, B := HSLToRGB(0, 1, 0.4)
  958. assert.Equal(t, uint8(204), R)
  959. assert.Equal(t, uint8(0), G)
  960. assert.Equal(t, uint8(0), B)
  961. R, G, B = HSLToRGB(0, 1, 0.6)
  962. assert.Equal(t, uint8(255), R)
  963. assert.Equal(t, uint8(51), G)
  964. assert.Equal(t, uint8(51), B)
  965. assert.Equal(t, 0.0, hueToRGB(0, 0, -1))
  966. assert.Equal(t, 0.0, hueToRGB(0, 0, 2))
  967. assert.Equal(t, 0.0, hueToRGB(0, 0, 1.0/7))
  968. assert.Equal(t, 0.0, hueToRGB(0, 0, 0.4))
  969. assert.Equal(t, 0.0, hueToRGB(0, 0, 2.0/4))
  970. t.Log(RGBToHSL(255, 255, 0))
  971. h, s, l := RGBToHSL(0, 255, 255)
  972. assert.Equal(t, float64(0.5), h)
  973. assert.Equal(t, float64(1), s)
  974. assert.Equal(t, float64(0.5), l)
  975. t.Log(RGBToHSL(250, 100, 50))
  976. t.Log(RGBToHSL(50, 100, 250))
  977. t.Log(RGBToHSL(250, 50, 100))
  978. }
  979. func TestProtectSheet(t *testing.T) {
  980. f := NewFile()
  981. assert.NoError(t, f.ProtectSheet("Sheet1", nil))
  982. assert.NoError(t, f.ProtectSheet("Sheet1", &FormatSheetProtection{
  983. Password: "password",
  984. EditScenarios: false,
  985. }))
  986. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestProtectSheet.xlsx")))
  987. // Test protect not exists worksheet.
  988. assert.EqualError(t, f.ProtectSheet("SheetN", nil), "sheet SheetN is not exist")
  989. }
  990. func TestUnprotectSheet(t *testing.T) {
  991. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  992. if !assert.NoError(t, err) {
  993. t.FailNow()
  994. }
  995. // Test unprotect not exists worksheet.
  996. assert.EqualError(t, f.UnprotectSheet("SheetN"), "sheet SheetN is not exist")
  997. assert.NoError(t, f.UnprotectSheet("Sheet1"))
  998. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestUnprotectSheet.xlsx")))
  999. }
  1000. func TestSetDefaultTimeStyle(t *testing.T) {
  1001. f := NewFile()
  1002. // Test set default time style on not exists worksheet.
  1003. assert.EqualError(t, f.setDefaultTimeStyle("SheetN", "", 0), "sheet SheetN is not exist")
  1004. // Test set default time style on invalid cell
  1005. assert.EqualError(t, f.setDefaultTimeStyle("Sheet1", "", 42), "cannot convert cell \"\" to coordinates: invalid cell name \"\"")
  1006. }
  1007. func TestAddVBAProject(t *testing.T) {
  1008. f := NewFile()
  1009. assert.NoError(t, f.SetSheetPrOptions("Sheet1", CodeName("Sheet1")))
  1010. assert.EqualError(t, f.AddVBAProject("macros.bin"), "stat macros.bin: no such file or directory")
  1011. assert.EqualError(t, f.AddVBAProject(filepath.Join("test", "Book1.xlsx")), ErrAddVBAProject.Error())
  1012. assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))
  1013. // Test add VBA project twice.
  1014. assert.NoError(t, f.AddVBAProject(filepath.Join("test", "vbaProject.bin")))
  1015. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestAddVBAProject.xlsm")))
  1016. }
  1017. func TestContentTypesReader(t *testing.T) {
  1018. // Test unsupported charset.
  1019. f := NewFile()
  1020. f.ContentTypes = nil
  1021. f.Pkg.Store("[Content_Types].xml", MacintoshCyrillicCharset)
  1022. f.contentTypesReader()
  1023. }
  1024. func TestWorkbookReader(t *testing.T) {
  1025. // Test unsupported charset.
  1026. f := NewFile()
  1027. f.WorkBook = nil
  1028. f.Pkg.Store("xl/workbook.xml", MacintoshCyrillicCharset)
  1029. f.workbookReader()
  1030. }
  1031. func TestWorkSheetReader(t *testing.T) {
  1032. // Test unsupported charset.
  1033. f := NewFile()
  1034. f.Sheet.Delete("xl/worksheets/sheet1.xml")
  1035. f.Pkg.Store("xl/worksheets/sheet1.xml", MacintoshCyrillicCharset)
  1036. _, err := f.workSheetReader("Sheet1")
  1037. assert.EqualError(t, err, "xml decode error: XML syntax error on line 1: invalid UTF-8")
  1038. // Test on no checked worksheet.
  1039. f = NewFile()
  1040. f.Sheet.Delete("xl/worksheets/sheet1.xml")
  1041. f.Pkg.Store("xl/worksheets/sheet1.xml", []byte(`<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData/></worksheet>`))
  1042. f.checked = nil
  1043. _, err = f.workSheetReader("Sheet1")
  1044. assert.NoError(t, err)
  1045. }
  1046. func TestRelsReader(t *testing.T) {
  1047. // Test unsupported charset.
  1048. f := NewFile()
  1049. rels := "xl/_rels/workbook.xml.rels"
  1050. f.Relationships.Store(rels, nil)
  1051. f.Pkg.Store(rels, MacintoshCyrillicCharset)
  1052. f.relsReader(rels)
  1053. }
  1054. func TestDeleteSheetFromWorkbookRels(t *testing.T) {
  1055. f := NewFile()
  1056. rels := "xl/_rels/workbook.xml.rels"
  1057. f.Relationships.Store(rels, nil)
  1058. assert.Equal(t, f.deleteSheetFromWorkbookRels("rID"), "")
  1059. }
  1060. func TestAttrValToInt(t *testing.T) {
  1061. _, err := attrValToInt("r", []xml.Attr{
  1062. {Name: xml.Name{Local: "r"}, Value: "s"}})
  1063. assert.EqualError(t, err, `strconv.Atoi: parsing "s": invalid syntax`)
  1064. }
  1065. func prepareTestBook1() (*File, error) {
  1066. f, err := OpenFile(filepath.Join("test", "Book1.xlsx"))
  1067. if err != nil {
  1068. return nil, err
  1069. }
  1070. err = f.AddPicture("Sheet2", "I9", filepath.Join("test", "images", "excel.jpg"),
  1071. `{"x_offset": 140, "y_offset": 120, "hyperlink": "#Sheet2!D8", "hyperlink_type": "Location"}`)
  1072. if err != nil {
  1073. return nil, err
  1074. }
  1075. // Test add picture to worksheet with offset, external hyperlink and positioning.
  1076. err = f.AddPicture("Sheet1", "F21", filepath.Join("test", "images", "excel.png"),
  1077. `{"x_offset": 10, "y_offset": 10, "hyperlink": "https://github.com/xuri/excelize", "hyperlink_type": "External", "positioning": "oneCell"}`)
  1078. if err != nil {
  1079. return nil, err
  1080. }
  1081. file, err := ioutil.ReadFile(filepath.Join("test", "images", "excel.jpg"))
  1082. if err != nil {
  1083. return nil, err
  1084. }
  1085. err = f.AddPictureFromBytes("Sheet1", "Q1", "", "Excel Logo", ".jpg", file)
  1086. if err != nil {
  1087. return nil, err
  1088. }
  1089. return f, nil
  1090. }
  1091. func prepareTestBook3() (*File, error) {
  1092. f := NewFile()
  1093. f.NewSheet("Sheet1")
  1094. f.NewSheet("XLSXSheet2")
  1095. f.NewSheet("XLSXSheet3")
  1096. if err := f.SetCellInt("XLSXSheet2", "A23", 56); err != nil {
  1097. return nil, err
  1098. }
  1099. if err := f.SetCellStr("Sheet1", "B20", "42"); err != nil {
  1100. return nil, err
  1101. }
  1102. f.SetActiveSheet(0)
  1103. err := f.AddPicture("Sheet1", "H2", filepath.Join("test", "images", "excel.gif"),
  1104. `{"x_scale": 0.5, "y_scale": 0.5, "positioning": "absolute"}`)
  1105. if err != nil {
  1106. return nil, err
  1107. }
  1108. err = f.AddPicture("Sheet1", "C2", filepath.Join("test", "images", "excel.png"), "")
  1109. if err != nil {
  1110. return nil, err
  1111. }
  1112. return f, nil
  1113. }
  1114. func prepareTestBook4() (*File, error) {
  1115. f := NewFile()
  1116. if err := f.SetColWidth("Sheet1", "B", "A", 12); err != nil {
  1117. return f, err
  1118. }
  1119. if err := f.SetColWidth("Sheet1", "A", "B", 12); err != nil {
  1120. return f, err
  1121. }
  1122. if _, err := f.GetColWidth("Sheet1", "A"); err != nil {
  1123. return f, err
  1124. }
  1125. if _, err := f.GetColWidth("Sheet1", "C"); err != nil {
  1126. return f, err
  1127. }
  1128. return f, nil
  1129. }
  1130. func fillCells(f *File, sheet string, colCount, rowCount int) {
  1131. for col := 1; col <= colCount; col++ {
  1132. for row := 1; row <= rowCount; row++ {
  1133. cell, _ := CoordinatesToCellName(col, row)
  1134. if err := f.SetCellStr(sheet, cell, cell); err != nil {
  1135. fmt.Println(err)
  1136. }
  1137. }
  1138. }
  1139. }
  1140. func BenchmarkOpenFile(b *testing.B) {
  1141. for i := 0; i < b.N; i++ {
  1142. if _, err := OpenFile(filepath.Join("test", "Book1.xlsx")); err != nil {
  1143. b.Error(err)
  1144. }
  1145. }
  1146. }