sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

Unable to parse file, if first header cell starts with '<' symbol

Open GienekGenin opened this issue 8 years ago • 3 comments

  1. CSV file content:

untitled

  1. Code
// const workbook = XLSX.readFile(path);
const parseHeaders = workbook => {
	const sheet = workbook.Sheets[workbook.SheetNames[0]];
	const range = XLSX.utils.decode_range(sheet['!ref']);
	let headers = [];
	let C;
	const R = range.s.r;
	/* start in the first row */
	/* walk every column in the range */
	let countBreak = 0;
	let buffer = [];
	for (C = range.s.c; C <= range.e.c; C += 1) {
		const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
		let hdr = 'UNKNOWN'; // <-- replace with your desired default
		if (!cell || cell.v === '' || cell.v === ' ') {
			countBreak += 1;
			/* if 3 cell in a row undefined - break */
			if (countBreak === 3) {
				return renameFiles(headers);
			}
			buffer.push(hdr);
		}
		/* find the cell in the first row */
		if (cell && cell.t && cell.v !== '' && cell.v !== ' ') {
			countBreak = 0;
			hdr = XLSX.utils.format_cell(cell);
			if (buffer.length >= 1) {
				headers = headers.concat(buffer);
			}
			buffer = [];
			headers.push(hdr);
		}
	}
	return renameFiles(headers);
};
  1. Error: UnhandledPromiseRejectionWarning: TypeError: Cannot read property '!ref' of undefined
workbook.Sheets // { }
workbook.SheetNames // [ ]
  1. Without this < works just fine

untitled 1 Thanks for your work. This library is truly awesome.

GienekGenin avatar Aug 25 '18 09:08 GienekGenin

When the file starts with < the library currently guesses that the file is either HTML or Flat ODS or SpreadsheetML 2003).

If you have access to Excel, try saving the contents of that file to test.csv and test.xls

<Title,New Title.
text,some text

Excel's interpretation is unexpected!

CSV (as you would expect)

screen shot 2018-08-25 at 6 41 03 am

XLS (surprising)

screen shot 2018-08-25 at 6 41 21 am

It's even more amusing if you put an actual HTML tag in there, like <table>,New Title. (blank file)

The current behavior is clearly incorrect, but what is the correct behavior?

SheetJSDev avatar Aug 25 '18 10:08 SheetJSDev

I would expect to get string '<Title' header.

I use parseHeaders function to get headers from CSV and Excel files wich user can parse from file or link, and subsequently form a payload wich you can see above, but apparently if first header's cell contains symbol < or any <tag>, the XLSX.readFile(path) function can't properly create workbook object.

What can You advise on this?

GienekGenin avatar Aug 25 '18 14:08 GienekGenin

Ran into this problem, too.

aaronArinder avatar Apr 15 '19 14:04 aaronArinder