cell_test.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package excelize
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "reflect"
  6. "strconv"
  7. "strings"
  8. "sync"
  9. "testing"
  10. "time"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. func TestConcurrency(t *testing.T) {
  14. f := NewFile()
  15. wg := new(sync.WaitGroup)
  16. for i := 1; i <= 5; i++ {
  17. wg.Add(1)
  18. go func(val int, t *testing.T) {
  19. assert.NoError(t, f.SetCellValue("Sheet1", fmt.Sprintf("A%d", val), val))
  20. assert.NoError(t, f.SetCellValue("Sheet1", fmt.Sprintf("B%d", val), strconv.Itoa(val)))
  21. _, err := f.GetCellValue("Sheet1", fmt.Sprintf("A%d", val))
  22. assert.NoError(t, err)
  23. wg.Done()
  24. }(i, t)
  25. }
  26. wg.Wait()
  27. val, err := f.GetCellValue("Sheet1", "A1")
  28. if err != nil {
  29. t.Error(err)
  30. }
  31. assert.Equal(t, "1", val)
  32. }
  33. func TestCheckCellInArea(t *testing.T) {
  34. f := NewFile()
  35. expectedTrueCellInAreaList := [][2]string{
  36. {"c2", "A1:AAZ32"},
  37. {"B9", "A1:B9"},
  38. {"C2", "C2:C2"},
  39. }
  40. for _, expectedTrueCellInArea := range expectedTrueCellInAreaList {
  41. cell := expectedTrueCellInArea[0]
  42. area := expectedTrueCellInArea[1]
  43. ok, err := f.checkCellInArea(cell, area)
  44. assert.NoError(t, err)
  45. assert.Truef(t, ok,
  46. "Expected cell %v to be in area %v, got false\n", cell, area)
  47. }
  48. expectedFalseCellInAreaList := [][2]string{
  49. {"c2", "A4:AAZ32"},
  50. {"C4", "D6:A1"}, // weird case, but you never know
  51. {"AEF42", "BZ40:AEF41"},
  52. }
  53. for _, expectedFalseCellInArea := range expectedFalseCellInAreaList {
  54. cell := expectedFalseCellInArea[0]
  55. area := expectedFalseCellInArea[1]
  56. ok, err := f.checkCellInArea(cell, area)
  57. assert.NoError(t, err)
  58. assert.Falsef(t, ok,
  59. "Expected cell %v not to be inside of area %v, but got true\n", cell, area)
  60. }
  61. ok, err := f.checkCellInArea("A1", "A:B")
  62. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  63. assert.False(t, ok)
  64. ok, err = f.checkCellInArea("AA0", "Z0:AB1")
  65. assert.EqualError(t, err, `cannot convert cell "AA0" to coordinates: invalid cell name "AA0"`)
  66. assert.False(t, ok)
  67. }
  68. func TestSetCellFloat(t *testing.T) {
  69. sheet := "Sheet1"
  70. t.Run("with no decimal", func(t *testing.T) {
  71. f := NewFile()
  72. assert.NoError(t, f.SetCellFloat(sheet, "A1", 123.0, -1, 64))
  73. assert.NoError(t, f.SetCellFloat(sheet, "A2", 123.0, 1, 64))
  74. val, err := f.GetCellValue(sheet, "A1")
  75. assert.NoError(t, err)
  76. assert.Equal(t, "123", val, "A1 should be 123")
  77. val, err = f.GetCellValue(sheet, "A2")
  78. assert.NoError(t, err)
  79. assert.Equal(t, "123.0", val, "A2 should be 123.0")
  80. })
  81. t.Run("with a decimal and precision limit", func(t *testing.T) {
  82. f := NewFile()
  83. assert.NoError(t, f.SetCellFloat(sheet, "A1", 123.42, 1, 64))
  84. val, err := f.GetCellValue(sheet, "A1")
  85. assert.NoError(t, err)
  86. assert.Equal(t, "123.4", val, "A1 should be 123.4")
  87. })
  88. t.Run("with a decimal and no limit", func(t *testing.T) {
  89. f := NewFile()
  90. assert.NoError(t, f.SetCellFloat(sheet, "A1", 123.42, -1, 64))
  91. val, err := f.GetCellValue(sheet, "A1")
  92. assert.NoError(t, err)
  93. assert.Equal(t, "123.42", val, "A1 should be 123.42")
  94. })
  95. f := NewFile()
  96. assert.EqualError(t, f.SetCellFloat(sheet, "A", 123.42, -1, 64), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  97. }
  98. func TestSetCellValue(t *testing.T) {
  99. f := NewFile()
  100. assert.EqualError(t, f.SetCellValue("Sheet1", "A", time.Now().UTC()), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  101. assert.EqualError(t, f.SetCellValue("Sheet1", "A", time.Duration(1e13)), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  102. }
  103. func TestSetCellValues(t *testing.T) {
  104. f := NewFile()
  105. err := f.SetCellValue("Sheet1", "A1", time.Date(2010, time.December, 31, 0, 0, 0, 0, time.UTC))
  106. assert.NoError(t, err)
  107. v, err := f.GetCellValue("Sheet1", "A1")
  108. assert.NoError(t, err)
  109. assert.Equal(t, v, "12/31/10 00:00")
  110. // test date value lower than min date supported by Excel
  111. err = f.SetCellValue("Sheet1", "A1", time.Date(1600, time.December, 31, 0, 0, 0, 0, time.UTC))
  112. assert.NoError(t, err)
  113. v, err = f.GetCellValue("Sheet1", "A1")
  114. assert.NoError(t, err)
  115. assert.Equal(t, v, "1600-12-31T00:00:00Z")
  116. }
  117. func TestSetCellBool(t *testing.T) {
  118. f := NewFile()
  119. assert.EqualError(t, f.SetCellBool("Sheet1", "A", true), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  120. }
  121. func TestGetCellValue(t *testing.T) {
  122. // Test get cell value without r attribute of the row.
  123. f := NewFile()
  124. sheetData := `<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetData>%s</sheetData></worksheet>`
  125. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  126. f.XLSX["xl/worksheets/sheet1.xml"] = []byte(fmt.Sprintf(sheetData, `<row r="3"><c t="str"><v>A3</v></c></row><row><c t="str"><v>A4</v></c><c t="str"><v>B4</v></c></row><row r="7"><c t="str"><v>A7</v></c><c t="str"><v>B7</v></c></row><row><c t="str"><v>A8</v></c><c t="str"><v>B8</v></c></row>`))
  127. f.checked = nil
  128. cells := []string{"A3", "A4", "B4", "A7", "B7"}
  129. rows, err := f.GetRows("Sheet1")
  130. assert.Equal(t, [][]string{nil, nil, {"A3"}, {"A4", "B4"}, nil, nil, {"A7", "B7"}, {"A8", "B8"}}, rows)
  131. assert.NoError(t, err)
  132. for _, cell := range cells {
  133. value, err := f.GetCellValue("Sheet1", cell)
  134. assert.Equal(t, cell, value)
  135. assert.NoError(t, err)
  136. }
  137. cols, err := f.GetCols("Sheet1")
  138. assert.Equal(t, [][]string{{"", "", "A3", "A4", "", "", "A7", "A8"}, {"", "", "", "B4", "", "", "B7", "B8"}}, cols)
  139. assert.NoError(t, err)
  140. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  141. f.XLSX["xl/worksheets/sheet1.xml"] = []byte(fmt.Sprintf(sheetData, `<row r="2"><c r="A2" t="str"><v>A2</v></c></row><row r="2"><c r="B2" t="str"><v>B2</v></c></row>`))
  142. f.checked = nil
  143. cell, err := f.GetCellValue("Sheet1", "A2")
  144. assert.Equal(t, "A2", cell)
  145. assert.NoError(t, err)
  146. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  147. f.XLSX["xl/worksheets/sheet1.xml"] = []byte(fmt.Sprintf(sheetData, `<row r="2"><c r="A2" t="str"><v>A2</v></c></row><row r="2"><c r="B2" t="str"><v>B2</v></c></row>`))
  148. f.checked = nil
  149. rows, err = f.GetRows("Sheet1")
  150. assert.Equal(t, [][]string{nil, {"A2", "B2"}}, rows)
  151. assert.NoError(t, err)
  152. delete(f.Sheet, "xl/worksheets/sheet1.xml")
  153. f.XLSX["xl/worksheets/sheet1.xml"] = []byte(fmt.Sprintf(sheetData, `<row r="1"><c r="A1" t="str"><v>A1</v></c></row><row r="1"><c r="B1" t="str"><v>B1</v></c></row>`))
  154. f.checked = nil
  155. rows, err = f.GetRows("Sheet1")
  156. assert.Equal(t, [][]string{{"A1", "B1"}}, rows)
  157. assert.NoError(t, err)
  158. }
  159. func TestGetCellFormula(t *testing.T) {
  160. // Test get cell formula on not exist worksheet.
  161. f := NewFile()
  162. _, err := f.GetCellFormula("SheetN", "A1")
  163. assert.EqualError(t, err, "sheet SheetN is not exist")
  164. // Test get cell formula on no formula cell.
  165. assert.NoError(t, f.SetCellValue("Sheet1", "A1", true))
  166. _, err = f.GetCellFormula("Sheet1", "A1")
  167. assert.NoError(t, err)
  168. }
  169. func ExampleFile_SetCellFloat() {
  170. f := NewFile()
  171. var x = 3.14159265
  172. if err := f.SetCellFloat("Sheet1", "A1", x, 2, 64); err != nil {
  173. fmt.Println(err)
  174. }
  175. val, _ := f.GetCellValue("Sheet1", "A1")
  176. fmt.Println(val)
  177. // Output: 3.14
  178. }
  179. func BenchmarkSetCellValue(b *testing.B) {
  180. values := []string{"First", "Second", "Third", "Fourth", "Fifth", "Sixth"}
  181. cols := []string{"A", "B", "C", "D", "E", "F"}
  182. f := NewFile()
  183. b.ResetTimer()
  184. for i := 1; i <= b.N; i++ {
  185. for j := 0; j < len(values); j++ {
  186. if err := f.SetCellValue("Sheet1", cols[j]+strconv.Itoa(i), values[j]); err != nil {
  187. b.Error(err)
  188. }
  189. }
  190. }
  191. }
  192. func TestOverflowNumericCell(t *testing.T) {
  193. f, err := OpenFile(filepath.Join("test", "OverflowNumericCell.xlsx"))
  194. if !assert.NoError(t, err) {
  195. t.FailNow()
  196. }
  197. val, err := f.GetCellValue("Sheet1", "A1")
  198. assert.NoError(t, err)
  199. // GOARCH=amd64 - all ok; GOARCH=386 - actual: "-2147483648"
  200. assert.Equal(t, "8595602512225", val, "A1 should be 8595602512225")
  201. }
  202. func TestGetCellRichText(t *testing.T) {
  203. f := NewFile()
  204. runsSource := []RichTextRun{
  205. {
  206. Text: "a\n",
  207. },
  208. {
  209. Text: "b",
  210. Font: &Font{
  211. Underline: "single",
  212. Color: "ff0000",
  213. Bold: true,
  214. Italic: true,
  215. Family: "Times New Roman",
  216. Size: 100,
  217. Strike: true,
  218. },
  219. },
  220. }
  221. assert.NoError(t, f.SetCellRichText("Sheet1", "A1", runsSource))
  222. runs, err := f.GetCellRichText("Sheet1", "A1")
  223. assert.NoError(t, err)
  224. assert.Equal(t, runsSource[0].Text, runs[0].Text)
  225. assert.Nil(t, runs[0].Font)
  226. assert.NotNil(t, runs[1].Font)
  227. runsSource[1].Font.Color = strings.ToUpper(runsSource[1].Font.Color)
  228. assert.True(t, reflect.DeepEqual(runsSource[1].Font, runs[1].Font), "should get the same font")
  229. // Test get cell rich text when string item index overflow
  230. f.Sheet["xl/worksheets/sheet1.xml"].SheetData.Row[0].C[0].V = "2"
  231. runs, err = f.GetCellRichText("Sheet1", "A1")
  232. assert.NoError(t, err)
  233. assert.Equal(t, 0, len(runs))
  234. // Test get cell rich text when string item index is negative
  235. f.Sheet["xl/worksheets/sheet1.xml"].SheetData.Row[0].C[0].V = "-1"
  236. runs, err = f.GetCellRichText("Sheet1", "A1")
  237. assert.NoError(t, err)
  238. assert.Equal(t, 0, len(runs))
  239. // Test get cell rich text on invalid string item index
  240. f.Sheet["xl/worksheets/sheet1.xml"].SheetData.Row[0].C[0].V = "x"
  241. _, err = f.GetCellRichText("Sheet1", "A1")
  242. assert.EqualError(t, err, "strconv.Atoi: parsing \"x\": invalid syntax")
  243. // Test set cell rich text on not exists worksheet
  244. _, err = f.GetCellRichText("SheetN", "A1")
  245. assert.EqualError(t, err, "sheet SheetN is not exist")
  246. // Test set cell rich text with illegal cell coordinates
  247. _, err = f.GetCellRichText("Sheet1", "A")
  248. assert.EqualError(t, err, `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  249. }
  250. func TestSetCellRichText(t *testing.T) {
  251. f := NewFile()
  252. assert.NoError(t, f.SetRowHeight("Sheet1", 1, 35))
  253. assert.NoError(t, f.SetColWidth("Sheet1", "A", "A", 44))
  254. richTextRun := []RichTextRun{
  255. {
  256. Text: "bold",
  257. Font: &Font{
  258. Bold: true,
  259. Color: "2354e8",
  260. Family: "Times New Roman",
  261. },
  262. },
  263. {
  264. Text: " and ",
  265. Font: &Font{
  266. Family: "Times New Roman",
  267. },
  268. },
  269. {
  270. Text: "italic ",
  271. Font: &Font{
  272. Bold: true,
  273. Color: "e83723",
  274. Italic: true,
  275. Family: "Times New Roman",
  276. },
  277. },
  278. {
  279. Text: "text with color and font-family,",
  280. Font: &Font{
  281. Bold: true,
  282. Color: "2354e8",
  283. Family: "Times New Roman",
  284. },
  285. },
  286. {
  287. Text: "\r\nlarge text with ",
  288. Font: &Font{
  289. Size: 14,
  290. Color: "ad23e8",
  291. },
  292. },
  293. {
  294. Text: "strike",
  295. Font: &Font{
  296. Color: "e89923",
  297. Strike: true,
  298. },
  299. },
  300. {
  301. Text: " and ",
  302. Font: &Font{
  303. Size: 14,
  304. Color: "ad23e8",
  305. },
  306. },
  307. {
  308. Text: "underline.",
  309. Font: &Font{
  310. Color: "23e833",
  311. Underline: "single",
  312. },
  313. },
  314. }
  315. assert.NoError(t, f.SetCellRichText("Sheet1", "A1", richTextRun))
  316. assert.NoError(t, f.SetCellRichText("Sheet1", "A2", richTextRun))
  317. style, err := f.NewStyle(&Style{
  318. Alignment: &Alignment{
  319. WrapText: true,
  320. },
  321. })
  322. assert.NoError(t, err)
  323. assert.NoError(t, f.SetCellStyle("Sheet1", "A1", "A1", style))
  324. assert.NoError(t, f.SaveAs(filepath.Join("test", "TestSetCellRichText.xlsx")))
  325. // Test set cell rich text on not exists worksheet
  326. assert.EqualError(t, f.SetCellRichText("SheetN", "A1", richTextRun), "sheet SheetN is not exist")
  327. // Test set cell rich text with illegal cell coordinates
  328. assert.EqualError(t, f.SetCellRichText("Sheet1", "A", richTextRun), `cannot convert cell "A" to coordinates: invalid cell name "A"`)
  329. }
  330. func TestFormattedValue2(t *testing.T) {
  331. f := NewFile()
  332. v := f.formattedValue(0, "43528")
  333. assert.Equal(t, "43528", v)
  334. v = f.formattedValue(15, "43528")
  335. assert.Equal(t, "43528", v)
  336. v = f.formattedValue(1, "43528")
  337. assert.Equal(t, "43528", v)
  338. customNumFmt := "[$-409]MM/DD/YYYY"
  339. _, err := f.NewStyle(&Style{
  340. CustomNumFmt: &customNumFmt,
  341. })
  342. assert.NoError(t, err)
  343. v = f.formattedValue(1, "43528")
  344. assert.Equal(t, "03/04/2019", v)
  345. // formatted value with no built-in number format ID
  346. numFmtID := 5
  347. f.Styles.CellXfs.Xf = append(f.Styles.CellXfs.Xf, xlsxXf{
  348. NumFmtID: &numFmtID,
  349. })
  350. v = f.formattedValue(2, "43528")
  351. assert.Equal(t, "43528", v)
  352. // formatted value with invalid number format ID
  353. f.Styles.CellXfs.Xf = append(f.Styles.CellXfs.Xf, xlsxXf{
  354. NumFmtID: nil,
  355. })
  356. _ = f.formattedValue(3, "43528")
  357. // formatted value with empty number format
  358. f.Styles.NumFmts = nil
  359. f.Styles.CellXfs.Xf = append(f.Styles.CellXfs.Xf, xlsxXf{
  360. NumFmtID: &numFmtID,
  361. })
  362. v = f.formattedValue(1, "43528")
  363. assert.Equal(t, "43528", v)
  364. }