stream_style_test.go 25 KB

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