How should I insert one more column in excel in javascript? - javascript

I have to put file sizes(need to capture from UI) near to file name(contained in excel) but was finding it difficult to insert such entry and so I created another sheet and class named FileProperties with filePath and fileSize. Then I had put the entries as JSON into new worksheet, then I want to delete the old sheet containing just the file names and want to rename the existing sheet so that it appears same. But when I used rename() and delete() on worksheet level I got an error and the work is more tedious then if I can write the file sizes near to file name in the old sheet.
FileProperties class
export class FileProperties {
filePath;
fileSize;
}
Below are the initialization and initially InputSheet is empty and Input_Data is holding File paths under File Path heading
inputWorksheet = workbook.Sheets.InputSheet;
oldInputSheet = workbook.Sheets.Input_Data;
const temp = XLSXReader.utils.sheet_to_json(oldInputSheet);
temp.forEach((res) => {
data.push(res);
});
Below is the code which I was trying to get the entries in new sheet which worked successfully.
allDataEle = await page.waitForSelector (
"locator passed here"
);
fileSize = await page.evaluate((el) => el.textContent.trim(), allDataEle);
//data is an object which refers to row of old sheet
fileProperties.filePath = data[i]['File Path'];
fileProperties.fileSize = fileSize;
fileProp = [fileProperties];
cell = 'A' + (i+2);
//inputWorksheet is referring to new sheet name
XLSXReader.utils.sheet_add_json(inputWorksheet, fileProp, {
skipHeader: true,
origin: cell
});
XLSXReader.writeFile(workbook, excelSheetName.xlsx');
I am getting proper data but want to write the file sizes in the old sheet and not getting another sheet for this.

Related

App Script new Google Sheet creation issue

I am trying to write an App Script that takes string data from multiple different spreadsheets (completely separate documents) and puts them all in a new spreadsheet. When I run the logger, it shows me all the data I want. I want each piece of data to show up in Column A, but when I run my script, it only puts 1 data point in the spreadsheet instead of all of them. Can someone give me some guidance? Here is my code:
function pullTogether() {
var files = DriveApp.getFolderById('Folder ID').searchFiles('title != "nothing"');
const rangeName = 'Sheet1!B2:C';
while(files.hasNext()){
var xFile = files.next();
var name = xFile.getId();
const values = Sheets.Spreadsheets.Values.get(name, rangeName).values;
for (const row in values) {
var a1 = (values[row][0]);
Logger.log(a1);
var ss = SpreadsheetApp.openById("ID of new spreadsheet"); //I have the real ID in my code
var cell = ss.getRange("A2");
cell.setValue(a1);
}
}
}
I believe your goal is as follows.
You want to retrieve the values from the column "B" of each Spreadsheet under the specific folder.
You want to put the retrieved values to the column "A" of the destination sheet.
Modification points:
About but when I run my script, it only puts 1 data point in the spreadsheet instead of all of them., when I saw your script, the retrieved value is always put to the cell "A2" of the destination sheet. I think that this might be the reason for your issue.
In your script, I thought that when the following flow is used, the process cost will become low. By this flow, your issue can be also removed.
In your situation, even when Sheets API is not used, the script might work using getValues().
When these points are reflected in your script, it becomes as follows.
Modified script:
Please set the folder ID and the destination Spreadsheet ID.
function pullTogether() {
// Retrieve values from each Spreadsheet.
var values = [];
var files = DriveApp.getFolderById('Folder ID').searchFiles(`title != 'nothing' and mimeType='${MimeType.GOOGLE_SHEETS}'`);
var sheetName = 'Sheet1'
while (files.hasNext()) {
var xFile = files.next();
var sheet = SpreadsheetApp.open(xFile).getSheetByName(sheetName);
if (sheet) {
var v = sheet.getRange("B2:B" + sheet.getLastRow()).getValues();
values = [...values, ...v];
}
}
// Put values to the destination sheet.
var ss = SpreadsheetApp.openById("ID of new spreadsheet"); //I have the real ID in my code
var dstSheet = ss.getSheets()[0];
dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
}
Note:
Although I'm not sure about your actual situation, when the above script didn't work by the large data, please modify as follows.
From
dstSheet.getRange(2, 1, values.length, values[0].length).setValues(values);
To
Sheets.Spreadsheets.Values.update({ values }, ss.getId(), `'${dstSheet.getSheetName()}'!A2`, { valueInputOption: "USER_ENTERED" });
References:
getValues()
setValues(values)

How can I leave a blank space/column inside an appended row?

I'm trying to leave a blank column in between data of an appended row, so that I can add a VLOOKUP function, functionally I don't need to do this (I could just add the VLOOKUP to the end of the row), but aesthetically it would be better if I could. Is there a way to just skip a column when appending data into a row?
Explanation:
You can use two separate setValues statements to achieve your goal and paste the data right after the last row with content with getLastRow().
I have fully described each block of lines in the following script so I think it is straightforward to work with it.
I tried to create a generic code where you can select:
the column you want to separate the data: sep_col
the starting column you want to paste the data: start_col
the number of columns you want to have between the two different datasets: space_col
Code snippet:
function myFunction() {
// get spreadsheet details
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1'); // change that to the name of your sheet
// provide some data
const sep_col = 3; // column you want to separate the data
const data = ["d1","d2","d3","d5","d6"];
const data1 = data.slice(0,sep_col);
const data2 = data.slice(sep_col,data.length);
// get current last row of document
const Lrow = sh.getLastRow();
// paste the data to separate ranges
const start_col = 1;
const space_col = 1;
sh.getRange(Lrow+1,start_col, 1, data1.length).setValues([data1]);
sh.getRange(Lrow+1,start_col+data1.length + space_col, 1, data2.length).setValues([data2]);
}
JavaScript References:
Array.prototype.slice()
Sheet used for the code snippet:

Google Script: How to display an image instead of hyperlink using a Document template

I have a G-Sheet with 3000 rows of data with links to images in one column. I am able to use body.replaceText to fill out a Google Doc template I have created. The issue is that it simply pulls the hyperlink.
Instead of displaying hyperlinks, how would you show the actual image?
Thank you for your time!
function newGoogleDoc() {
const googleDocTemplate = DriveApp.getFileById('XXXXX');
const destinationFolder = DriveApp.getFolderById('XXXXX')
const sheet = SpreadsheetApp
.getActiveSpreadsheet()
const rows = sheet.getDataRange().getValues();
rows.forEach(function(row, index){
if (index === 0) return;
if (row[15]) return;
const copy = googleDocTemplate.makeCopy(`${row[1]}, ${row[0]} Employee Details` , destinationFolder)
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();
const friendlyDate = new Date(row[12]).toLocaleDateString();
body.replaceText('{{Scope}}', row[0]);
body.replaceText('{{Block}}', row[1]);
body.replaceText('{{Line Item}}', row[2]);
body.replaceText('{{Date}}', friendlyDate);
body.replaceText('{{User}}', row[13]);
doc.saveAndClose();
const url = doc.getUrl();
sheet.getRange(index + 1, 15).setValue(url)
})
}
If the placeholder for the image is a paragraph of its own, and not part of a container element that includes other content, you could to the following:
Find the placeholder using findText(searchPattern).
Get the Blob from the image URL via UrlFetchApp.fetch(url) and getBlob().
Get the container element that included the placeholder, and use insertInlineImage to insert the retrieved image to the beginning of this element.
For example, if the URL to the images were in column A (so the images should replace {{Scope}}), you could replace this line:
body.replaceText('{{Scope}}', row[0]);
With this:
const rangeElement = body.findText('{{Scope}}');
const imageBlob = UrlFetchApp.fetch(row[0]).getBlob();
if (rangeElement) {
const element = rangeElement.getElement();
element.asText().setText("");
const image = element.getParent().asParagraph().insertInlineImage(0, imageBlob);
}
Important note:
This will remove all the other content in the paragraph the placeholder was on. You could also append the image just before or after the paragraph, but not at the exact same location the placeholder was on. See this related question.
Other issues:
Instead of checking for each iteration whether index === 0, I'd suggest either getting the range without headers (.getRange(2,1, sheet.getLastRow() - 1, sheet.getLastColumn())), or removing the header array from the outer array (rows.shift()). In this case, though, you should be careful to modify all the other mentions of index inside the loop, since the row this will reference will be a different one.
It's not a best practice to call setValue inside a loop. I'd suggest to push the data into an array instead (e.g. urls.push([url])) and write those values at once (using setValues) after the loop is finished (e.g. sheet.getRange(1,15,urls.length).setValues(urls)).
You will need to convert the image url into a blob and then define the position where to enter it in the doc. Replace text only replaces text with text.
Adapted solution from https://www.labnol.org/code/20078-insert-image-in-google-document
function webImage() {
//continuing from your code
const doc = DocumentApp.openById(copy.getId())
const body = doc.getBody();
// using example image url, not sure which row has your urls
var image = 'www.imageurl.com/image.jpg';
var blob = UrlFetchApp.fetch(image).getBlob();
// find position, not sure what you are using in the doc, used text PLACEHOLDER as an example
var position = body.findText('PLACEHOLDER').getElement()
var offset = body.getChildIndex(position.getParent())
// insert image
body.insertImage(offset +1,blob)
// remove placeholder text
position.removeFromParent()
}
Another solution: Add images to Google Document via Google Apps Script

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);

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