ReactJS - How to skip empty rows in excel while reading with xlsx - javascript

I'm successfully reading my Excel file in React by following this SO thread as.
var reader = new FileReader();
reader.onload = function (e) {
var data = e.target.result;
let readedData = XLSX.read(data, {type: 'binary'});
const wsname = readedData.SheetNames[0];
const ws = readedData.Sheets[wsname];
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {header:1});
console.log(parsedData);
}
reader.readAsBinaryString(fileName)
But having a simple problem, i.e., it's reading empty rows as well and causing empty entries in array.
Output of console.log(parsedData); in the above code is
I know a quick hack is to remove empty entries from the array but I want to know a better approach to avoid this problem even happening.

Edit - It's "blankrows" and not "blankRows"
I did a search and came across a similar question on gitmemory here, which shows that there's a blankRows property you can set to false in order to skip blank rows, which would look like this with your implementation:
/* Converts a worksheet object to an array of JSON objects*/
const parsedData = XLSX.utils.sheet_to_json(ws, {
header:1,
blankrows: false
});

Related

Can't read cell values of XLSX generated using SheetJs

I wrote a JS code where I imported SheetJS and js-xlsx to perform actions on XLSX files (I can't use nodeJs nor npm, bower or any other solution that requires any installation on final user computer).
Shortly, the code has to do the following:
gets data that will be added to excel from user;
imports the excel the user wants to edit;
use a function to determine in which row data has to be added;
save and download a new file with updated data
The problem with the code I wrote is that it works just fine with Excels written, in fact, via Excel, but crashes if a user imports an XLSX that was previously generated and downloaded by my code.
Here's a snippet of the code:
// user choose the source excel
$('#xlf').change(function(e) {
var reader = new FileReader();
reader.readAsArrayBuffer(e.target.files[0]);
reader.onload = function(e) {
var data = new Uint8Array(reader.result);
var wb = XLSX.read(data, {
type: 'array',
cellDates: true,
cellStyles: true,
sheetStubs: true,
raw: true
});
var fSN = wb.SheetNames[0];
var ws = wb.Sheets[fSN];
function findEmpty() {
// this function check all the values in a specific range of cells (C9:C25)
// In order to do so, I included them into an array where I stored the value of the cells;
// later I loop the array and add 1 to the counter *dataSize* anytime I found a value > 0
var dataRange = [ws["C9"].v, ws["C10"].v, ws["C11"].v, , ws["C12"].v, ws["C13"].v, ws["C14"].v, ws["C15"].v, ws["C16"].v, ws["C17"].v, ws["C18"].v, ws["C19"].v, ws["C20"].v, ws["C21"].v, ws["C22"].v, ws["C23"].v, ws["C24"].v, ws["C25"].v];
var dataSize = 0;
var row;
for (i = 0; i < dataRange.length; i++) {
if (dataRange[i] > 0)
dataSize++;
}
row = 8 + dataSize; // 8 is the row of C9 (0 index-based)
return row;
}
var firstEmpty = findEmpty();
var header = ["a", "b", "c", "d", "e", "f"];
//origin is firstEmpty
XLSX.utils.sheet_add_json(ws, [{
a: $('#from').val(),
b: $('#to').val(),
c: $("#differenza").val(),
e: $("#comm").val()
}], {
header: header,
origin: firstEmpty,
skipHeader: true
});
// save file
XLSX.writeFile(wb, "test.xlsx");
}
});
If I try storing in dataRange the cells without the value (.v):
var dataRange = [ws["C9"], ws["C10"], ws["C11"], ws["C12"], ws["C13"], ws["C14"], ws["C15"], ws["C16"], ws["C17"], ws["C18"], ws["C19"], ws["C20"], ws["C21"], ws["C22"], ws["C23"], ws["C24"], ws["C25"]];
it won't crash with neither Excel generated files nor this-code-generated files, however the function findEmpty() will not work as intended (dataSize will be 0, no matter what's inside the cells).
Looks like my code can't write proper cell objects.
My guess is that there's something I should fix with the way I'm saving the file, but after several research and attempts I couldn't figure out a way to fix this - do you have a clue?
Thanks to all
Just in case this could help anyone, I solved my problem changing the IF condition within the FOR loop like this:
if((dataRange[i] !== undefined) && (dataRange[i].v > 0))
dataSize++;
Also, I'm using the dataRange array where I did not pass the .v property
(dataRange = [ws["C9"], ws["C10"], ... , ...])
After few attempts I found my code was not able to read within the .v of a cell of a file it generates, still it write and passes the whole cell object to it

Remove rows having blank value for some column from CSV file using Node JS

