accessing spreadsheet by ID - google-apps-script

I am using google Apps script.
I need to access some information in the spreadsheet.
I navigate to the file and find its ID.
However, the function
var fileID = file.getId()
var activityName = Sheets.Spreadsheets.Values.get (fileID,'B1:B4'); doesn't seem to accept the ID, even thought the ID is correct as I logged it and checked.
function getTheInformation() {
//navigate to the correct folder
var dApp = DriveApp;
var folderIter = dApp.getFoldersByName("scriptFolder");
var folder = folderIter.next();
//reality check
Logger.log(folder);
var filesIter = folder.getFiles();
var i = 1;
//cycle through the files
while (filesIter.hasNext())
{
var file = filesIter.next();
var fileID = file.getId()
var fileName = file.getName();
//here the code breaks
var activityName = Sheets.Spreadsheets.Values.get (fileID,'B1:B4');
i++;
Logger.log(fileName + " file ID " + fileID);
}
}

This worked for me:
function getTheInformation() {
var dApp = DriveApp;
var folderIter = dApp.getFoldersByName("Questions");
var folder = folderIter.next();
var filesIter = folder.getFiles();
while (filesIter.hasNext()) {
var file = filesIter.next();
var fileID = file.getId()
var fileName = file.getName();
if(fileName=='StackOverflow1') {
var values = Sheets.Spreadsheets.Values.get (fileID,'Sheet1!B1:B4')
Logger.log(values);
}
}
}
Things I did a little different: I added the sheet name to the range and I also checked for the correct file name.

Related

Google Apps Script: How to specify to only pull back files with certain file names

I have a folder 35000 images in and growing. I need to extract the file name and the URL of the file.
I had been using this but its now timing out, so I want to pop in that it looks for a file name begining with x but I havent the foggiest how to! Please help!
function listFolderContents() {
var foldername = 'Salesforce Images';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
sheet.appendRow( ['name', 'link'] );
var file;
var name;
var link;
var row;
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
sheet.appendRow( [name, link] );
}
I've tried a few of the rabit holes that Google search threw up but no luck
Try this:
function listFolderContents(name) {
var foldername = 'Salesforce Images';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFilesByName(name);
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet();
sheet.appendRow( ['name', 'link'] );
var file;
var name;
var link;
var row;
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
link = file.getUrl();
sheet.appendRow( [name, link] );
}
}

Trying to copy the data from a sheet inside a folder in Google Drive to a different sheet but the original changes every day with different id's

Every day there is a new report that I want to copy to a master sheet outside of the folder, I'm using a different script to transfer the file from my Gmail to a folder in Drive, there is only one file at a time in the folder. I tried getting the id of the file with this code and then use the id to copy and paste the info. I'm still trying to understand how google scripts works so I know the code is not functional, I would like to know if what I want to do is possible and a guide to what I could do.
function obtainId() {
var folder = DriveApp.getFolderById('ID');
var files = folder.getFiles();
var file = files.next();
var id = DriveApp.getFileById(file.getId());
var ss = SpreadsheetApp.getActiveSpreadsheet(id);
var copySheet = ss.getSheetByName("name");
var pasteSheet = ss.getSheetByName("name");
var source = copySheet.getRange(range);
var destination = pasteSheet.getRange(range);
source.copyTo(destination);
}
Obtain Id copy data for a file with today's date in particular folder
function obtainId() {
let dt = new Date();
let tdv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()).valueOf();
var folder = DriveApp.getFolderById('ID');
var files = folder.getFilesByType(mimeType.GOOGlE_SHEETS);
let id;
while (files.hasNext()) {
let file = files.next(;
if (file.getDateCreated().valueOf() > tdv) {
id = file.getId();
break;
}
}
const ss = SpreadsheetApp.openById(id);
const csh = ss.getSheetByName("copy sheet name");
const psh = ss.getSheetByName("paste sheet name");
csh.getRange().copyTo(psh.getRange();)
}
Using Sheets API:
function obtainId() {
let dt = new Date();
let tdv = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()).valueOf();
var folder = DriveApp.getFolderById(gobj.globals.folder3id);
var files = folder.getFilesByType(MimeType.GOOGLE_SHEETS);
let id;
while (files.hasNext()) {
let file = files.next();
if (file.getDateCreated().valueOf() > tdv) {
id = file.getId();
break;
}
}
const ss = SpreadsheetApp.openById(id);
const csh = ss.getSheetByName("Sheet1");
const dss = SpreadsheetApp.getActive();
const psh = dss.getSheetByName("Sheet2");
let crg = csh.getDataRange().getA1Notation();
let vs = Sheets.Spreadsheets.Values.get(ss.getId(),`${csh.getName()}!${crg}`).values;
prg = psh.getRange(psh.getLastRow() + 1,1,vs.length,vs[0].length).getA1Notation();
Sheets.Spreadsheets.Values.update({values: vs}, dss.getId(), psh.getSheetName(), {valueInputOption: "USER_ENTERED"});
}

