Convert an excel xlsx file with nested headers into json - javascript

I am converting my excel file to json using the below library and it works fine when I have one header row and the remaining rows are data.
var excelToJson = require('convert-excel-to-json');
var result = excelToJson({
sourceFile: 'Auto.xlsx',
header: {
rows: 2 //Used 2 to skip the first line of headers
},
columnToKey: {
'*': '{{columnHeader}}'
}
});
But I have a file that has nested rows as headers similar to below and want to convert that into json.
Something like this, with multiple sheets
Appreciate any help or pointers. Thanks!

Related

Excel to Json File And Json to Excel In Specific Manner Using Javascript

I have a Json Which look like
{
"2001":{
"abc":2000,
"bcd":2005
},
"2002":{
"abc":3000,
"bcd":3500
}
}
I want a specific way that converts this Json to excel file.
And When that excel file is again converted to Json it should give me above styled json again. Is there any way that I can convert this Json to excel and Excel to Json, but I won't want to change syntex of Json.While the Excel should also show every detail in Json have.
This line fetch data from excel sheet:
var rowMajor = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], { raw: true, header: 1 });
I am thinking to fetch name of the sheet where the year is been set, and set it as a key to them by local concatenation. Multiple sheet has multiple data which would enclose as seen above in the question. But while reversing the thing 'Json to excel' I am not getting any idea how to do it by code, while the idea to do it is clear.
you can simply use xlsx library
https://www.npmjs.com/package/xlsx
Ex: XLSX.write(wb, {Props:{Author:"SheetJS"}});
wb: is your data.
and inside {} is your file name(SheetJS name of your file).

Unable to write data (addRow) into Excel file in Nodejs

I'm trying to write data into an Excel file using ExcelJS library. I was successfully able to create worksheet and add column data.
However, while trying to implement addRow() or addRows() method, the data is not added into the Excel worksheet.
Here is the code I tried:
const ExcelJS = require('exceljs');
var workbook = new ExcelJS.Workbook();
var worksheet = workbook.addWorksheet('Payment Data');
worksheet.columns = reportHeaders; //reportHeaders is an array of header objects
I'm able to see the columns created successfully in the excel sheet. The trouble starts from below, where I'm trying to add data (into rows):
1st method :
worksheet.addRows(excelData);//excelData is an array of data objects
2nd method:
for(var rowItem in excelData){
worksheet.addRow(excelData[rowItem]);}
However, it seems either of these methods aren't working for me.
Finally, the file is saved:
workbook.xlsx.writeFile('PaymentData.xlsx')
Is there anything I'm missing? Any help will be appreciated.
So the issue with your code was, you were trying to add the data to the columns without specifying the key property in the columns array and hence it was unable to add the data.
I modified the worksheet.columns array to look something like the following:
worksheet.columns = [
{ header: "A", key: "a" },
{ header: "B", key: "b" },
];
This will solve your problem
I managed to convert the object to an array and passed it to the addRow method.
This worked for me.
I'm still not sure why I'm not able to pass an array of objects to addRow method.

Make a data table using exceljs

I'm trying to format some data into a Excel table, I already have the data written in the Excel file, but I want it as a table, is there any way to do this, if not, is there any way with another npm package
You could convert the range to table:
const sheet = context.workbook.worksheets.getItem("Sample");
let expensesTable = sheet.tables.add("A1:E7", true);
expensesTable.name = "ExpensesTable";
here is the sample gist that you could have a try
https://gist.github.com/lumine2008/8eccb88f7fccf34b63c7ecd5fd05aaea

Parsing CSV file in vue/typescript

I am reading in a csv file and i am in the process of parsing through it but having some trouble.
1 - Before parsing the file i already have an array with strings of headers that i want to pull the data for from the csv file.
2- I want to parse the file so i can also display the data into a table with my predefined headers. And any extra headers they will be ignored from being displayed in the table.
Here is my code:
this.predefinedHeaders = ["Name", "Age", "Gender"];
readCSV(event: Event) {
const file = (event.target as HTMLInputElement).files![0];
var reader = new FileReader();
let text = (reader.result as string).split(/\r\n|\r|\n/);
let lines = [];
for( var i=1; i<text.length; i++) {
var data = text[i].split(',');
var tarr=[];
for(var j=0; j<this.predefinedHeaders.length; j++) {
tarr.push(data[j]);
}
lines.push(tarr);
}
this.tableData = lines;
}
reader.readAsText(file);
What is currently happening is that data is being populated to the table but not under the right headers.. How can i bind the data to my headers... NOTE: the predefined are guaranteed to be part of the original headers from the file. the difference is that it doesn't show data for all the columns such several of them.
HTML View:
table
thead
tr
th(v-for='column in predefinedColumns) {{column.name}}
tbody
tr(v-for='(a, index)in data')
td(v-for='(b, index2) in a') {{data[index][index2]}}
You might want to use most popular CSV parser which is PapaParse.
URLs for the deep documentation:
https://www.papaparse.com/demo
this library has various configuration options and one of them is 'Header row' which is exact solution you need.
to use the predefined header you can supply header argument as true to have all the data parsed as key-value pairs.
example: { data: Papa.parse(reader.result, { header: true }) }
with 'header: true', it will take first row of CSV file as key value for all the row in CSV file
NPM package for easiest implementation in javaScript app:
https://www.npmjs.com/package/papaparse
If you want to have the predefined headers and display only the table with only needed columns.
checkout this one of my example on codesandbox,
https://codesandbox.io/embed/llqmrp96pm
sample CSV file is already uploaded in the same directory so you would be able to upload it and see magic
this CSV file in there has 7 or 8 column but I am displaying only 4 columns, I assume that's what you are looking for
I see you are looking for JavaScript solution, my example is created with ReactJS and couple of NPM libraries but it is almost same as you are looking for, I believe it would be easier than anything to replicate in your code.

Reading the headers of a CSV file using angularjs

My CSV file consists of headers namely (DateTime,Samplevalue and hostname).
And
I want to read these headers and for instance, if the csv file consists of DateTime as it's header I want to print ( this is suitable for timeseries database)
How to achieve this using angularjs ?
How to code this ?
For instance, my CSV looks like
Hostname,Samplevalue,DateTime
Host1,1,2018-05-04 31:21:11
Host2,1,2018-05-05 21:15:10
Host3,1,2018-05-04 11:11:13
Host4,1,2018-05-06 41:21:15
Need to just read any one of the header and print something like
Console.log(datetime header is suitable fr this database)
Thanks in advance.
You can use $http and 1) split the returned string by line breaks 2)
split the first line by commas :
$http.get('path/to/csv/').then(function(csv) {
var headers = csv.data.split('\n')[0].split(',')
headers.forEach(function(header, index) {
console.log('header #'+index, header)
})
})
Do you mean you wish to read the CSV data?
If yes, the best way to deal with CSV files in JavaScript is to convert it into JSON data.
Check out https://github.com/evanplaice/jquery-csv, its a simple library where you can pass your CSV data and get JSON in return. Hope it helps!

Categories

Resources