stream_test.go 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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)
  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. expectedWorkbookData [][][]string
  269. headerTypes [][]*CellMetadata
  270. expectedError error
  271. }{
  272. {
  273. testName: "One Sheet",
  274. sheetNames: []string{
  275. "Sheet1",
  276. },
  277. workbookData: [][][]string{
  278. {
  279. {"Token", "Name", "Price", "SKU"},
  280. {"123", "Taco", "300.0", "0000000123"},
  281. {"123", "Taco", "string", "0000000123"},
  282. },
  283. },
  284. expectedWorkbookData: [][][]string{
  285. {
  286. {"Token", "Name", "Price", "SKU"},
  287. {"123", "Taco", "300.00", "0000000123"},
  288. {"123", "Taco", "string", "0000000123"},
  289. },
  290. },
  291. headerTypes: [][]*CellMetadata{
  292. {DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultDecimalCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr()},
  293. },
  294. },
  295. {
  296. testName: "One Column",
  297. sheetNames: []string{
  298. "Sheet1",
  299. },
  300. workbookData: [][][]string{
  301. {
  302. {"Token"},
  303. {"1234"},
  304. },
  305. },
  306. expectedWorkbookData: [][][]string{
  307. {
  308. {"Token"},
  309. {"1234.00"},
  310. },
  311. },
  312. headerTypes: [][]*CellMetadata{
  313. {DefaultDecimalCellMetadata.Ptr()},
  314. },
  315. },
  316. {
  317. testName: "Several Sheets, with different numbers of columns and rows",
  318. sheetNames: []string{
  319. "Sheet 1", "Sheet 2", "Sheet3",
  320. },
  321. workbookData: [][][]string{
  322. {
  323. {"Token", "Name", "Price", "SKU"},
  324. {"123", "Taco", "300", "0000000123"},
  325. },
  326. {
  327. {"Token", "Name", "Price", "SKU", "Stock"},
  328. {"456", "Salsa", "200", "0346", "1"},
  329. {"789", "Burritos", "400", "754", "3"},
  330. },
  331. {
  332. {"Token", "Name", "Price"},
  333. {"9853", "Guacamole", "500"},
  334. {"2357", "Margarita", "700"},
  335. },
  336. },
  337. expectedWorkbookData: [][][]string{
  338. {
  339. {"Token", "Name", "Price", "SKU"},
  340. {"123", "Taco", "300.00", "0000000123"},
  341. },
  342. {
  343. {"Token", "Name", "Price", "SKU", "Stock"},
  344. {"456", "Salsa", "200.00", "0346", "1"},
  345. {"789", "Burritos", "400.00", "754", "3"},
  346. },
  347. {
  348. {"Token", "Name", "Price"},
  349. {"9853", "Guacamole", "500"},
  350. {"2357", "Margarita", "700"},
  351. },
  352. },
  353. headerTypes: [][]*CellMetadata{
  354. {DefaultIntegerCellMetadata.Ptr(), nil, DefaultDecimalCellMetadata.Ptr(), nil},
  355. {DefaultIntegerCellMetadata.Ptr(), nil, DefaultDecimalCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultIntegerCellMetadata.Ptr()},
  356. {nil, nil, nil},
  357. },
  358. },
  359. {
  360. testName: "Two Sheets with same the name",
  361. sheetNames: []string{
  362. "Sheet 1", "Sheet 1",
  363. },
  364. workbookData: [][][]string{
  365. {
  366. {"Token", "Name", "Price", "SKU"},
  367. {"123", "Taco", "300", "0000000123"},
  368. },
  369. {
  370. {"Token", "Name", "Price", "SKU", "Stock"},
  371. {"456", "Salsa", "200", "0346", "1"},
  372. {"789", "Burritos", "400", "754", "3"},
  373. },
  374. },
  375. expectedError: fmt.Errorf("duplicate sheet name '%s'.", "Sheet 1"),
  376. },
  377. {
  378. testName: "One Sheet Registered, tries to write to two",
  379. sheetNames: []string{
  380. "Sheet 1",
  381. },
  382. workbookData: [][][]string{
  383. {
  384. {"Token", "Name", "Price", "SKU"},
  385. {"123", "Taco", "300", "0000000123"},
  386. },
  387. {
  388. {"Token", "Name", "Price", "SKU"},
  389. {"456", "Salsa", "200", "0346"},
  390. },
  391. },
  392. expectedError: AlreadyOnLastSheetError,
  393. },
  394. {
  395. testName: "One Sheet, too many columns in row 1",
  396. sheetNames: []string{
  397. "Sheet 1",
  398. },
  399. workbookData: [][][]string{
  400. {
  401. {"Token", "Name", "Price", "SKU"},
  402. {"123", "Taco", "300", "0000000123", "asdf"},
  403. },
  404. },
  405. expectedError: WrongNumberOfRowsError,
  406. },
  407. {
  408. testName: "One Sheet, too few columns in row 1",
  409. sheetNames: []string{
  410. "Sheet 1",
  411. },
  412. workbookData: [][][]string{
  413. {
  414. {"Token", "Name", "Price", "SKU"},
  415. {"123", "Taco", "300"},
  416. },
  417. },
  418. expectedError: WrongNumberOfRowsError,
  419. },
  420. {
  421. testName: "Lots of Sheets, only writes rows to one, only writes headers to one, should not error and should still create a valid file",
  422. sheetNames: []string{
  423. "Sheet 1", "Sheet 2", "Sheet 3", "Sheet 4", "Sheet 5", "Sheet 6",
  424. },
  425. workbookData: [][][]string{
  426. {
  427. {"Token", "Name", "Price", "SKU"},
  428. {"123", "Taco", "300", "0000000123"},
  429. },
  430. {{}},
  431. {{"Id", "Unit Cost"}},
  432. {{}},
  433. {{}},
  434. {{}},
  435. },
  436. headerTypes: [][]*CellMetadata{
  437. {DefaultIntegerCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultIntegerCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr()},
  438. {nil},
  439. {nil, nil},
  440. {nil},
  441. {nil},
  442. {nil},
  443. },
  444. },
  445. {
  446. testName: "Two Sheets, only writes to one, should not error and should still create a valid file",
  447. sheetNames: []string{
  448. "Sheet 1", "Sheet 2",
  449. },
  450. workbookData: [][][]string{
  451. {
  452. {"Token", "Name", "Price", "SKU"},
  453. {"123", "Taco", "300", "0000000123"},
  454. },
  455. {{}},
  456. },
  457. headerTypes: [][]*CellMetadata{
  458. {DefaultDateCellMetadata.Ptr(), DefaultDateCellMetadata.Ptr(), DefaultDateCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr()},
  459. {nil},
  460. },
  461. },
  462. {
  463. testName: "Larger Sheet",
  464. sheetNames: []string{
  465. "Sheet 1",
  466. },
  467. workbookData: [][][]string{
  468. {
  469. {"Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU", "Token", "Name", "Price", "SKU"},
  470. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  471. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  472. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  473. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  474. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  475. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  476. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  477. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  478. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  479. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  480. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  481. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  482. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  483. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  484. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  485. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  486. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  487. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  488. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  489. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  490. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  491. {"123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123", "123", "Taco", "300", "0000000123"},
  492. {"456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346", "456", "Salsa", "200", "0346"},
  493. {"789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754", "789", "Burritos", "400", "754"},
  494. },
  495. },
  496. headerTypes: [][]*CellMetadata{
  497. {DefaultIntegerCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultIntegerCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr()},
  498. },
  499. },
  500. {
  501. testName: "UTF-8 Characters. This XLSX File loads correctly with Excel, Numbers, and Google Docs. It also passes Microsoft's Office File Format Validator.",
  502. sheetNames: []string{
  503. "Sheet1",
  504. },
  505. workbookData: [][][]string{
  506. {
  507. // String courtesy of https://github.com/minimaxir/big-list-of-naughty-strings/
  508. // Header row contains the tags that I am filtering on
  509. {"Token", endSheetDataTag, "Price", fmt.Sprintf(dimensionTag, "A1:D1")},
  510. // Japanese and emojis
  511. {"123", "パーティーへ行かないか", "300", "🍕🐵 🙈 🙉 🙊"},
  512. // XML encoder/parser test strings
  513. {"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>`},
  514. // Upside down text and Right to Left Arabic text
  515. {"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˥
  516. 00˙Ɩ$-`, "300", `ﷺ`},
  517. {"123", "Taco", "300", "0000000123"},
  518. },
  519. },
  520. headerTypes: [][]*CellMetadata{
  521. {DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr(), DefaultStringCellMetadata.Ptr()},
  522. },
  523. },
  524. }
  525. for i, testCase := range testCases {
  526. var filePath string
  527. var buffer bytes.Buffer
  528. if TestsShouldMakeRealFiles {
  529. filePath = fmt.Sprintf("WorkbookTyped%d.xlsx", i)
  530. }
  531. err := writeStreamFileWithDefaultMetadata(filePath, &buffer, testCase.sheetNames, testCase.workbookData, testCase.headerTypes, TestsShouldMakeRealFiles)
  532. if err != testCase.expectedError && err.Error() != testCase.expectedError.Error() {
  533. t.Fatalf("Error differs from expected error. Error: %v, Expected Error: %v ", err, testCase.expectedError)
  534. }
  535. if testCase.expectedError != nil {
  536. return
  537. }
  538. // read the file back with the xlsx package
  539. var bufReader *bytes.Reader
  540. var size int64
  541. if !TestsShouldMakeRealFiles {
  542. bufReader = bytes.NewReader(buffer.Bytes())
  543. size = bufReader.Size()
  544. }
  545. actualSheetNames, actualWorkbookData, workbookCellTypes := readXLSXFile(t, filePath, bufReader, size, TestsShouldMakeRealFiles)
  546. verifyCellTypesInColumnMatchHeaderType(t, workbookCellTypes, testCase.headerTypes, testCase.workbookData)
  547. // check if data was able to be read correctly
  548. if !reflect.DeepEqual(actualSheetNames, testCase.sheetNames) {
  549. t.Fatal("Expected sheet names to be equal")
  550. }
  551. if !reflect.DeepEqual(actualWorkbookData, testCase.expectedWorkbookData) {
  552. t.Fatal("Expected workbook data to be equal")
  553. }
  554. }
  555. }
  556. // Ensures that the cell type of all cells in each column across all sheets matches the provided header types
  557. // in each corresponding sheet
  558. func verifyCellTypesInColumnMatchHeaderType(t *C, workbookCellTypes [][][]CellType, headerMetadata [][]*CellMetadata, workbookData [][][]string) {
  559. numSheets := len(workbookCellTypes)
  560. numHeaders := len(headerMetadata)
  561. if numSheets != numHeaders {
  562. t.Fatalf("Number of sheets in workbook: %d not equal to number of sheet headers: %d", numSheets, numHeaders)
  563. }
  564. for sheetI, headers := range headerMetadata {
  565. var sanitizedHeaders []CellType
  566. for _, header := range headers {
  567. if header == (*CellMetadata)(nil) || header.cellType == CellTypeString {
  568. sanitizedHeaders = append(sanitizedHeaders, CellTypeInline)
  569. } else {
  570. sanitizedHeaders = append(sanitizedHeaders, header.cellType)
  571. }
  572. }
  573. sheet := workbookCellTypes[sheetI]
  574. // Skip header row
  575. for rowI, row := range sheet[1:] {
  576. if len(row) != len(headers) {
  577. t.Fatalf("Number of cells in row: %d not equal number of headers; %d", len(row), len(headers))
  578. }
  579. for colI, cellType := range row {
  580. headerTypeForCol := sanitizedHeaders[colI]
  581. if cellType != headerTypeForCol.fallbackTo(workbookData[sheetI][rowI+1][colI], CellTypeInline) {
  582. t.Fatalf("Cell type %d in row: %d and col: %d does not match header type: %d for this col in sheet: %d",
  583. cellType, rowI, colI, headerTypeForCol, sheetI)
  584. }
  585. }
  586. }
  587. }
  588. }
  589. // The purpose of TestXlsxStyleBehavior is to ensure that initMaxStyleId has the correct starting value
  590. // and that the logic in AddSheet() that predicts Style IDs is correct.
  591. func (s *StreamSuite) TestXlsxStyleBehavior(t *C) {
  592. file := NewFile()
  593. sheet, err := file.AddSheet("Sheet 1")
  594. if err != nil {
  595. t.Fatal(err)
  596. }
  597. row := sheet.AddRow()
  598. rowData := []string{"testing", "1", "2", "3"}
  599. if count := row.WriteSlice(&rowData, -1); count != len(rowData) {
  600. t.Fatal("not enough cells written")
  601. }
  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 only the default style.
  608. // We expect that the number of styles is one more than our max index constant.
  609. // This means the library adds two styles by default.
  610. if !strings.Contains(styleSheet, fmt.Sprintf(`<cellXfs count="%d">`, initMaxStyleId+1)) {
  611. t.Fatal("Expected sheet to have two styles")
  612. }
  613. file = NewFile()
  614. sheet, err = file.AddSheet("Sheet 1")
  615. if err != nil {
  616. t.Fatal(err)
  617. }
  618. row = sheet.AddRow()
  619. rowData = []string{"testing", "1", "2", "3", "4"}
  620. if count := row.WriteSlice(&rowData, -1); count != len(rowData) {
  621. t.Fatal("not enough cells written")
  622. }
  623. sheet.Cols[0].SetType(CellTypeString)
  624. sheet.Cols[1].SetType(CellTypeString)
  625. sheet.Cols[3].SetType(CellTypeNumeric)
  626. sheet.Cols[4].SetType(CellTypeString)
  627. parts, err = file.MarshallParts()
  628. styleSheet, ok = parts["xl/styles.xml"]
  629. if !ok {
  630. t.Fatal("no style sheet")
  631. }
  632. // Created an XLSX file with two distinct cell types, which should create two new styles.
  633. // The same cell type was added three times, this should be coalesced into the same style rather than
  634. // recreating the style. This XLSX stream library depends on this behavior when predicting the next style id.
  635. if !strings.Contains(styleSheet, fmt.Sprintf(`<cellXfs count="%d">`, initMaxStyleId+1+2)) {
  636. t.Fatal("Expected sheet to have four styles")
  637. }
  638. }
  639. // writeStreamFile will write the file using this stream package
  640. func writeStreamFile(filePath string, fileBuffer io.Writer, sheetNames []string, workbookData [][][]string, headerTypes [][]*CellType, shouldMakeRealFiles bool) error {
  641. var file *StreamFileBuilder
  642. var err error
  643. if shouldMakeRealFiles {
  644. file, err = NewStreamFileBuilderForPath(filePath)
  645. if err != nil {
  646. return err
  647. }
  648. } else {
  649. file = NewStreamFileBuilder(fileBuffer)
  650. }
  651. for i, sheetName := range sheetNames {
  652. header := workbookData[i][0]
  653. var sheetHeaderTypes []*CellType
  654. if i < len(headerTypes) {
  655. sheetHeaderTypes = headerTypes[i]
  656. }
  657. err := file.AddSheet(sheetName, header, sheetHeaderTypes)
  658. if err != nil {
  659. return err
  660. }
  661. }
  662. streamFile, err := file.Build()
  663. if err != nil {
  664. return err
  665. }
  666. for i, sheetData := range workbookData {
  667. if i != 0 {
  668. err = streamFile.NextSheet()
  669. if err != nil {
  670. return err
  671. }
  672. }
  673. for i, row := range sheetData {
  674. if i == 0 {
  675. continue
  676. }
  677. err = streamFile.Write(row)
  678. if err != nil {
  679. return err
  680. }
  681. }
  682. }
  683. err = streamFile.Close()
  684. if err != nil {
  685. return err
  686. }
  687. return nil
  688. }
  689. // writeStreamFileWithDefaultMetadata is the same thing as writeStreamFile but with headerMetadata instead of headerTypes
  690. func writeStreamFileWithDefaultMetadata(filePath string, fileBuffer io.Writer, sheetNames []string, workbookData [][][]string, headerMetadata [][]*CellMetadata, shouldMakeRealFiles bool) error {
  691. var file *StreamFileBuilder
  692. var err error
  693. if shouldMakeRealFiles {
  694. file, err = NewStreamFileBuilderForPath(filePath)
  695. if err != nil {
  696. return err
  697. }
  698. } else {
  699. file = NewStreamFileBuilder(fileBuffer)
  700. }
  701. for i, sheetName := range sheetNames {
  702. header := workbookData[i][0]
  703. var sheetHeaderTypes []*CellMetadata
  704. if i < len(headerMetadata) {
  705. sheetHeaderTypes = headerMetadata[i]
  706. }
  707. err := file.AddSheetWithDefaultColumnMetadata(sheetName, header, sheetHeaderTypes)
  708. if err != nil {
  709. return err
  710. }
  711. }
  712. streamFile, err := file.Build()
  713. if err != nil {
  714. return err
  715. }
  716. for i, sheetData := range workbookData {
  717. if i != 0 {
  718. err = streamFile.NextSheet()
  719. if err != nil {
  720. return err
  721. }
  722. }
  723. for i, row := range sheetData {
  724. if i == 0 {
  725. continue
  726. }
  727. err = streamFile.WriteWithColumnDefaultMetadata(row)
  728. if err != nil {
  729. return err
  730. }
  731. }
  732. }
  733. err = streamFile.Close()
  734. if err != nil {
  735. return err
  736. }
  737. return nil
  738. }
  739. // readXLSXFile will read the file using the xlsx package.
  740. func readXLSXFile(t *C, filePath string, fileBuffer io.ReaderAt, size int64, shouldMakeRealFiles bool) ([]string, [][][]string, [][][]CellType) {
  741. var readFile *File
  742. var err error
  743. if shouldMakeRealFiles {
  744. readFile, err = OpenFile(filePath)
  745. if err != nil {
  746. t.Fatal(err)
  747. }
  748. } else {
  749. readFile, err = OpenReaderAt(fileBuffer, size)
  750. if err != nil {
  751. t.Fatal(err)
  752. }
  753. }
  754. var actualWorkbookData [][][]string
  755. var workbookCellTypes [][][]CellType
  756. var sheetNames []string
  757. for _, sheet := range readFile.Sheets {
  758. sheetData := [][]string{}
  759. sheetCellTypes := [][]CellType{}
  760. for _, row := range sheet.Rows {
  761. data := []string{}
  762. cellTypes := []CellType{}
  763. for _, cell := range row.Cells {
  764. str, err := cell.FormattedValue()
  765. if err != nil {
  766. t.Fatal(err)
  767. }
  768. data = append(data, str)
  769. cellTypes = append(cellTypes, cell.Type())
  770. }
  771. sheetData = append(sheetData, data)
  772. sheetCellTypes = append(sheetCellTypes, cellTypes)
  773. }
  774. sheetNames = append(sheetNames, sheet.Name)
  775. actualWorkbookData = append(actualWorkbookData, sheetData)
  776. workbookCellTypes = append(workbookCellTypes, sheetCellTypes)
  777. }
  778. return sheetNames, actualWorkbookData, workbookCellTypes
  779. }
  780. func (s *StreamSuite) TestAddSheetErrorsAfterBuild(t *C) {
  781. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  782. err := file.AddSheet("Sheet1", []string{"Header"}, nil)
  783. if err != nil {
  784. t.Fatal(err)
  785. }
  786. err = file.AddSheet("Sheet2", []string{"Header2"}, nil)
  787. if err != nil {
  788. t.Fatal(err)
  789. }
  790. _, err = file.Build()
  791. if err != nil {
  792. t.Fatal(err)
  793. }
  794. err = file.AddSheet("Sheet3", []string{"Header3"}, nil)
  795. if err != BuiltStreamFileBuilderError {
  796. t.Fatal(err)
  797. }
  798. }
  799. func (s *StreamSuite) TestBuildErrorsAfterBuild(t *C) {
  800. file := NewStreamFileBuilder(bytes.NewBuffer(nil))
  801. err := file.AddSheet("Sheet1", []string{"Header"}, nil)
  802. if err != nil {
  803. t.Fatal(err)
  804. }
  805. err = file.AddSheet("Sheet2", []string{"Header2"}, nil)
  806. if err != nil {
  807. t.Fatal(err)
  808. }
  809. _, err = file.Build()
  810. if err != nil {
  811. t.Fatal(err)
  812. }
  813. _, err = file.Build()
  814. if err != BuiltStreamFileBuilderError {
  815. t.Fatal(err)
  816. }
  817. }
  818. func (s *StreamSuite) TestCloseWithNothingWrittenToSheets(t *C) {
  819. buffer := bytes.NewBuffer(nil)
  820. file := NewStreamFileBuilder(buffer)
  821. sheetNames := []string{"Sheet1", "Sheet2"}
  822. workbookData := [][][]string{
  823. {{"Header1", "Header2"}},
  824. {{"Header3", "Header4"}},
  825. }
  826. err := file.AddSheet(sheetNames[0], workbookData[0][0], nil)
  827. if err != nil {
  828. t.Fatal(err)
  829. }
  830. err = file.AddSheet(sheetNames[1], workbookData[1][0], nil)
  831. if err != nil {
  832. t.Fatal(err)
  833. }
  834. stream, err := file.Build()
  835. if err != nil {
  836. t.Fatal(err)
  837. }
  838. err = stream.Close()
  839. if err != nil {
  840. t.Fatal(err)
  841. }
  842. bufReader := bytes.NewReader(buffer.Bytes())
  843. size := bufReader.Size()
  844. actualSheetNames, actualWorkbookData, _ := readXLSXFile(t, "", bufReader, size, false)
  845. // check if data was able to be read correctly
  846. if !reflect.DeepEqual(actualSheetNames, sheetNames) {
  847. t.Fatal("Expected sheet names to be equal")
  848. }
  849. if !reflect.DeepEqual(actualWorkbookData, workbookData) {
  850. t.Fatal("Expected workbook data to be equal")
  851. }
  852. }