save a sheet from spreadsheet as pdf in same google drive folder

I am trying to make a code that gets all files from a google drive folder, then converts all files to excel and save in same folder and also make pdf files from second sheet 'V2' of each spreadsheet and save in same folder.
I am successful in creating excel folder but pdf part is not working. I have copied code from many different sources.
function Generator(){
//Factors to change every month
var folderID = '14Bz9LLAiv2BgsT4bowxUtMfG2AsTxk91';
// Loop through all the files and save as excel and pdf.
var reportsFolder = DriveApp.getFolderById(folderID);
var files = reportsFolder.getFiles();
var TAB_NAME = 'V2' //For pdf
while(files.hasNext()) {
var file = files.next();
var bnkFile = SpreadsheetApp.getActiveSpreadsheet();
var name = file.getName();
//Creating Excel files
var url = "https://docs.google.com/spreadsheets/d/" + file.getId() + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); // Modified
reportsFolder.createFile(blob);
//Creating PDF files
var VName = name.replace("REPORT", "V2");
var V2Sheet = bnkFile.getSheetByName(TAB_NAME);
var url2 = "https://docs.google.com/spreadsheets/d/" + V2Sheet.getId() + "/export?exportFormat=pdf&format=pdf" + ScriptApp.getOAuthToken();
var blob2 = UrlFetchApp.fetch(url2).getBlob().setName(VName + ".pdf"); // Modified
reportsFolder.createFile(blob2);
}
}
Any simple solution for generating PDFs?
Explanation:
You need to specify both the id of the spreadsheet file but also the gid of the sheet itself.
Replace
var url2 = "https://docs.google.com/spreadsheets/d/" + V2Sheet.getId() + "/export?exportFormat=pdf&format=pdf" + ScriptApp.getOAuthToken();
with
var url2 = "https://docs.google.com/spreadsheets/d/"+ file.getId() + "/export?format=pdf&id="+file.getId()+"&gid="+V2Sheet.getSheetId();
Replace
var bnkFile = SpreadsheetApp.getActiveSpreadsheet();
with
var bnkFile = SpreadsheetApp.openById(file.getId());
to get the spreadsheet object of the file. Your current code gets the active spreadsheet which is the spreadsheet that this script is attached to.
Also use the requestData object as I define it in my solution.
Solution:
function Generator(){
//Factors to change every month
var folderID = '14Bz9LLAiv2BgsT4bowxUtMfG2AsTxk91';
// Loop through all the files and save as excel and pdf.
var reportsFolder = DriveApp.getFolderById(folderID);
var files = reportsFolder.getFiles();
var TAB_NAME = 'V2' //For pdf
while(files.hasNext()) {
var file = files.next();
if(file.getMimeType()=='application/vnd.google-apps.spreadsheet'){
var bnkFile = SpreadsheetApp.openById(file.getId());
var name = file.getName();
//Creating Excel files
var url = "https://docs.google.com/spreadsheets/d/" + file.getId() + "/export?format=xlsx&access_token=" + ScriptApp.getOAuthToken();
var blob = UrlFetchApp.fetch(url).getBlob().setName(name + ".xlsx"); // Modified
reportsFolder.createFile(blob);
//Creating PDF files
var VName = name.replace("REPORT", "V2");
var V2Sheet = bnkFile.getSheetByName(TAB_NAME);
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var url2 = "https://docs.google.com/spreadsheets/d/"+ file.getId() + "/export?format=pdf&id="+file.getId()+"&gid="+V2Sheet.getSheetId();
var blob2 = UrlFetchApp.fetch(url2,requestData).getBlob().setName(VName + ".pdf"); // Modified
var pdfFile = reportsFolder.createFile(blob2);
var pdfUrl = pdfFile.getUrl(); // <- pdfUrl will give you the url of the pdf file.
}
}
}

