sheetjs icon indicating copy to clipboard operation
sheetjs copied to clipboard

sheet_to_json skips empty rows

Open tamlyn opened this issue 12 years ago • 44 comments

When calling xlsx.utils.sheet_to_json(sheet, {header: 1}) I would expect to receive an array of arrays including empty rows. However the function explicitly skips out empty rows which makes it impossible to select a particular row in the results. It would be good to make this behaviour configurable.

As a workaround, I have used sheet_to_csv, which doesn't skip rows, followed by csv-parse.

tamlyn avatar Oct 28 '14 10:10 tamlyn

@tamlyn excellent catch! Fortunately this is an easy fix: in the loop, the empty check should also consider the header. https://github.com/SheetJS/js-xlsx/blob/master/bits/90_utils.js#L119 can be rewritten as:

if(isempty === false || header === 1) out[outi++] = row;

This is important enough to merit a new push later today with the fix.

SheetJSDev avatar Oct 28 '14 20:10 SheetJSDev

sheet_to_json still not include empty cells

komuville avatar Nov 12 '14 11:11 komuville

Hi, first of all thx for this awesome tool. Now then, in the version bump 0.7.2 only includes the fix for xls empty cells, but im using an xlsx and still have problems with the empty cells.

Kevzz avatar Dec 05 '14 17:12 Kevzz

Also experiencing the same issue as Kevzz. Any updates?

jeffgunderson avatar Apr 10 '15 23:04 jeffgunderson

Can also confirm I'm having this issue. Empty cells in xlsx files don't convert properly. Instead of leaving the value of that column as '', it just doesn't include that key at all.

rdmurphy avatar Apr 15 '15 17:04 rdmurphy

Same issue here

marcioaguiar avatar Jun 23 '15 17:06 marcioaguiar

eagerly awaiting for an update here :)

simonbergstrom avatar Jul 17 '15 13:07 simonbergstrom

+1

require support for empty cell.

shenlong avatar Jul 20 '15 09:07 shenlong

