stream_style_test.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  1. package xlsx
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "reflect"
  8. "strconv"
  9. "testing"
  10. "time"
  11. )
  12. const (
  13. StyleStreamTestsShouldMakeRealFiles = false
  14. )
  15. func TestStreamTestsShouldMakeRealFilesShouldBeFalse(t *testing.T) {
  16. if StyleStreamTestsShouldMakeRealFiles {
  17. t.Fatal("TestsShouldMakeRealFiles should only be true for local debugging. Don't forget to switch back before commiting.")
  18. }
  19. }
  20. func TestXlsxStreamWriteWithStyle(t *testing.T) {
  21. // When shouldMakeRealFiles is set to true this test will make actual XLSX files in the file system.
  22. // This is useful to ensure files open in Excel, Numbers, Google Docs, etc.
  23. // In case of issues you can use "Open XML SDK 2.5" to diagnose issues in generated XLSX files:
  24. // https://www.microsoft.com/en-us/download/details.aspx?id=30425
  25. testCases := []struct {
  26. testName string
  27. sheetNames []string
  28. workbookData [][][]StreamCell
  29. expectedError error
  30. }{
  31. {
  32. testName: "Style Test",
  33. sheetNames: []string{
  34. "Sheet1",
  35. },
  36. workbookData: [][][]StreamCell{
  37. {
  38. {
  39. NewStyledStringStreamCell("1", StreamStyleUnderlinedString),
  40. NewStyledStringStreamCell("25", StreamStyleItalicString),
  41. NewStyledStringStreamCell("A", StreamStyleBoldString),
  42. NewStringStreamCell("B"),
  43. },
  44. {
  45. NewIntegerStreamCell(1234),
  46. NewStyledIntegerStreamCell(98, StreamStyleBoldInteger),
  47. NewStyledIntegerStreamCell(34, StreamStyleItalicInteger),
  48. NewStyledIntegerStreamCell(26, StreamStyleUnderlinedInteger),
  49. },
  50. },
  51. },
  52. },
  53. {
  54. testName: "One Sheet",
  55. sheetNames: []string{
  56. "Sheet1",
  57. },
  58. workbookData: [][][]StreamCell{
  59. {
  60. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  61. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  62. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  63. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  64. },
  65. },
  66. },
  67. {
  68. testName: "One Column",
  69. sheetNames: []string{
  70. "Sheet1",
  71. },
  72. workbookData: [][][]StreamCell{
  73. {
  74. {NewStringStreamCell("Token")},
  75. {NewIntegerStreamCell(123)},
  76. },
  77. },
  78. },
  79. {
  80. testName: "Several Sheets, with different numbers of columns and rows",
  81. sheetNames: []string{
  82. "Sheet 1", "Sheet 2", "Sheet3",
  83. },
  84. workbookData: [][][]StreamCell{
  85. {
  86. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  87. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  88. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  89. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  90. },
  91. {
  92. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  93. NewStringStreamCell("Price"), NewStringStreamCell("SKU"),
  94. NewStringStreamCell("Stock")},
  95. {NewIntegerStreamCell(456), NewStringStreamCell("Salsa"),
  96. NewIntegerStreamCell(200), NewIntegerStreamCell(346),
  97. NewIntegerStreamCell(1)},
  98. {NewIntegerStreamCell(789), NewStringStreamCell("Burritos"),
  99. NewIntegerStreamCell(400), NewIntegerStreamCell(754),
  100. NewIntegerStreamCell(3)},
  101. },
  102. {
  103. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  104. NewStringStreamCell("Price")},
  105. {NewIntegerStreamCell(9853), NewStringStreamCell("Guacamole"),
  106. NewIntegerStreamCell(500)},
  107. {NewIntegerStreamCell(2357), NewStringStreamCell("Margarita"),
  108. NewIntegerStreamCell(700)},
  109. },
  110. },
  111. },
  112. {
  113. testName: "Two Sheets with same the name",
  114. sheetNames: []string{
  115. "Sheet 1", "Sheet 1",
  116. },
  117. workbookData: [][][]StreamCell{
  118. {
  119. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  120. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  121. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  122. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  123. },
  124. {
  125. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  126. NewStringStreamCell("Price"), NewStringStreamCell("SKU"),
  127. NewStringStreamCell("Stock")},
  128. {NewIntegerStreamCell(456), NewStringStreamCell("Salsa"),
  129. NewIntegerStreamCell(200), NewIntegerStreamCell(346),
  130. NewIntegerStreamCell(1)},
  131. {NewIntegerStreamCell(789), NewStringStreamCell("Burritos"),
  132. NewIntegerStreamCell(400), NewIntegerStreamCell(754),
  133. NewIntegerStreamCell(3)},
  134. },
  135. },
  136. expectedError: fmt.Errorf("duplicate sheet name '%s'.", "Sheet 1"),
  137. },
  138. {
  139. testName: "One Sheet Registered, tries to write to two",
  140. sheetNames: []string{
  141. "Sheet 1",
  142. },
  143. workbookData: [][][]StreamCell{
  144. {
  145. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  146. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  147. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  148. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  149. },
  150. {
  151. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  152. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  153. {NewIntegerStreamCell(456), NewStringStreamCell("Salsa"),
  154. NewIntegerStreamCell(200), NewIntegerStreamCell(346)},
  155. },
  156. },
  157. expectedError: AlreadyOnLastSheetError,
  158. },
  159. {
  160. testName: "One Sheet, too many columns in row 1",
  161. sheetNames: []string{
  162. "Sheet 1",
  163. },
  164. workbookData: [][][]StreamCell{
  165. {
  166. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  167. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  168. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  169. NewIntegerStreamCell(300), NewIntegerStreamCell(123),
  170. NewStringStreamCell("asdf")},
  171. },
  172. },
  173. expectedError: WrongNumberOfRowsError,
  174. },
  175. {
  176. testName: "One Sheet, too few columns in row 1",
  177. sheetNames: []string{
  178. "Sheet 1",
  179. },
  180. workbookData: [][][]StreamCell{
  181. {
  182. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  183. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  184. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  185. NewIntegerStreamCell(300)},
  186. },
  187. },
  188. expectedError: WrongNumberOfRowsError,
  189. },
  190. {
  191. testName: "Lots of Sheets, only writes rows to one, only writes headers to one, should not error and should still create a valid file",
  192. sheetNames: []string{
  193. "Sheet 1", "Sheet 2", "Sheet 3", "Sheet 4", "Sheet 5", "Sheet 6",
  194. },
  195. workbookData: [][][]StreamCell{
  196. {
  197. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  198. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  199. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  200. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  201. },
  202. {{}},
  203. {{NewStringStreamCell("Id"), NewStringStreamCell("Unit Cost")}},
  204. {{}},
  205. {{}},
  206. {{}},
  207. },
  208. },
  209. {
  210. testName: "Two Sheets, only writes to one, should not error and should still create a valid file",
  211. sheetNames: []string{
  212. "Sheet 1", "Sheet 2",
  213. },
  214. workbookData: [][][]StreamCell{
  215. {
  216. {NewStringStreamCell("Token"), NewStringStreamCell("Name"),
  217. NewStringStreamCell("Price"), NewStringStreamCell("SKU")},
  218. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  219. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  220. },
  221. {{}},
  222. },
  223. },
  224. {
  225. testName: "UTF-8 Characters. This XLSX File loads correctly with Excel, Numbers, and Google Docs. It also passes Microsoft's Office File Format Validator.",
  226. sheetNames: []string{
  227. "Sheet1",
  228. },
  229. workbookData: [][][]StreamCell{
  230. {
  231. // String courtesy of https://github.com/minimaxir/big-list-of-naughty-strings/
  232. // Header row contains the tags that I am filtering on
  233. {NewStringStreamCell("Token"), NewStringStreamCell(endSheetDataTag),
  234. NewStringStreamCell("Price"), NewStringStreamCell(fmt.Sprintf(dimensionTag, "A1:D1"))},
  235. // Japanese and emojis
  236. {NewIntegerStreamCell(123), NewStringStreamCell("パーティーへ行かないか"),
  237. NewIntegerStreamCell(300), NewStringStreamCell("🍕🐵 🙈 🙉 🙊")},
  238. // XML encoder/parser test strings
  239. {NewIntegerStreamCell(123), NewStringStreamCell(`<?xml version="1.0" encoding="ISO-8859-1"?>`),
  240. NewIntegerStreamCell(300), NewStringStreamCell(`<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>`)},
  241. // Upside down text and Right to Left Arabic text
  242. {NewIntegerStreamCell(123), NewStringStreamCell(`˙ɐnbᴉlɐ ɐuƃɐɯ ǝɹolop ʇǝ ǝɹoqɐl ʇn ʇunpᴉpᴉɔuᴉ ɹodɯǝʇ poɯsnᴉǝ op pǝs 'ʇᴉlǝ ƃuᴉɔsᴉdᴉpɐ ɹnʇǝʇɔǝsuoɔ 'ʇǝɯɐ ʇᴉs ɹolop ɯnsdᴉ ɯǝɹo˥
  243. 00˙Ɩ$-`), NewIntegerStreamCell(300), NewStringStreamCell(`ﷺ`)},
  244. {NewIntegerStreamCell(123), NewStringStreamCell("Taco"),
  245. NewIntegerStreamCell(300), NewIntegerStreamCell(123)},
  246. },
  247. },
  248. },
  249. }
  250. for i, testCase := range testCases {
  251. t.Run(testCase.testName, func(t *testing.T) {
  252. var filePath string
  253. var buffer bytes.Buffer
  254. if StyleStreamTestsShouldMakeRealFiles {
  255. filePath = fmt.Sprintf("WorkbookWithStyle%d.xlsx", i)
  256. }
  257. err := writeStreamFileWithStyle(filePath, &buffer, testCase.sheetNames, testCase.workbookData, StyleStreamTestsShouldMakeRealFiles, []StreamStyle{})
  258. switch {
  259. case err == nil && testCase.expectedError != nil:
  260. t.Fatalf("Expected error but none was returned")
  261. case err != nil && testCase.expectedError == nil:
  262. t.Fatalf("Unexpected error: %q", err.Error())
  263. case err != testCase.expectedError && err.Error() != testCase.expectedError.Error():
  264. t.Fatalf("Error differs from expected error. Error: %v, Expected Error: %v ", err, testCase.expectedError)
  265. case err != nil:
  266. // We got an expected error
  267. return
  268. }
  269. // read the file back with the xlsx package
  270. var bufReader *bytes.Reader
  271. var size int64
  272. if !StyleStreamTestsShouldMakeRealFiles {
  273. bufReader = bytes.NewReader(buffer.Bytes())
  274. size = bufReader.Size()
  275. }
  276. actualSheetNames, actualWorkbookData, actualWorkbookCells := readXLSXFileS(t, filePath, bufReader, size, StyleStreamTestsShouldMakeRealFiles)
  277. // check if data was able to be read correctly
  278. if !reflect.DeepEqual(actualSheetNames, testCase.sheetNames) {
  279. t.Fatal("Expected sheet names to be equal")
  280. }
  281. expectedWorkbookDataStrings := [][][]string{}
  282. for j := range testCase.workbookData {
  283. expectedWorkbookDataStrings = append(expectedWorkbookDataStrings, [][]string{})
  284. for k := range testCase.workbookData[j] {
  285. if len(testCase.workbookData[j][k]) == 0 {
  286. expectedWorkbookDataStrings[j] = append(expectedWorkbookDataStrings[j], nil)
  287. } else {
  288. expectedWorkbookDataStrings[j] = append(expectedWorkbookDataStrings[j], []string{})
  289. for _, cell := range testCase.workbookData[j][k] {
  290. expectedWorkbookDataStrings[j][k] = append(expectedWorkbookDataStrings[j][k], cell.cellData)
  291. }
  292. }
  293. }
  294. }
  295. if !reflect.DeepEqual(actualWorkbookData, expectedWorkbookDataStrings) {
  296. t.Fatal("Expected workbook data to be equal")
  297. }
  298. if err := checkForCorrectCellStyles(actualWorkbookCells, testCase.workbookData); err != nil {
  299. t.Fatal("Expected styles to be equal")
  300. }
  301. })
  302. }
  303. }
  304. // writeStreamFile will write the file using this stream package
  305. func writeStreamFileWithStyle(filePath string, fileBuffer io.Writer, sheetNames []string, workbookData [][][]StreamCell,
  306. shouldMakeRealFiles bool, customStyles []StreamStyle) error {
  307. var file *StreamFileBuilder
  308. var err error
  309. if shouldMakeRealFiles {
  310. file, err = NewStreamFileBuilderForPath(filePath)
  311. if err != nil {
  312. return err
  313. }
  314. } else {
  315. file = NewStreamFileBuilder(fileBuffer)
  316. }
  317. defaultStyles := []StreamStyle{StreamStyleDefaultString, StreamStyleBoldString, StreamStyleItalicString, StreamStyleUnderlinedString,
  318. StreamStyleDefaultInteger, StreamStyleBoldInteger, StreamStyleItalicInteger, StreamStyleUnderlinedInteger,
  319. StreamStyleDefaultDate}
  320. allStylesToBeAdded := append(defaultStyles, customStyles...)
  321. err = file.AddStreamStyleList(allStylesToBeAdded)
  322. if err != nil {
  323. return err
  324. }
  325. for i, sheetName := range sheetNames {
  326. var colStyles []StreamStyle
  327. for range workbookData[i][0] {
  328. colStyles = append(colStyles, StreamStyleDefaultString)
  329. }
  330. err := file.AddSheetS(sheetName, colStyles)
  331. if err != nil {
  332. return err
  333. }
  334. }
  335. streamFile, err := file.Build()
  336. if err != nil {
  337. return err
  338. }
  339. for i, sheetData := range workbookData {
  340. if i != 0 {
  341. err = streamFile.NextSheet()
  342. if err != nil {
  343. return err
  344. }
  345. }
  346. if i%2 == 0 {
  347. err = streamFile.WriteAllS(sheetData)
  348. } else {
  349. for _, row := range sheetData {
  350. err = streamFile.WriteS(row)
  351. if err != nil {
  352. return err
  353. }
  354. }
  355. }
  356. }
  357. err = streamFile.Close()
  358. if err != nil {
  359. return err
  360. }
  361. return nil
  362. }
  363. // readXLSXFileS will read the file using the xlsx package.
  364. func readXLSXFileS(t *testing.T, filePath string, fileBuffer io.ReaderAt, size int64, shouldMakeRealFiles bool) ([]string, [][][]string, [][][]Cell) {
  365. var readFile *File
  366. var err error
  367. if shouldMakeRealFiles {
  368. readFile, err = OpenFile(filePath)
  369. if err != nil {
  370. t.Fatal(err)
  371. }
  372. } else {
  373. readFile, err = OpenReaderAt(fileBuffer, size)
  374. if err != nil {
  375. t.Fatal(err)
  376. }
  377. }
  378. var actualWorkbookData [][][]string
  379. var sheetNames []string
  380. var actualWorkBookCells [][][]Cell
  381. for i, sheet := range readFile.Sheets {
  382. actualWorkBookCells = append(actualWorkBookCells, [][]Cell{})
  383. var sheetData [][]string
  384. for j, row := range sheet.Rows {
  385. actualWorkBookCells[i] = append(actualWorkBookCells[i], []Cell{})
  386. var data []string
  387. for _, cell := range row.Cells {
  388. actualWorkBookCells[i][j] = append(actualWorkBookCells[i][j], *cell)
  389. str, err := cell.FormattedValue()
  390. if err != nil {
  391. t.Fatal(err)
  392. }
  393. data = append(data, str)
  394. }
  395. sheetData = append(sheetData, data)
  396. }
  397. sheetNames = append(sheetNames, sheet.Name)
  398. actualWorkbookData = append(actualWorkbookData, sheetData)
  399. }
  400. return sheetNames, actualWorkbookData, actualWorkBookCells
  401. }
  402. func TestStreamStyleDates(t *testing.T) {
  403. var filePath string
  404. var buffer bytes.Buffer
  405. if StyleStreamTestsShouldMakeRealFiles {
  406. filePath = fmt.Sprintf("Workbook_Date_test.xlsx")
  407. }
  408. // We use a fixed time to avoid weird errors around midnight
  409. fixedTime := time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC)
  410. sheetNames := []string{"Sheet1"}
  411. workbookData := [][][]StreamCell{
  412. {
  413. {NewStringStreamCell("Date:")},
  414. {NewDateStreamCell(fixedTime)},
  415. },
  416. }
  417. err := writeStreamFileWithStyle(filePath, &buffer, sheetNames, workbookData, StyleStreamTestsShouldMakeRealFiles, []StreamStyle{})
  418. if err != nil {
  419. t.Fatalf("Error during writing: %s", err.Error())
  420. }
  421. // read the file back with the xlsx package
  422. var bufReader *bytes.Reader
  423. var size int64
  424. if !StyleStreamTestsShouldMakeRealFiles {
  425. bufReader = bytes.NewReader(buffer.Bytes())
  426. size = bufReader.Size()
  427. }
  428. actualSheetNames, actualWorkbookData, actualWorkbookCells := readXLSXFileS(t, filePath, bufReader, size, StyleStreamTestsShouldMakeRealFiles)
  429. // check if data was able to be read correctly
  430. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  431. t.Fatal("Expected sheet names to be equal")
  432. }
  433. expectedWorkbookDataStrings := [][][]string{}
  434. for j := range workbookData {
  435. expectedWorkbookDataStrings = append(expectedWorkbookDataStrings, [][]string{})
  436. for range workbookData[j] {
  437. expectedWorkbookDataStrings[j] = append(expectedWorkbookDataStrings[j], []string{})
  438. }
  439. }
  440. expectedWorkbookDataStrings[0][0] = append(expectedWorkbookDataStrings[0][0], workbookData[0][0][0].cellData)
  441. year, month, day := fixedTime.Date()
  442. monthString := strconv.Itoa(int(month))
  443. if int(month) < 10 {
  444. monthString = "0" + monthString
  445. }
  446. dayString := strconv.Itoa(day)
  447. if day < 10 {
  448. dayString = "0" + dayString
  449. }
  450. yearString := strconv.Itoa(year - 2000)
  451. if (year - 2000) < 10 {
  452. yearString = "0" + yearString
  453. }
  454. expectedWorkbookDataStrings[0][1] = append(expectedWorkbookDataStrings[0][1],
  455. monthString+"-"+dayString+"-"+yearString)
  456. if !reflect.DeepEqual(actualWorkbookData, expectedWorkbookDataStrings) {
  457. t.Fatalf(`Expected workbook data to be equal:
  458. Expected:
  459. %s
  460. Actual:
  461. %s
  462. `, expectedWorkbookDataStrings, actualWorkbookData)
  463. }
  464. if err := checkForCorrectCellStyles(actualWorkbookCells, workbookData); err != nil {
  465. t.Fatal("Expected styles to be equal")
  466. }
  467. }
  468. func TestMakeNewStylesAndUseIt(t *testing.T) {
  469. var filePath string
  470. var buffer bytes.Buffer
  471. if StyleStreamTestsShouldMakeRealFiles {
  472. filePath = fmt.Sprintf("Workbook_newStyle.xlsx")
  473. }
  474. timesNewRoman12 := NewFont(12, TimesNewRoman)
  475. timesNewRoman12.Color = RGB_Dark_Green
  476. courier12 := NewFont(12, Courier)
  477. courier12.Color = RGB_Dark_Red
  478. greenFill := NewFill(Solid_Cell_Fill, RGB_Light_Green, RGB_White)
  479. redFill := NewFill(Solid_Cell_Fill, RGB_Light_Red, RGB_White)
  480. greenStyle := MakeStyle(GeneralFormat, timesNewRoman12, greenFill, DefaultAlignment(), DefaultBorder())
  481. redStyle := MakeStyle(GeneralFormat, courier12, redFill, DefaultAlignment(), DefaultBorder())
  482. sheetNames := []string{"Sheet1"}
  483. workbookData := [][][]StreamCell{
  484. {
  485. {NewStringStreamCell("TRUE"), NewStringStreamCell("False")},
  486. {NewStyledStringStreamCell("Good", greenStyle), NewStyledStringStreamCell("Bad", redStyle)},
  487. },
  488. }
  489. err := writeStreamFileWithStyle(filePath, &buffer, sheetNames, workbookData, StyleStreamTestsShouldMakeRealFiles, []StreamStyle{greenStyle, redStyle})
  490. if err != nil {
  491. t.Fatal("Error during writing")
  492. }
  493. // read the file back with the xlsx package
  494. var bufReader *bytes.Reader
  495. var size int64
  496. if !StyleStreamTestsShouldMakeRealFiles {
  497. bufReader = bytes.NewReader(buffer.Bytes())
  498. size = bufReader.Size()
  499. }
  500. actualSheetNames, actualWorkbookData, actualWorkbookCells := readXLSXFileS(t, filePath, bufReader, size, StyleStreamTestsShouldMakeRealFiles)
  501. // check if data was able to be read correctly
  502. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  503. t.Fatal("Expected sheet names to be equal")
  504. }
  505. expectedWorkbookDataStrings := [][][]string{}
  506. for j := range workbookData {
  507. expectedWorkbookDataStrings = append(expectedWorkbookDataStrings, [][]string{})
  508. for k := range workbookData[j] {
  509. expectedWorkbookDataStrings[j] = append(expectedWorkbookDataStrings[j], []string{})
  510. for _, cell := range workbookData[j][k] {
  511. expectedWorkbookDataStrings[j][k] = append(expectedWorkbookDataStrings[j][k], cell.cellData)
  512. }
  513. }
  514. }
  515. if !reflect.DeepEqual(actualWorkbookData, expectedWorkbookDataStrings) {
  516. t.Fatal("Expected workbook data to be equal")
  517. }
  518. if err := checkForCorrectCellStyles(actualWorkbookCells, workbookData); err != nil {
  519. t.Fatal("Expected styles to be equal")
  520. }
  521. }
  522. func TestStreamNewTypes(t *testing.T) {
  523. var filePath string
  524. var buffer bytes.Buffer
  525. if StyleStreamTestsShouldMakeRealFiles {
  526. filePath = fmt.Sprintf("Workbook_newStyle.xlsx")
  527. }
  528. sheetNames := []string{"Sheet1"}
  529. workbookData := [][][]StreamCell{
  530. {
  531. {NewStreamCell("1", StreamStyleDefaultString, CellTypeBool),
  532. NewStreamCell("InLine", StreamStyleBoldString, CellTypeInline),
  533. NewStreamCell("Error", StreamStyleDefaultString, CellTypeError)},
  534. },
  535. }
  536. err := writeStreamFileWithStyle(filePath, &buffer, sheetNames, workbookData, StyleStreamTestsShouldMakeRealFiles, []StreamStyle{})
  537. if err != nil {
  538. t.Fatal("Error during writing")
  539. }
  540. // read the file back with the xlsx package
  541. var bufReader *bytes.Reader
  542. var size int64
  543. if !StyleStreamTestsShouldMakeRealFiles {
  544. bufReader = bytes.NewReader(buffer.Bytes())
  545. size = bufReader.Size()
  546. }
  547. actualSheetNames, actualWorkbookData, actualWorkbookCells := readXLSXFileS(t, filePath, bufReader, size, StyleStreamTestsShouldMakeRealFiles)
  548. // check if data was able to be read correctly
  549. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  550. t.Fatal("Expected sheet names to be equal")
  551. }
  552. expectedWorkbookDataStrings := [][][]string{}
  553. for j := range workbookData {
  554. expectedWorkbookDataStrings = append(expectedWorkbookDataStrings, [][]string{})
  555. for k := range workbookData[j] {
  556. expectedWorkbookDataStrings[j] = append(expectedWorkbookDataStrings[j], []string{})
  557. for _, cell := range workbookData[j][k] {
  558. if cell.cellData == "1" {
  559. expectedWorkbookDataStrings[j][k] = append(expectedWorkbookDataStrings[j][k], "TRUE")
  560. } else {
  561. expectedWorkbookDataStrings[j][k] = append(expectedWorkbookDataStrings[j][k], cell.cellData)
  562. }
  563. }
  564. }
  565. }
  566. if !reflect.DeepEqual(actualWorkbookData, expectedWorkbookDataStrings) {
  567. t.Fatal("Expected workbook data to be equal")
  568. }
  569. if err := checkForCorrectCellStyles(actualWorkbookCells, workbookData); err != nil {
  570. t.Fatal("Expected styles to be equal")
  571. }
  572. }
  573. func TestStreamCloseWithNothingWrittenToSheetsWithStyle(t *testing.T) {
  574. buffer := bytes.NewBuffer(nil)
  575. file := NewStreamFileBuilder(buffer)
  576. sheetNames := []string{"Sheet1", "Sheet2"}
  577. workbookData := [][][]StreamCell{
  578. {{NewStringStreamCell("Header1"), NewStringStreamCell("Header2")}},
  579. {{NewStringStreamCell("Header3"), NewStringStreamCell("Header4")}},
  580. }
  581. defaultStyles := []StreamStyle{StreamStyleDefaultString, StreamStyleBoldString, StreamStyleItalicInteger, StreamStyleUnderlinedString,
  582. StreamStyleDefaultInteger, StreamStyleBoldInteger, StreamStyleItalicInteger, StreamStyleUnderlinedInteger,
  583. StreamStyleDefaultDate}
  584. err := file.AddStreamStyleList(defaultStyles)
  585. if err != nil {
  586. t.Fatal(err)
  587. }
  588. colStyles0 := []StreamStyle{}
  589. for range workbookData[0][0] {
  590. colStyles0 = append(colStyles0, StreamStyleDefaultString)
  591. }
  592. colStyles1 := []StreamStyle{}
  593. for range workbookData[1][0] {
  594. colStyles1 = append(colStyles1, StreamStyleDefaultString)
  595. }
  596. err = file.AddSheetS(sheetNames[0], colStyles0)
  597. if err != nil {
  598. t.Fatal(err)
  599. }
  600. err = file.AddSheetS(sheetNames[1], colStyles1)
  601. if err != nil {
  602. t.Fatal(err)
  603. }
  604. stream, err := file.Build()
  605. if err != nil {
  606. t.Fatal(err)
  607. }
  608. err = stream.Close()
  609. if err != nil {
  610. t.Fatal(err)
  611. }
  612. bufReader := bytes.NewReader(buffer.Bytes())
  613. size := bufReader.Size()
  614. actualSheetNames, actualWorkbookData, _ := readXLSXFileS(t, "", bufReader, size, false)
  615. // check if data was able to be read correctly
  616. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  617. t.Fatal("Expected sheet names to be equal")
  618. }
  619. expectedWorkbookDataStrings := [][][]string{}
  620. for range workbookData {
  621. expectedWorkbookDataStrings = append(expectedWorkbookDataStrings, nil)
  622. }
  623. if !reflect.DeepEqual(actualWorkbookData, expectedWorkbookDataStrings) {
  624. t.Fatal("Expected workbook data to be equal")
  625. }
  626. }
  627. func TestStreamBuildErrorsAfterBuildWithStyle(t *testing.T) {
  628. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  629. defaultStyles := []StreamStyle{StreamStyleDefaultString, StreamStyleBoldString, StreamStyleItalicInteger, StreamStyleUnderlinedString,
  630. StreamStyleDefaultInteger, StreamStyleBoldInteger, StreamStyleItalicInteger, StreamStyleUnderlinedInteger,
  631. StreamStyleDefaultDate}
  632. err := file.AddStreamStyleList(defaultStyles)
  633. if err != nil {
  634. t.Fatal(err)
  635. }
  636. err = file.AddSheetS("Sheet1", []StreamStyle{StreamStyleDefaultString})
  637. if err != nil {
  638. t.Fatal(err)
  639. }
  640. err = file.AddSheetS("Sheet2", []StreamStyle{StreamStyleDefaultString})
  641. if err != nil {
  642. t.Fatal(err)
  643. }
  644. _, err = file.Build()
  645. if err != nil {
  646. t.Fatal(err)
  647. }
  648. _, err = file.Build()
  649. if err != BuiltStreamFileBuilderError {
  650. t.Fatal(err)
  651. }
  652. }
  653. func TestStreamAddSheetSWithErrorsAfterBuild(t *testing.T) {
  654. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  655. defaultStyles := []StreamStyle{StreamStyleDefaultString, StreamStyleBoldString, StreamStyleItalicInteger, StreamStyleUnderlinedString,
  656. StreamStyleDefaultInteger, StreamStyleBoldInteger, StreamStyleItalicInteger, StreamStyleUnderlinedInteger,
  657. StreamStyleDefaultDate}
  658. err := file.AddStreamStyleList(defaultStyles)
  659. if err != nil {
  660. t.Fatal(err)
  661. }
  662. err = file.AddSheetS("Sheet1", []StreamStyle{StreamStyleDefaultString})
  663. if err != nil {
  664. t.Fatal(err)
  665. }
  666. err = file.AddSheetS("Sheet2", []StreamStyle{StreamStyleDefaultString})
  667. if err != nil {
  668. t.Fatal(err)
  669. }
  670. _, err = file.Build()
  671. if err != nil {
  672. t.Fatal(err)
  673. }
  674. err = file.AddSheetS("Sheet3", []StreamStyle{StreamStyleDefaultString})
  675. if err != BuiltStreamFileBuilderError {
  676. t.Fatal(err)
  677. }
  678. }
  679. func TestStreamNoStylesAddSheetSError(t *testing.T) {
  680. buffer := bytes.NewBuffer(nil)
  681. file := NewStreamFileBuilder(buffer)
  682. sheetNames := []string{"Sheet1", "Sheet2"}
  683. workbookData := [][][]StreamCell{
  684. {{NewStringStreamCell("Header1"), NewStringStreamCell("Header2")}},
  685. {{NewStyledStringStreamCell("Header3", StreamStyleBoldString), NewStringStreamCell("Header4")}},
  686. }
  687. colStyles0 := []StreamStyle{}
  688. for range workbookData[0][0] {
  689. colStyles0 = append(colStyles0, StreamStyleDefaultString)
  690. }
  691. err := file.AddSheetS(sheetNames[0], colStyles0)
  692. if err.Error() != "trying to make use of a style that has not been added" {
  693. t.Fatal("Error differs from expected error.")
  694. }
  695. }
  696. func TestStreamNoStylesWriteSError(t *testing.T) {
  697. buffer := bytes.NewBuffer(nil)
  698. var filePath string
  699. greenStyle := MakeStyle(GeneralFormat, DefaultFont(), FillGreen, DefaultAlignment(), DefaultBorder())
  700. sheetNames := []string{"Sheet1", "Sheet2"}
  701. workbookData := [][][]StreamCell{
  702. {{NewStringStreamCell("Header1"), NewStringStreamCell("Header2")}},
  703. {{NewStyledStringStreamCell("Header3", greenStyle), NewStringStreamCell("Header4")}},
  704. }
  705. err := writeStreamFileWithStyle(filePath, buffer, sheetNames, workbookData, StyleStreamTestsShouldMakeRealFiles, []StreamStyle{})
  706. expected := "trying to make use of a style that has not been added"
  707. if err.Error() != expected {
  708. t.Fatalf("Error differs from expected error: Expected %q got %q", err.Error(), expected)
  709. }
  710. }
  711. func checkForCorrectCellStyles(actualCells [][][]Cell, expectedCells [][][]StreamCell) error {
  712. for i := range actualCells {
  713. for j := range actualCells[i] {
  714. for k, actualCell := range actualCells[i][j] {
  715. expectedCell := expectedCells[i][j][k]
  716. if err := compareCellStyles(actualCell, expectedCell); err != nil {
  717. return err
  718. }
  719. }
  720. }
  721. }
  722. return nil
  723. }
  724. func compareCellStyles(cellA Cell, cellB StreamCell) error {
  725. fontA := cellA.style.Font
  726. fontB := cellB.cellStyle.style.Font
  727. if fontA != fontB {
  728. return errors.New("actual and expected font do not match")
  729. }
  730. numFmtA := cellA.NumFmt
  731. numFmtB := builtInNumFmt[cellB.cellStyle.xNumFmtId]
  732. if numFmtA != numFmtB {
  733. return errors.New("actual and expected NumFmt do not match")
  734. }
  735. return nil
  736. }