Unable to DATE VALUE using XLSX Library Javascript - javascript

I need to separate all the headers of Excel sheet. code that i implemented is working but only text format is working. kindly help.
const xlsx = require('xlsx');
const workbook = xlsx.readFile('./SMALL.xlsx');
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
const workbookHeaders = xlsx.readFile('./SMALL.xlsx', { sheetRows: 1 });
const columnsArray = xlsx.utils.sheet_to_json(workbookHeaders.Sheets[workbook.SheetNames[0]], { header: 1 })[0];
console.log(columnsArray);
Response
My console should print ['Task', '1/2022', '2/2022' ]. instead its printing
[ 'Task', 44562, 44593 ]

Looks like you can specify a date format string in the options parameter to the sheet_to_json(worksheet, opts) method.
The option property name appears to be: dateNF
https://www.npmjs.com/package/xlsx#parsing-options

Related

Google Sheets API - Import all named Ranges

I have a google sheet with several named ranges.
I would like to import every single named range in the sheet and save them as individual objects named after the named range.
Furthermore, there are 4 similar blocks of data. Therefore the names of the ranges are structured like "block1_name1" "block1_name2" "block2_name1" "block2_name2" etc.
With the following code I can enter every range manually, but there are too many to enter them all manually:
const API_KEY = "###"; // Please set your API key.
const ID = "###"; // Please set your Spreadsheet ID.
const RANGE = ["Range1", "Range2"]; // Named ranges
const ranges = RANGE.map(e => `ranges=${encodeURIComponent(e)}`).join("&");
const response = await fetch(`https://sheets.googleapis.com/v4/spreadsheets/${ID}/values:batchGet?key=${API_KEY}&${ranges}`);
const { valueRanges } = await response.json();
const obj = valueRanges.reduce((o, { values }, i) => (o[RANGE[i]] = values, o), {});
console.log(obj);
How can I import every named range automatically?
How can I save them as a different objects for each datablock like block1.name1 etc?
I believe your goal is as follows.
You want to retrieve the named range list from Google Spreadsheet, and want to retrieve the values from the named ranges.
And, you want to export the values as {namedRange1: values1, namedRange2: values2,,,}.
You want to achieve this by directly requesting the endpoint of Sheets API with fetch API of Javascript.
In this case, how about the following modification?
Modified script:
const API_KEY = "###"; // Please set your API key.
const ID = "###"; // Please set your Spreadsheet ID.
// 1. Retrieve the named range list.
const base = `https:\/\/sheets.googleapis.com/v4/spreadsheets/${ID}`;
const res1 = await fetch(`${base}?key=${API_KEY}&fields=namedRanges(name)`);
const { namedRanges } = await res1.json();
// 2. Retrieve values from named ranges.
const ranges = namedRanges.map(({ name }) => `ranges=${encodeURIComponent(name)}`).join("&");
const res2 = await fetch(`${base}/values:batchGet?key=${API_KEY}&${ranges}`);
const { valueRanges } = await res2.json();
// 3. Create an output object.
const res = valueRanges.reduce((o, { values }, i) => (o[namedRanges[i].name] = values, o), {});
console.log(res);
// For your 2nd question.
const res3 = valueRanges.reduce((o, { values }, i) => {
const [k1, k2] = namedRanges[i].name.split("_");
if (o[k1]) {
o[k1][k2] = values;
} else {
o[k1] = { [k2]: values };
}
return o;
}, {});
console.log(res3);
Testing:
When this script is run, the following result can be seen at the console.
{
"block1_name2":[###values###],
"block2_name2":[###values###],
,
,
,
}
Note:
When you have a lot of named ranges, it is required to separate the request for retrieving the values, because of the limitation of the length of the URL. Please be careful about this.
About your 2nd question, when you want to convert from {"block1_name2":[###values###],,,} to {"block1": {"name2":[###values###]},,,}, as a premise, I think that it is required to decide the format of the name of the named ranges. In this case, from your showing sample named ranges, it supposes that your format of the name of all named ranges is like block#_name#. Please be careful about this.
References:
Method: spreadsheets.get
Method: spreadsheets.values.batchGet
You can use the Method: spreadsheets.get to list the ranges of a Google Spreadsheet. This is returned as an object.
{
"namedRangeId": "xxxxxxxxxxx",
"name": "test",
"range": {
"startRowIndex": 4,
"endRowIndex": 10,
"startColumnIndex": 0,
"endColumnIndex": 3
}
},
A simple sample using the method, and limiting the field for name ranges only:
function execute() {
return gapi.client.sheets.spreadsheets.get({
"spreadsheetId": "Google_Sheet_ID",
"fields": "namedRanges"
})
You can read more information about this method in the Google Documentation here
And there is a sample complete code on the same documentation. You can then use the name in "name": "test", to rename the objects.

filter and copy data from one spreadsheet to another while criteria is in different spreadsheet

I have two google sheets forst one is https://docs.google.com/spreadsheets/d/1PJtjlkxCDFOIhJxpMJl4PcpJKL4nvGVtk2LDgVhbuNQ/edit#gid=0
and the second is https://docs.google.com/spreadsheets/d/1ZGw6dHpYE4ABvsE8S6dIPe7kLQ1eZW95Xp2F1oPHX5c/edit#gid=0
I want to filer data in first sheet base on the criteria which presents in the second sheet "Automate!D3" and then copy the filtered data to second sheet in "Filtered_Data". and want to this process automate so in future when i add more data to sheet one so that can be copy to below data in sheet two.
i can not able to filter throw app script, so i want to help in this.
Something like this should work:
const dsid = "1PJtjlkxCDFOIhJxpMJl4PcpJKL4nvGVtk2LDgVhbuNQ";
const tssid = "1ZGw6dHpYE4ABvsE8S6dIPe7kLQ1eZW95Xp2F1oPHX5c"
function filterByDate() {
const values = SpreadsheetApp.openById(dsid).getSheetByName('DT').getDataRange().getValues();
const tss = SpreadsheetApp.openById(tssid);
const criteria = tss.getSheetByName('Automate').getRange('D3').getValue();
const ts = tss.getSheetByName('Filtered_Data');
const results = values
.filter(row => row[1].getDate == criteria.getDate)
.map(row => [row[1],row[2],row[3],row[4]]);
ts.getRange(2,1,results.length,results[0].length).setValues(results);
}
I would suggest to place the criteria value in the daily sheet, and install the function into daily sheet as an edit trigger.
Make sure that the 'criteria' and the 'date' column are both formatted as 'Date' format.
The follow code has changed the way to get values.
Insead of .getValues(), it now uses .getDisplayValues(), and convert the string back into date obj afterwards.
const dsid = "1PJtjlkxCDFOIhJxpMJl4PcpJKL4nvGVtk2LDgVhbuNQ";
const tssid = "1ZGw6dHpYE4ABvsE8S6dIPe7kLQ1eZW95Xp2F1oPHX5c";
function filterByDate() {
const values = SpreadsheetApp.openById(dsid).getSheetByName('DT').getDataRange().getDisplayValues();
const tss = SpreadsheetApp.openById(tssid);
const criteria = tss.getSheetByName('Automate').getRange('D3').getDisplayValues();
const ts = tss.getSheetByName('Filtered_Data');
const results = values
.filter(row => new Date(row[1]).setHours(0,0,0,0) == new Date(criteria).setHours(0,0,0,0))
.map(row => [row[1],row[2],row[3],row[4]]);
ts.getRange(2,1,results.length,results[0].length).setValues(results);
}

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 do I append XLSX data to existing worksheet using SheetJS?

I am currently using NodeJS and the library SheetsJS to read an XLSX workbook.
My task is to take data from multiple sheets and append them to a new worksheet. The structure of the sheet has the Categories in Column A and Category Values in Column B.
*Things I've Tried *
I have tried 2 things that have presented 2 different issues:
1.) I've tried using the builtin function sheet_to_json to format my xlsx data into JSON but it makes the header the key for every object. I've used the option skipHeader: true to negate this but if A1 is the header, A2 is the next value that gets repeated as the object.
Below is a code snippet:
let readFiletoJSON = filename => {
//wb = workbook
let wb = xlsx.readFile(filename, {cellDates: true});
let ws = wb.Sheets["1-Header"]
let currentRange = { s: { c: 0, r: 1 }, e: { c: 1, r: 10 } }
let encodedRange = xlsx.utils.encode_range(currentRange)
let sheetData = []
sheetData.push(
xlsx.utils.sheet_to_json(ws, {range: encodedRange}, {skipHeader: true})
)
console.log(sheetData)
2.) I have also tried creating my own array of objects with Column A as the key and Column B as the value however, I have trouble figuring out how to read the object into the new worksheet. How can I read the values into the new sheet?
I hope this is clear enough. Thank you in advance.

Add a new record to an existing records contained excel file in excel js( already the excel contains some value now trying to insert a new record )

1 -I want to add a new record inside the excel which is already contains some value
2 - Is there any way to use excel as the database for our project
so that client can use the excel effieciently
//script file.js
var Excel = require('exceljs');
var workbook = new Excel.Workbook();
//calling 2 function (writeFile() and writeFile1() )
writeFile();
writeFile1();
// this function should add/ create the record in excel file
function writeFile(){
var worksheet = workbook.addWorksheet('sheet1');
worksheet.columns =[
{header:"Id",key:"id",width:10},
{header:'Type',key:'type',width:15},
{header:'Assigned Engineer',key:'eng',width:25},
{header:'Due Date',key:'ddate',width:18},
{header:'Client Name',key:'cname',width:20},
{header:'person Name',key:'pname',width:20},
{header:'enquiry type',key:'etype',width:18},
{header:'acknowledge',key:'ack',width:20}
]
Worksheet.addRow({id:16,type:"Trading1221",eng:"Dhanasekar122",ddate:new
Date(),cname:"Ford22",pname:"sekar22",etype:"pipeling2",ack:"Y2"})
worksheet.addRow({id:71,type:"Trading3221",eng:"Dhanasekar322",ddate:new
Date(),cname:"Ford32",pname:"sekar32",etype:"pipeling3",ack:"Y3"})
workbook.xlsx.writeFile('file2.xlsx').then(function(){
})
}
//similary this below function should also add the record inside the
// excel
function writeFile1(){
var worksheet = workbook.addWorksheet('sheet1');
worksheet.columns =[
{header:"Id",key:"id",width:10},
{header:'Type',key:'type',width:15},
{header:'Assigned Engineer',key:'eng',width:25},
{header:'Due Date',key:'ddate',width:18},
{header:'Client Name',key:'cname',width:20},
{header:'person Name',key:'pname',width:20},
{header:'enquiry type',key:'etype',width:18},
{header:'acknowledge',key:'ack',width:20}
]
Worksheet.addRow({id:11,type:"Trading1221",eng:"Dhana11sekar122",ddate:new
Date(),cname:"Fo12",pname:"sekar122",etype:"pi1peling2",ack:"Y2"})
worksheet.addRow({id:171,type:"Trading31221",eng:"Dhanasekar11322",ddate:new
Date(),cname:"For1d32",pname:"sek1ar32",etype:"pipelin1g3",ack:"Y13"})
workbook.xlsx.writeFile('file2.xlsx').then(function(){
})
}
// what happening is value is overwriting and the excel has the last
inserted value
I had even tried in the second function of removing the columns but
still works the same and shows error on some time
excelJS requires an array of objects where each object points to row in excel , try doing this , this should solve your pblm
var rows = [{id:11,type:"Trading1221",eng:"Dhana11sekar122",ddate:new Date(),cname:"Fo12",pname:"sekar122",etype:"pi1peling2",ack:"Y2"},
{id:171,type:"Trading31221",eng:"Dhanasekar11322",ddate:new Date(),cname:"For1d32",pname:"sek1ar32",etype:"pipelin1g3",ack:"Y13"}];
worksheet.addRows(rows);
At last i found the solution to the above problem
//file1.js
var Excel = require('exceljs')
var workbook = new Excel.Workbook()
var arr=[]
workbook.xlsx.readFile('./file4.xlsx')
.then(function(){
var worksheet = workbook.getWorksheet(1)
var row =[
[ 55,"trading","sekar",new Date(2017-02-12),"ashok leyaland",arun",
"modeling","Y"],
[99,"training",new Date(2018-02-13),"tata motors","dhana","reference
name","wheldding","Y"]
]
worksheet.addRows(row)
return workbook.xlsx.writeFile('./file4.xlsx')
})
//
first you need to read the respective excel file and then you need to select the particular worksheet of the workbook(excel file) now you can readfile are write file using any of the form you can choose and update the value of the excel in the form of array or arrays
and return the output as file write function

Categories

Resources