I have a CSV file where for a row some value is missing. So if a value is missing then we need to delete that row from the CSV file. I am facing a problem with doing that. Please help me with this.
We can use a CSV parsing library, such as the excellent Papa Parse to parse the data, then we can filter the rows based on the column that we wish to filter on.
For example:
const Papa = require('papaparse');
let csvData = `Col1,Col2,Col3\na1,b1,c1\na2,,c2\na3,b3,c3`;
let { data } = Papa.parse(csvData, { header: true });
console.log("Original csv data:");
console.log(csvData);
function filterEmptyValues(data, column) {
return data.filter(row => row[column]);
}
let filteredData = filterEmptyValues(data, "Col2");
let filteredCsv = Papa.unparse(filteredData);
console.log("\nFiltered csv:")
console.log(filteredCsv);

How can I overwrite my xlsx sheet data with new data in node js

Below is my code
Ws-Contains redundant data while
wsRemDup-contains data after removing the redundant/duplicate data.
wsRemDup is an array of JSON.
I want to overwrite my ws sheets data with wsRemDup.
I googled to find a way but most of the stuff showed how to append instead of overwriting it.
How can I proceed?
ws = XLSX.utils.sheet_add_json(ws, ticketNameArr,{origin:-1, skipHeader:true});
//Contains unique ticket name and their other fields
wsRemDup=removeDuplicate(ws)
console.log(wsRemDup)
XLSX.writeFile(wb, 'DailyTicketSatus.xlsx')
respond.render('index', { "ticketNameArr": ticketNameArr });
You should be able to overwrite the sheet on your original workbook like so:
const excelFile = "tickets.xlsx";
const sheetName = "Sheet1" // <-- Change to the actual sheet name.
const workbook = XLSX.readFile(excelFile);
const ws = workbook.Sheets[sheetName];
let sheetJson = removeDuplicate(ws);
// Overwrite worksheet
workbook.Sheets[sheetName] = XLSX.utils.json_to_sheet(sheetJson);
XLSX.writeFile(workbook, excelFile);

Filter data from bulk csv to small csv

I have one raw sheet and that needs to be divided into certain templates.From the raw sheet(raw_data), I have one more sheet (man_data) in which whole data is present.I need to check the manufacturer(column E from raw_data) to be checked with (column C from man_data). If data is not present in the man_data then i need that data to be written in new template(manufacturer_template in column C(name)).
Please find below the template format of the sheet.
How can we write a program in a simple javascript code.I am very new at this and learning javascript now so kindly help me out in writing the code.
Thanks.
Kindly let me know if you need any help regarding question description.
Please find attached files on below onedrive link.
https://1drv.ms/f/s!Asot5b-vLh9Qhlvu9HuMtlKMSmdV
You can read data using javascript.
then apply filter method of javascript to get filtered result...
var data = [1,2,3,4,5];
data.filter(function(obj){ return obj>2 })
Likewise above code return numbers greater than 2
You can write any logic in '{ }' of function
HTML Code to accept csv file:
<input type="file" id="cvsFileChooser" accept=".csv" />
JavaScript code for reading and processing csv file
$('#cvsFileChooser').change(function() {
var output = "";
var csvInputFilesName = $('#cvsFileChooser').prop("files");
var file = csvInputFilesName[0];
var reader = new FileReader();
reader.onload = function(e) {
output = e.target.result;
displayContents(output);
};
reader.readAsText(file);
reader.onerror = function() {
alert('Unable to read ' + file.fileName);
};
}
});
function displayContents(txt) {
var rows = txt.split('\n')// this will give each row array saperate from csv data
for(i=0;i<row.length;i++){ // iteration upto the end of all rows
var singleRow = rows[i]; // get each row
var columnArray = singleRow.split(','); // get column array data for each row
if(columnArray[ your excel column number to check data ] !="")
{
// your logic to copy data in new array
}
}
}

Associative array dynamic key addition error

I am converting a CSV to JSON object to render data in a html table. When creating object I am using associative array to create a key,value pair structure of the object, but last column of the CSV file is becoming inaccessible because it is creating object as follows,
Object {code:"F1",description:"Family 1",discount: "0.2","validity":"1434567098"}
So I can't access data for "validity" in my code. It is only happening with the last column of CSV file. Please help me to resolve this issue.
Please refer to this block of code,
reader.onload = function(e) {
var fileData = e.target.result.split("\n"),
tableData = [],
tData = {},
length = fileData.length;
for(i=0;i<length;i++){
csvObj.push(fileData[i]);
}
theaderArray = csvObj[0].toLowerCase().split(",");
for(k=1;k<csvObj.length;k++){
tData = {};
csvDataArray = csvObj[k].split(",");
if(csvDataArray[0]){
angular.forEach(theaderArray, function(val,key){
tData[val] = csvDataArray[key];
});
}
tableData.push(tData);
}
$rootScope.familyList = tableData;
}

Categories

Resources