stream_test.go 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809
  1. package xlsx
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "reflect"
  7. "strings"
  8. . "gopkg.in/check.v1"
  9. )
  10. const (
  11. TestsShouldMakeRealFiles = false
  12. )
  13. type StreamSuite struct{}
  14. var _ = Suite(&StreamSuite{})
  15. func (s *StreamSuite) TestTestsShouldMakeRealFilesShouldBeFalse(t *C) {
  16. if TestsShouldMakeRealFiles {
  17. t.Fatal("TestsShouldMakeRealFiles should only be true for local debugging. Don't forget to switch back before commiting.")
  18. }
  19. }
  20. func (s *StreamSuite) TestXlsxStreamWrite(t *C) {
  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 [][][]string
  29. headerTypes [][]*CellType
  30. expectedError error
  31. }{
  32. {
  33. testName: "One Sheet",
  34. sheetNames: []string{
  35. "Sheet1",
  36. },
  37. workbookData: [][][]string{
  38. {
  39. {"Token", "Name", "Price", "SKU"},
  40. {"123", "Taco", "300", "0000000123"},
  41. },
  42. },
  43. headerTypes: [][]*CellType{
  44. {nil, CellTypeString.Ptr(), nil, CellTypeString.Ptr()},
  45. },
  46. },
  47. {
  48. testName: "One Column",
  49. sheetNames: []string{
  50. "Sheet1",
  51. },
  52. workbookData: [][][]string{
  53. {
  54. {"Token"},
  55. {"123"},
  56. },
  57. },
  58. },
  59. {
  60. testName: "Several Sheets, with different numbers of columns and rows",
  61. sheetNames: []string{
  62. "Sheet 1", "Sheet 2", "Sheet3",
  63. },
  64. workbookData: [][][]string{
  65. {
  66. {"Token", "Name", "Price", "SKU"},
  67. {"123", "Taco", "300", "0000000123"},
  68. },
  69. {
  70. {"Token", "Name", "Price", "SKU", "Stock"},
  71. {"456", "Salsa", "200", "0346", "1"},
  72. {"789", "Burritos", "400", "754", "3"},
  73. },
  74. {
  75. {"Token", "Name", "Price"},
  76. {"9853", "Guacamole", "500"},
  77. {"2357", "Margarita", "700"},
  78. },
  79. },
  80. },
  81. {
  82. testName: "Two Sheets with same the name",
  83. sheetNames: []string{
  84. "Sheet 1", "Sheet 1",
  85. },
  86. workbookData: [][][]string{
  87. {
  88. {"Token", "Name", "Price", "SKU"},
  89. {"123", "Taco", "300", "0000000123"},
  90. },
  91. {
  92. {"Token", "Name", "Price", "SKU", "Stock"},
  93. {"456", "Salsa", "200", "0346", "1"},
  94. {"789", "Burritos", "400", "754", "3"},
  95. },
  96. },
  97. expectedError: fmt.Errorf("duplicate sheet name '%s'.", "Sheet 1"),
  98. },
  99. {
  100. testName: "One Sheet Registered, tries to write to two",
  101. sheetNames: []string{
  102. "Sheet 1",
  103. },
  104. workbookData: [][][]string{
  105. {
  106. {"Token", "Name", "Price", "SKU"},
  107. {"123", "Taco", "300", "0000000123"},
  108. },
  109. {
  110. {"Token", "Name", "Price", "SKU"},
  111. {"456", "Salsa", "200", "0346"},
  112. },
  113. },
  114. expectedError: AlreadyOnLastSheetError,
  115. },
  116. {
  117. testName: "One Sheet, too many columns in row 1",
  118. sheetNames: []string{
  119. "Sheet 1",
  120. },
  121. workbookData: [][][]string{
  122. {
  123. {"Token", "Name", "Price", "SKU"},
  124. {"123", "Taco", "300", "0000000123", "asdf"},
  125. },
  126. },
  127. expectedError: WrongNumberOfRowsError,
  128. },
  129. {
  130. testName: "One Sheet, too few columns in row 1",
  131. sheetNames: []string{
  132. "Sheet 1",
  133. },
  134. workbookData: [][][]string{
  135. {
  136. {"Token", "Name", "Price", "SKU"},
  137. {"123", "Taco", "300"},
  138. },
  139. },
  140. expectedError: WrongNumberOfRowsError,
  141. },
  142. {
  143. testName: "Lots of Sheets, only writes rows to one, only writes headers to one, should not error and should still create a valid file",
  144. sheetNames: []string{
  145. "Sheet 1", "Sheet 2", "Sheet 3", "Sheet 4", "Sheet 5", "Sheet 6",
  146. },
  147. workbookData: [][][]string{
  148. {
  149. {"Token", "Name", "Price", "SKU"},
  150. {"123", "Taco", "300", "0000000123"},
  151. },
  152. {{}},
  153. {{"Id", "Unit Cost"}},
  154. {{}},
  155. {{}},
  156. {{}},
  157. },
  158. },
  159. {
  160. testName: "Two Sheets, only writes to one, should not error and should still create a valid file",
  161. sheetNames: []string{
  162. "Sheet 1", "Sheet 2",
  163. },
  164. workbookData: [][][]string{
  165. {
  166. {"Token", "Name", "Price", "SKU"},
  167. {"123", "Taco", "300", "0000000123"},
  168. },
  169. {{}},
  170. },
  171. },
  172. {
  173. testName: "Larger Sheet",
  174. sheetNames: []string{
  175. "Sheet 1",
  176. },
  177. workbookData: [][][]string{
  178. {
  179. {"Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU"},
  180. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  181. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  182. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  183. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  184. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  185. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  186. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  187. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  188. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  189. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  190. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  191. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  192. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  193. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  194. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  195. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  196. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  197. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  198. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  199. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  200. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  201. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  202. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  203. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  204. },
  205. },
  206. },
  207. {
  208. testName: "UTF-8 Characters. This XLSX File loads correctly with Excel, Numbers, and Google Docs. It also passes Microsoft's Office File Format Validator.",
  209. sheetNames: []string{
  210. "Sheet1",
  211. },
  212. workbookData: [][][]string{
  213. {
  214. // String courtesy of https://github.com/minimaxir/big-list-of-naughty-strings/
  215. // Header row contains the tags that I am filtering on
  216. {"Token", endSheetDataTag, "Price", fmt.Sprintf(dimensionTag, "A1:D1")},
  217. // Japanese and emojis
  218. {"123", "パーティーへ行かないか", "300", "🍕🐵 🙈 🙉 🙊"},
  219. // XML encoder/parser test strings
  220. {"123", `<?xml version="1.0" encoding="ISO-8859-1"?>`, "300", `<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>`},
  221. // Upside down text and Right to Left Arabic text
  222. {"123", `˙ɐ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˥
  223. 00˙Ɩ$-`, "300", `ﷺ`},
  224. {"123", "Taco", "300", "0000000123"},
  225. },
  226. },
  227. },
  228. }
  229. for i, testCase := range testCases {
  230. var filePath string
  231. var buffer bytes.Buffer
  232. if TestsShouldMakeRealFiles {
  233. filePath = fmt.Sprintf("Workbook%d.xlsx", i)
  234. }
  235. err := writeStreamFile(filePath, &buffer, testCase.sheetNames, testCase.workbookData, testCase.headerTypes, TestsShouldMakeRealFiles, false)
  236. if err != testCase.expectedError && err.Error() != testCase.expectedError.Error() {
  237. t.Fatalf("Error differs from expected error. Error: %v, Expected Error: %v ", err, testCase.expectedError)
  238. }
  239. if testCase.expectedError != nil {
  240. return
  241. }
  242. // read the file back with the xlsx package
  243. var bufReader *bytes.Reader
  244. var size int64
  245. if !TestsShouldMakeRealFiles {
  246. bufReader = bytes.NewReader(buffer.Bytes())
  247. size = bufReader.Size()
  248. }
  249. actualSheetNames, actualWorkbookData, _ := readXLSXFile(t, filePath, bufReader, size, TestsShouldMakeRealFiles)
  250. // check if data was able to be read correctly
  251. if !reflect.DeepEqual(actualSheetNames, testCase.sheetNames) {
  252. t.Fatal("Expected sheet names to be equal")
  253. }
  254. if !reflect.DeepEqual(actualWorkbookData, testCase.workbookData) {
  255. t.Fatal("Expected workbook data to be equal")
  256. }
  257. }
  258. }
  259. func (s *StreamSuite) TestXlsxStreamWriteWithDefaultCellType(t *C) {
  260. // When shouldMakeRealFiles is set to true this test will make actual XLSX files in the file system.
  261. // This is useful to ensure files open in Excel, Numbers, Google Docs, etc.
  262. // In case of issues you can use "Open XML SDK 2.5" to diagnose issues in generated XLSX files:
  263. // https://www.microsoft.com/en-us/download/details.aspx?id=30425
  264. testCases := []struct {
  265. testName string
  266. sheetNames []string
  267. workbookData [][][]string
  268. headerTypes [][]*CellType
  269. expectedError error
  270. }{
  271. {
  272. testName: "One Sheet",
  273. sheetNames: []string{
  274. "Sheet1",
  275. },
  276. workbookData: [][][]string{
  277. {
  278. {"Token", "Name", "Price", "SKU"},
  279. {"123", "Taco", "300", "0000000123"},
  280. },
  281. },
  282. headerTypes: [][]*CellType{
  283. {nil, CellTypeString.Ptr(), CellTypeNumeric.Ptr(), CellTypeString.Ptr()},
  284. },
  285. },
  286. {
  287. testName: "One Column",
  288. sheetNames: []string{
  289. "Sheet1",
  290. },
  291. workbookData: [][][]string{
  292. {
  293. {"Token"},
  294. {"123"},
  295. },
  296. },
  297. headerTypes: [][]*CellType{
  298. {CellTypeNumeric.Ptr()},
  299. },
  300. },
  301. {
  302. testName: "Several Sheets, with different numbers of columns and rows",
  303. sheetNames: []string{
  304. "Sheet 1", "Sheet 2", "Sheet3",
  305. },
  306. workbookData: [][][]string{
  307. {
  308. {"Token", "Name", "Price", "SKU"},
  309. {"123", "Taco", "variable", "0000000123"},
  310. },
  311. {
  312. {"Token", "Name", "Price", "SKU", "Stock"},
  313. {"456", "Salsa", "200", "0346", "1"},
  314. {"789", "Burritos", "400", "754", "3"},
  315. },
  316. {
  317. {"Token", "Name", "Price"},
  318. {"9853", "Guacamole", "500"},
  319. {"2357", "Margarita", "700"},
  320. },
  321. },
  322. headerTypes: [][]*CellType{
  323. {CellTypeNumeric.Ptr(), CellTypeString.Ptr(), CellTypeNumeric.Ptr(), CellTypeString.Ptr()},
  324. {nil, CellTypeString.Ptr(), nil, CellTypeString.Ptr(), nil},
  325. {nil, nil, nil},
  326. },
  327. },
  328. {
  329. testName: "Two Sheets with same the name",
  330. sheetNames: []string{
  331. "Sheet 1", "Sheet 1",
  332. },
  333. workbookData: [][][]string{
  334. {
  335. {"Token", "Name", "Price", "SKU"},
  336. {"123", "Taco", "300", "0000000123"},
  337. },
  338. {
  339. {"Token", "Name", "Price", "SKU", "Stock"},
  340. {"456", "Salsa", "200", "0346", "1"},
  341. {"789", "Burritos", "400", "754", "3"},
  342. },
  343. },
  344. expectedError: fmt.Errorf("duplicate sheet name '%s'.", "Sheet 1"),
  345. },
  346. {
  347. testName: "One Sheet Registered, tries to write to two",
  348. sheetNames: []string{
  349. "Sheet 1",
  350. },
  351. workbookData: [][][]string{
  352. {
  353. {"Token", "Name", "Price", "SKU"},
  354. {"123", "Taco", "300", "0000000123"},
  355. },
  356. {
  357. {"Token", "Name", "Price", "SKU"},
  358. {"456", "Salsa", "200", "0346"},
  359. },
  360. },
  361. expectedError: AlreadyOnLastSheetError,
  362. },
  363. {
  364. testName: "One Sheet, too many columns in row 1",
  365. sheetNames: []string{
  366. "Sheet 1",
  367. },
  368. workbookData: [][][]string{
  369. {
  370. {"Token", "Name", "Price", "SKU"},
  371. {"123", "Taco", "300", "0000000123", "asdf"},
  372. },
  373. },
  374. expectedError: WrongNumberOfRowsError,
  375. },
  376. {
  377. testName: "One Sheet, too few columns in row 1",
  378. sheetNames: []string{
  379. "Sheet 1",
  380. },
  381. workbookData: [][][]string{
  382. {
  383. {"Token", "Name", "Price", "SKU"},
  384. {"123", "Taco", "300"},
  385. },
  386. },
  387. expectedError: WrongNumberOfRowsError,
  388. },
  389. {
  390. testName: "Lots of Sheets, only writes rows to one, only writes headers to one, should not error and should still create a valid file",
  391. sheetNames: []string{
  392. "Sheet 1", "Sheet 2", "Sheet 3", "Sheet 4", "Sheet 5", "Sheet 6",
  393. },
  394. workbookData: [][][]string{
  395. {
  396. {"Token", "Name", "Price", "SKU"},
  397. {"123", "Taco", "300", "0000000123"},
  398. },
  399. {{}},
  400. {{"Id", "Unit Cost"}},
  401. {{}},
  402. {{}},
  403. {{}},
  404. },
  405. headerTypes: [][]*CellType{
  406. {CellTypeNumeric.Ptr(), CellTypeString.Ptr(), CellTypeNumeric.Ptr(), CellTypeString.Ptr()},
  407. {nil},
  408. {nil, nil},
  409. {nil},
  410. {nil},
  411. {nil},
  412. },
  413. },
  414. {
  415. testName: "Two Sheets, only writes to one, should not error and should still create a valid file",
  416. sheetNames: []string{
  417. "Sheet 1", "Sheet 2",
  418. },
  419. workbookData: [][][]string{
  420. {
  421. {"Token", "Name", "Price", "SKU"},
  422. {"123", "Taco", "300", "0000000123"},
  423. },
  424. {{}},
  425. },
  426. headerTypes: [][]*CellType{
  427. {CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeString.Ptr()},
  428. {nil},
  429. },
  430. },
  431. {
  432. testName: "Larger Sheet",
  433. sheetNames: []string{
  434. "Sheet 1",
  435. },
  436. workbookData: [][][]string{
  437. {
  438. {"Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU"},
  439. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  440. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  441. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  442. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  443. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  444. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  445. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  446. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  447. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  448. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  449. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  450. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  451. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  452. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  453. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  454. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  455. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  456. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  457. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  458. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  459. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  460. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  461. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  462. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  463. },
  464. },
  465. headerTypes: [][]*CellType{
  466. {CellTypeNumeric.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeString.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr()},
  467. },
  468. },
  469. {
  470. testName: "UTF-8 Characters. This XLSX File loads correctly with Excel, Numbers, and Google Docs. It also passes Microsoft's Office File Format Validator.",
  471. sheetNames: []string{
  472. "Sheet1",
  473. },
  474. workbookData: [][][]string{
  475. {
  476. // String courtesy of https://github.com/minimaxir/big-list-of-naughty-strings/
  477. // Header row contains the tags that I am filtering on
  478. {"Token", endSheetDataTag, "Price", fmt.Sprintf(dimensionTag, "A1:D1")},
  479. // Japanese and emojis
  480. {"123", "パーティーへ行かないか", "300", "🍕🐵 🙈 🙉 🙊"},
  481. // XML encoder/parser test strings
  482. {"123", `<?xml version="1.0" encoding="ISO-8859-1"?>`, "300", `<?xml version="1.0" encoding="ISO-8859-1"?><!DOCTYPE foo [ <!ELEMENT foo ANY ><!ENTITY xxe SYSTEM "file:///etc/passwd" >]><foo>&xxe;</foo>`},
  483. // Upside down text and Right to Left Arabic text
  484. {"123", `˙ɐ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˥
  485. 00˙Ɩ$-`, "300", `ﷺ`},
  486. {"123", "Taco", "300", "0000000123"},
  487. },
  488. },
  489. headerTypes: [][]*CellType{
  490. {CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeDate.Ptr(), CellTypeString.Ptr(), CellTypeString.Ptr()},
  491. },
  492. },
  493. }
  494. for i, testCase := range testCases {
  495. var filePath string
  496. var buffer bytes.Buffer
  497. if TestsShouldMakeRealFiles {
  498. filePath = fmt.Sprintf("WorkbookTyped%d.xlsx", i)
  499. }
  500. err := writeStreamFile(filePath, &buffer, testCase.sheetNames, testCase.workbookData, testCase.headerTypes, TestsShouldMakeRealFiles, true)
  501. if err != testCase.expectedError && err.Error() != testCase.expectedError.Error() {
  502. t.Fatalf("Error differs from expected error. Error: %v, Expected Error: %v ", err, testCase.expectedError)
  503. }
  504. if testCase.expectedError != nil {
  505. return
  506. }
  507. // read the file back with the xlsx package
  508. var bufReader *bytes.Reader
  509. var size int64
  510. if !TestsShouldMakeRealFiles {
  511. bufReader = bytes.NewReader(buffer.Bytes())
  512. size = bufReader.Size()
  513. }
  514. actualSheetNames, actualWorkbookData, workbookCellTypes := readXLSXFile(t, filePath, bufReader, size, TestsShouldMakeRealFiles)
  515. verifyCellTypesInColumnMatchHeaderType(t, workbookCellTypes, testCase.headerTypes, testCase.workbookData)
  516. // check if data was able to be read correctly
  517. if !reflect.DeepEqual(actualSheetNames, testCase.sheetNames) {
  518. t.Fatal("Expected sheet names to be equal")
  519. }
  520. if !reflect.DeepEqual(actualWorkbookData, testCase.workbookData) {
  521. t.Fatal("Expected workbook data to be equal")
  522. }
  523. /*if len(testCase.headerTypes) != 0 {
  524. testCaseLogic(true)
  525. }*/
  526. }
  527. }
  528. // Ensures that the cell type of all cells in each column across all sheets matches the provided header types
  529. // in each corresponding sheet
  530. func verifyCellTypesInColumnMatchHeaderType(t *C, workbookCellTypes [][][]CellType, headerTypes [][]*CellType, workbookData [][][]string) {
  531. numSheets := len(workbookCellTypes)
  532. numHeaders := len(headerTypes)
  533. if numSheets != numHeaders {
  534. t.Fatalf("Number of sheets in workbook: %d not equal to number of sheet headers: %d", numSheets, numHeaders)
  535. }
  536. for sheetI, headers := range headerTypes {
  537. var sanitizedHeaders []CellType
  538. for _, headerType := range headers {
  539. // if `Col.defaultCellType` is `nil` in `StreamFile.writeWithColumnDefaultCellType` we give it a
  540. // `CellTypeString` by default but then later `StreamFile.makeXlsxCell` actually encodes `CellTypeString` as
  541. // `CellTypeInline` before marshalling
  542. if headerType == (*CellType)(nil) || *headerType == CellTypeString {
  543. sanitizedHeaders = append(sanitizedHeaders, CellTypeInline)
  544. } else {
  545. sanitizedHeaders = append(sanitizedHeaders, *headerType)
  546. }
  547. }
  548. sheet := workbookCellTypes[sheetI]
  549. // Skip header row
  550. for rowI, row := range sheet[1:] {
  551. if len(row) != len(headers) {
  552. t.Fatalf("Number of cells in row: %d not equal number of headers; %d", len(row), len(headers))
  553. }
  554. for colI, cellType := range row {
  555. headerTypeForCol := sanitizedHeaders[colI]
  556. if cellType != headerTypeForCol.fallbackTo(workbookData[sheetI][rowI+1][colI], CellTypeInline) {
  557. t.Fatalf("Cell type %d in row: %d and col: %d does not match header type: %d for this col in sheet: %d",
  558. cellType, rowI, colI, headerTypeForCol, sheetI)
  559. }
  560. }
  561. }
  562. }
  563. }
  564. // The purpose of TestXlsxStyleBehavior is to ensure that initMaxStyleId has the correct starting value
  565. // and that the logic in AddSheet() that predicts Style IDs is correct.
  566. func (s *StreamSuite) TestXlsxStyleBehavior(t *C) {
  567. file := NewFile()
  568. sheet, err := file.AddSheet("Sheet 1")
  569. if err != nil {
  570. t.Fatal(err)
  571. }
  572. row := sheet.AddRow()
  573. rowData := []string{"testing", "1", "2", "3"}
  574. if count := row.WriteSlice(&rowData, -1); count != len(rowData) {
  575. t.Fatal("not enough cells written")
  576. }
  577. parts, err := file.MarshallParts()
  578. styleSheet, ok := parts["xl/styles.xml"]
  579. if !ok {
  580. t.Fatal("no style sheet")
  581. }
  582. // Created an XLSX file with only the default style.
  583. // We expect that the number of styles is one more than our max index constant.
  584. // This means the library adds two styles by default.
  585. if !strings.Contains(styleSheet, fmt.Sprintf(`<cellXfs count="%d">`, initMaxStyleId+1)) {
  586. t.Fatal("Expected sheet to have two styles")
  587. }
  588. file = NewFile()
  589. sheet, err = file.AddSheet("Sheet 1")
  590. if err != nil {
  591. t.Fatal(err)
  592. }
  593. row = sheet.AddRow()
  594. rowData = []string{"testing", "1", "2", "3", "4"}
  595. if count := row.WriteSlice(&rowData, -1); count != len(rowData) {
  596. t.Fatal("not enough cells written")
  597. }
  598. sheet.Cols[0].SetType(CellTypeString)
  599. sheet.Cols[1].SetType(CellTypeString)
  600. sheet.Cols[3].SetType(CellTypeNumeric)
  601. sheet.Cols[4].SetType(CellTypeString)
  602. parts, err = file.MarshallParts()
  603. styleSheet, ok = parts["xl/styles.xml"]
  604. if !ok {
  605. t.Fatal("no style sheet")
  606. }
  607. // Created an XLSX file with two distinct cell types, which should create two new styles.
  608. // The same cell type was added three times, this should be coalesced into the same style rather than
  609. // recreating the style. This XLSX stream library depends on this behavior when predicting the next style id.
  610. if !strings.Contains(styleSheet, fmt.Sprintf(`<cellXfs count="%d">`, initMaxStyleId+1+2)) {
  611. t.Fatal("Expected sheet to have four styles")
  612. }
  613. }
  614. // writeStreamFile will write the file using this stream package
  615. func writeStreamFile(filePath string, fileBuffer io.Writer, sheetNames []string, workbookData [][][]string, headerTypes [][]*CellType, shouldMakeRealFiles bool, useHeaderTypeAsCellType bool) error {
  616. var file *StreamFileBuilder
  617. var err error
  618. if shouldMakeRealFiles {
  619. file, err = NewStreamFileBuilderForPath(filePath)
  620. if err != nil {
  621. return err
  622. }
  623. } else {
  624. file = NewStreamFileBuilder(fileBuffer)
  625. }
  626. for i, sheetName := range sheetNames {
  627. header := workbookData[i][0]
  628. var sheetHeaderTypes []*CellType
  629. if i < len(headerTypes) {
  630. sheetHeaderTypes = headerTypes[i]
  631. }
  632. err := file.AddSheet(sheetName, header, sheetHeaderTypes)
  633. if err != nil {
  634. return err
  635. }
  636. }
  637. streamFile, err := file.Build()
  638. if err != nil {
  639. return err
  640. }
  641. for i, sheetData := range workbookData {
  642. if i != 0 {
  643. err = streamFile.NextSheet()
  644. if err != nil {
  645. return err
  646. }
  647. }
  648. for i, row := range sheetData {
  649. if i == 0 {
  650. continue
  651. }
  652. if useHeaderTypeAsCellType {
  653. err = streamFile.WriteWithDefaultCellType(row)
  654. } else {
  655. err = streamFile.Write(row)
  656. }
  657. if err != nil {
  658. return err
  659. }
  660. }
  661. }
  662. err = streamFile.Close()
  663. if err != nil {
  664. return err
  665. }
  666. return nil
  667. }
  668. // readXLSXFile will read the file using the xlsx package.
  669. func readXLSXFile(t *C, filePath string, fileBuffer io.ReaderAt, size int64, shouldMakeRealFiles bool) ([]string, [][][]string, [][][]CellType) {
  670. var readFile *File
  671. var err error
  672. if shouldMakeRealFiles {
  673. readFile, err = OpenFile(filePath)
  674. if err != nil {
  675. t.Fatal(err)
  676. }
  677. } else {
  678. readFile, err = OpenReaderAt(fileBuffer, size)
  679. if err != nil {
  680. t.Fatal(err)
  681. }
  682. }
  683. var actualWorkbookData [][][]string
  684. var workbookCellTypes [][][]CellType
  685. var sheetNames []string
  686. for _, sheet := range readFile.Sheets {
  687. sheetData := [][]string{}
  688. sheetCellTypes := [][]CellType{}
  689. for _, row := range sheet.Rows {
  690. data := []string{}
  691. cellTypes := []CellType{}
  692. for _, cell := range row.Cells {
  693. str, err := cell.FormattedValue()
  694. if err != nil {
  695. t.Fatal(err)
  696. }
  697. data = append(data, str)
  698. cellTypes = append(cellTypes, cell.Type())
  699. }
  700. sheetData = append(sheetData, data)
  701. sheetCellTypes = append(sheetCellTypes, cellTypes)
  702. }
  703. sheetNames = append(sheetNames, sheet.Name)
  704. actualWorkbookData = append(actualWorkbookData, sheetData)
  705. workbookCellTypes = append(workbookCellTypes, sheetCellTypes)
  706. }
  707. return sheetNames, actualWorkbookData, workbookCellTypes
  708. }
  709. func (s *StreamSuite) TestAddSheetErrorsAfterBuild(t *C) {
  710. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  711. err := file.AddSheet("Sheet1", []string{"Header"}, nil)
  712. if err != nil {
  713. t.Fatal(err)
  714. }
  715. err = file.AddSheet("Sheet2", []string{"Header2"}, nil)
  716. if err != nil {
  717. t.Fatal(err)
  718. }
  719. _, err = file.Build()
  720. if err != nil {
  721. t.Fatal(err)
  722. }
  723. err = file.AddSheet("Sheet3", []string{"Header3"}, nil)
  724. if err != BuiltStreamFileBuilderError {
  725. t.Fatal(err)
  726. }
  727. }
  728. func (s *StreamSuite) TestBuildErrorsAfterBuild(t *C) {
  729. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  730. err := file.AddSheet("Sheet1", []string{"Header"}, nil)
  731. if err != nil {
  732. t.Fatal(err)
  733. }
  734. err = file.AddSheet("Sheet2", []string{"Header2"}, nil)
  735. if err != nil {
  736. t.Fatal(err)
  737. }
  738. _, err = file.Build()
  739. if err != nil {
  740. t.Fatal(err)
  741. }
  742. _, err = file.Build()
  743. if err != BuiltStreamFileBuilderError {
  744. t.Fatal(err)
  745. }
  746. }
  747. func (s *StreamSuite) TestCloseWithNothingWrittenToSheets(t *C) {
  748. buffer := bytes.NewBuffer(nil)
  749. file := NewStreamFileBuilder(buffer)
  750. sheetNames := []string{"Sheet1", "Sheet2"}
  751. workbookData := [][][]string{
  752. {{"Header1", "Header2"}},
  753. {{"Header3", "Header4"}},
  754. }
  755. err := file.AddSheet(sheetNames[0], workbookData[0][0], nil)
  756. if err != nil {
  757. t.Fatal(err)
  758. }
  759. err = file.AddSheet(sheetNames[1], workbookData[1][0], nil)
  760. if err != nil {
  761. t.Fatal(err)
  762. }
  763. stream, err := file.Build()
  764. if err != nil {
  765. t.Fatal(err)
  766. }
  767. err = stream.Close()
  768. if err != nil {
  769. t.Fatal(err)
  770. }
  771. bufReader := bytes.NewReader(buffer.Bytes())
  772. size := bufReader.Size()
  773. actualSheetNames, actualWorkbookData, _ := readXLSXFile(t, "", bufReader, size, false)
  774. // check if data was able to be read correctly
  775. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  776. t.Fatal("Expected sheet names to be equal")
  777. }
  778. if !reflect.DeepEqual(actualWorkbookData, workbookData) {
  779. t.Fatal("Expected workbook data to be equal")
  780. }
  781. }