Hmmm, too bad, thought this would save my day :( But the empty cells bug is still even in 0.8.0 The only way to convert also empty cells, is to save the xlsx table as xls. Unfortunatley not an option for me since this destroys my table.

Extano avatar Jul 23 '15 18:07 Extano

Yeah. For me, I go thru the each row and each header to check for undefined values and put '' for empty field.

 workbook.SheetNames.forEach(function (sheetName) {
                // Get headers.
                var headers = [];
                var sheet = workbook.Sheets[sheetName];
                var range = XLSX.utils.decode_range(sheet['!ref']);
                var C, R = range.s.r;
                /* start in the first row */
                /* walk every column in the range */
                for (C = range.s.c; C <= range.e.c; ++C) {
                    var cell = sheet[XLSX.utils.encode_cell({c: C, r: R})];
                    /* find the cell in the first row */

                    var hdr = "UNKNOWN " + C; // <-- replace with your desired default
                    if (cell && cell.t) {
                        hdr = XLSX.utils.format_cell(cell);
                    }
                    headers.push(hdr);
                }
                // For each sheets, convert to json.
                var roa = X.utils.sheet_to_json(workbook.Sheets[sheetName]);
                if (roa.length > 0) {
                    roa.forEach(function (row) {
                        // Set empty cell to ''.
                        headers.forEach(function (hd) {
                            if (row[hd] == undefined) {
                                row[hd] = '';
                            }
                        });
                    });
                }
            });

shenlong avatar Jul 24 '15 09:07 shenlong

+1 the key should be included in the json objects with an empty string or null.

(Awesome tool nontheless)

codeofsumit avatar Nov 26 '15 17:11 codeofsumit

@SheetJSDev Hi, any update when this will be fixed? I am still seeing this issue.

BTW great library!

abartolo avatar Aug 02 '16 20:08 abartolo

@abartolo Go to xlsx.js file, find sheet_to_json function and change it like as this:

function sheet_to_json(sheet, opts){
	var val, row, range, header = 0, offset = 1, r, hdr = [], isempty, R, C, v;
	var o = opts != null ? opts : {};
	var raw = o.raw;
	if(sheet == null || sheet["!ref"] == null) return [];
	range = o.range !== undefined ? o.range : sheet["!ref"];
	if(o.header === 1) header = 1;
	else if(o.header === "A") header = 2;
	else if(Array.isArray(o.header)) header = 3;
	switch(typeof range) {
		case 'string': r = safe_decode_range(range); break;
		case 'number': r = safe_decode_range(sheet["!ref"]); r.s.r = range; break;
		default: r = range;
	}
	if(header > 0) offset = 0;
	var rr = encode_row(r.s.r);
	var cols = new Array(r.e.c-r.s.c+1);
	var out = new Array(r.e.r-r.s.r-offset+1);
	var outi = 0;
	for(C = r.s.c; C <= r.e.c; ++C) {
		cols[C] = encode_col(C);
		val = sheet[cols[C] + rr];
		switch(header) {
			case 1: hdr[C] = C; break;
			case 2: hdr[C] = cols[C]; break;
			case 3: hdr[C] = o.header[C - r.s.c]; break;
			default:
				if(val === undefined) continue;
				hdr[C] = format_cell(val);
		}
	}
	for (R = r.s.r + offset; R <= r.e.r; ++R) {
		rr = encode_row(R);
		isempty = true;
		if(header === 1) row = [];
		else {
			row = {};
			if(Object.defineProperty) Object.defineProperty(row, '__rowNum__', {value:R, enumerable:false});
			else row.__rowNum__ = R;
		}
		for (C = r.s.c; C <= r.e.c; ++C) {
			val = sheet[cols[C] + rr];
			if(val === undefined || val.t === undefined) {val = {t: "s", v: null, w: ""};}
			v = val.v;
			switch(val.t){
				case 'e': continue;
				case 's': break;
				case 'b': case 'n': break;
				default: throw 'unrecognized type ' + val.t;
			}
			if(v !== undefined) {
				row[hdr[C]] = raw ? v : format_cell(val,v);
				isempty = false;
			}
		}
		if(isempty === false || header === 1) out[outi++] = row;
		
	}
	out.length = outi;
	return out;
}

In summary this part has to be changed:

if(val === undefined || val.t === undefined) {val = {t: "s", v: null, w: ""};}

mjza avatar Nov 30 '16 12:11 mjza

@mjza that has no change for me. Still the empty fields are inexistant and imposible to detect.

muscaiu avatar Feb 17 '17 13:02 muscaiu

+1

VectorM avatar Feb 18 '17 11:02 VectorM

@mjza Thanks , It is work

ttting avatar Feb 18 '17 16:02 ttting

Any updates on this matter?

rashthedude avatar Mar 13 '17 11:03 rashthedude

I think this was resolved a long time ago, in version 0.8.0 the fix from https://github.com/SheetJS/js-xlsx/issues/139#issuecomment-60823125 was applied. I just tested a file and see blank arrays generated when the option {header:1} is set.

As far as I can tell the crux of the matter (including empty rows) has been resolved. If anyone can share a sample file with expected output I'll reopen the issue.

SheetJSDev avatar Mar 23 '17 06:03 SheetJSDev

sheet_to_json() with header option true yields empty column headers perfectly, But there is a bug and it won't echo null for last empty column data. In attached screenshot, there are 11 header items. 2nd column is empty and it's coming null as expected. But it's not echoing null for 11th column which is last one.

image

vins13pattar avatar Mar 24 '17 09:03 vins13pattar

@vins13pattar do you have a file you can share? It should not be generating null in the first place -- those should be array holes (undefined)

I made a sample file to check what's going on: t139.xlsx

And this is what I see in node:

> XLSX.version
'0.9.5'
> XLSX.utils.sheet_to_json(XLSX.readFile('t139.xlsx').Sheets.Sheet1, {header:1})
[ [ 'id',
    'id-job',
    'type',
    'name',
    'address',
    'latitude',
    'longitude',
    'service-duration',
    'start-time',
    'end-time',
    'quantity',
    'required-skills' ],
  [ 'Stop1', , , , , , , , , , '206' ] ]

SheetJSDev avatar Mar 24 '17 12:03 SheetJSDev