I am trying to download the Google drive contents to sheets not getting the last modified column

I am trying to download the Google drive contents to sheets not getting the last modified column.
function myFunction() {
var foldername = 'Folder Name';
var folderlisting = 'listing of folder ' + foldername;
var folders = DriveApp.getFoldersByName(foldername)
var folder = folders.next();
var contents = folder.getFiles();
var contents = folder.getFiles();
var ss = SpreadsheetApp.create(folderlisting);
var sheet = ss.getActiveSheet(); sheet.appendRow(['name','link','Owner','Modified']);
var file;
var name;
var link;
var Owner;
var Modified;
var row;
while(contents.hasNext()){
file = contents.next();
name = file.getName();
link = file.getUrl();
Owner = file.getOwner();
Modified = file.getModified();
sheet.appendRow([name, link,Owner,Modified]);
} };
I Think no method of getModified, please try with this
Modified = file.getLastUpdated();

PDF in other google drive

I have several tech's working with one google sheet.
Want to save the PDF from a filled sheet to a specific google drive (myPMtechs#gmail.com) // fake email only for indication // and not to my drive but keep the sheet in my drive.
For some reason the folder ID part does not work and I cannot find out why.
Script is
// Get active spreadsheet.
var sourceSpreadsheet = SpreadsheetApp.getActive();
// Get active sheet.
var sheets = sourceSpreadsheet.getSheets();
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
// Output filename.
var jobNo = sourceSpreadsheet.getRange('A10:A10').getValue();
var jobName = sourceSpreadsheet.getRange('B3:B3').getValue();
var doorNo = sourceSpreadsheet.getRange('B5:B5').getValue();
var date = sourceSpreadsheet.getRange('A8:A8').getDisplayValue();
var pdfName = date + " - " + jobNo + " - " + jobName + " - " + doorNo;
// Get folder containing spreadsheet to save pdf in.
var parents = DriveApp.getFileById(sourceSpreadsheet.getId()).getParents();
if (parents.hasNext()) {
var folder = parents.next();
}
else {
folder = DriveApp.getRootFolder();
}
// Copy whole spreadsheet.
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder))
// Delete redundant sheets.
var sheets = destSpreadsheet.getSheets();
for (i = 0; i < sheets.length; i++) {
if (sheets[i].getSheetName() != sheetName){
destSpreadsheet.deleteSheet(sheets[i]);
}
}
var destSheet = destSpreadsheet.getSheets()[0];
// Repace cell values with text (to avoid broken references).
var sourceRange = sourceSheet.getRange(1,1,sourceSheet.getMaxRows(),sourceSheet.getMaxColumns());
var sourcevalues = sourceRange.getValues();
var destRange = destSheet.getRange(1, 1, destSheet.getMaxRows(),destSheet.getMaxColumns());destRange.setValues(sourcevalues);
// Save to pdf.
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);var newFile = folder.createFile(theBlob);
// Delete the temporary sheet.
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
//Move the pdf file from rootfolder to the folder where the PMSheet are to be stored.
var files = DriveApp.getRootFolder().getFiles();
while (files.hasNext()) {
var file = files.next();
var destination = DriveApp.getFolderById("**Folder where files should go to**");
destination.addFile(file);
var pull = DriveApp.getRootFolder();
pull.removeFile(file);
}