Get specific Range to Export - google-apps-script

can anyone help me with my problem?
Need to export a specific range (A1:J39), not the full sheet.
function SavePDFtoDrive() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ltrsht = ss.getSheetByName("Schichtübergabe-Protokoll");
var datasheet = ss.getSheetByName("Daten");
var sheets=SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i =0;i<sheets.length;i++){
if(sheets[i].getName()!="Schichtübergabe-Protokoll"){ sheets[i].hideSheet() }
}
var pdf = DriveApp.getFileById(ss.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(datasheet.getRange("I8").getValue()+".pdf");
var folderID = "1dyKFNvQWrSiNFA8N5PyUMPJQpWSVhsLf"; // Folder id to save in a folder
var folder = DriveApp.getFolderById(folderID);
var newFile = folder.createFile(theBlob);
}

Answer:
Rather than getting your blob using DriveApp, you can obtain your blob from an export URL using UrlFetchApp.
More Information:
When you use DriveApp to create a blob of a file, it doesn't have the functionality to read the specifics of the file. In this case, you can't specify the range of a Sheet you wish to export with DriveApp.
You can, however, build a URL with all your export parameters and create your export in Drive by creating a blob of the response and creating it in Drive.
Code:
function SavePDFtoDrive() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ltrsht = ss.getSheetByName("Schichtübergabe-Protokoll");
var datasheet = ss.getSheetByName("Daten");
// build your URL:
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?"
//define your parameters:
var params = 'exportFormat=pdf&format=pdf'
+ '&portrait=false'
+ '&fitw=true'
+ '&gid=' + ltrsht.getSheetId()
+ '&range=A1:J39';
//get token for UrlFetch:
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + params, {
'headers': {
'Authorization': 'Bearer ' + token
}
});
var fileName = datasheet.getRange("I8").getValue() + ".pdf";
var theBlob = response.getBlob().setName(fileName);
var folderID = "1Hp-P1dzWaKHhhS2FTPzKib6pwJibS12t";
var folder = DriveApp.getFolderById(folderID);
folder.createFile(theBlob);
}
References:
Class UrlFetchApp | Apps Script | Google Developers
Related Questions/Answers:
how to print a long Google sheets column in fewer columns

Related

Error : I want to convert the file from XLSX to csv using google script

Hi Facing error while running code of Coverting excel to csv. Please guide what to edit to solve the query.
function makeCSV() {
var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN")
var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj")
var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" +
MimeType.MICROSOFT_EXCEL_LEGACY + "'";
var sourceFiles = SourceFolder.searchFiles(searchQuery);
var now = new Date();
var properties = PropertiesService.getScriptProperties();
var cutoff_datetime = properties.getProperty('last_execution_time');
if(cutoff_datetime)
cutoff_datetime = new Date(cutoff_datetime);
while (sourceFiles.hasNext()){
var sourceFile = sourceFiles.next();
if(!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime){
var fileId = sourceFile.getId();
var Spreadsheet = Drive.Files.copy({mimeType: MimeType.csv, parents:
[{id:"1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj"}]}, fileId);
}
}
properties.setProperty('last_execution_time',now.toString());
}
Unfortunately, XLSX data cannot be directly converted to CSV data using Google Apps Script. And, Drive.Files.copy can convert non-Google Docs files to Google Docs files. Please be careful about this. I think that this is the reason for your current issue. In order to convert XLSX data to CSV data using Google Apps Script, it is required to do the following flow.
Convert XLSX data to Google Spreadsheet.
Convert Google Spreadsheet to CSV data.
Remove Google Spreadsheet.
When this flow is reflected in your script, it becomes as follows.
Modified script:
function makeCSV() {
var SourceFolder = DriveApp.getFolderById("1aoonhCebvI5DddvJVGTzBvWs2BPn_yXN");
var DestinationFolder = DriveApp.getFolderById("1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj");
var searchQuery = "mimeType='" + MimeType.MICROSOFT_EXCEL + "' or mimeType='" + MimeType.MICROSOFT_EXCEL_LEGACY + "'";
var sourceFiles = SourceFolder.searchFiles(searchQuery);
var now = new Date();
var properties = PropertiesService.getScriptProperties();
var cutoff_datetime = properties.getProperty('last_execution_time');
if (cutoff_datetime) cutoff_datetime = new Date(cutoff_datetime);
var token = ScriptApp.getOAuthToken();
while (sourceFiles.hasNext()) {
var sourceFile = sourceFiles.next();
if (!cutoff_datetime || sourceFile.getDateCreated() > cutoff_datetime) {
var fileId = sourceFile.getId();
var ssId = Drive.Files.copy({mimeType: MimeType.GOOGLE_SHEETS, parents: [{ id: "1LB0Em4vYFJV8vJIEiLt6Tg5pnzPATZEj" }]}, fileId).id;
var url = "https://docs.google.com/spreadsheets/export?exportFormat=csv&id=" + ssId;
var blob = UrlFetchApp.fetch(url, {headers: {authorization: "Bearer " + token}}).getBlob();
DestinationFolder.createFile(blob.setName(sourceFile.getName().split(".")[0] + ".csv"));
DriveApp.getFileById(ssId).setTrashed(true);
}
}
properties.setProperty('last_execution_time', now.toString());
}
When this script is run, the XLSX data is converted to Google Spreadsheet, and Google Spreadsheet is converted to CSV data. The CSV file is created to DestinationFolder folder.
Note:
This script used Drive API. So, please enable Drive API at Advanced Google services.
References:
Files: copy
fetch(url, params)

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.
}
}
}

Getting an error for next() function when trying to run function from shared sheet

I have a script that exports a sheet to a pdf file when function is run. This works fine when I run it from the account in which the script was created but when a shared user runs it returns the following error: Exception: Cannot retrieve the next object: iterator has reached the end. Line 9
The code is as below, i'm not sure what actually is wrong with this so would be glad of help:
function CreatePDF() {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
var sheetName = "Stock List";
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var sh = sourceSpreadsheet.getSheetByName("Product List");
var driveFile = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
var parentFolder = driveFile.getParents();
var folderName =parentFolder.next().getId();
var folder = DriveApp.getFolderById(folderName);
var numf = sourceSpreadsheet.getRangeByName("exportrange").getValue();
var anof = numf.split("/",2);
var pdfRange = sh.getRange("F1");
var pdfName = pdfRange.getValue();
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+sourceSpreadsheet.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.00'
+ '&bottom_margin=0.00'
+ '&left_margin=0.00'
+ '&right_margin=0.00'
+ '&sheetnames=false&printtitle=false'
+ '&pagenumbers=false&gridlines=false'
+ '&fzr=false'
+ '&gid='+sourceSheet.getSheetId();
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
var files = folder.getFilesByName(pdfName);
while (files.hasNext())
{
files.next().setTrashed(true);
}
}

google app script : how to change folder destination

I am using the script below to export a google spreadsheet to CSV (thank you ziganotschka).
I am trying to save the CSV in another folder than the same as my Spreadsheet.
I have a folder containing my spreadsheet and inside a subfolder ("Final_Export) where I would like the CSV to save in.
The app script I use is :
function saveAsCSV() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ssname = ss.getName();
var sheet = ss.getActiveSheet();
var folder = DriveApp.getFileById(ss.getId()).getParents().next();
var fileName = ssname + ".csv";
var url = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/export?
exportFormat=csv&format=csv";
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + sheet.getSheetId(), {
headers: {
'Authorization': 'Bearer ' + token
}
});
folder.createFile(response.getBlob().setName(fileName));
}
Thank you for your help
Finally, I found the solution.
I had this code :
var parentFolder = DriveApp.getFolderById("myFolderDestinationId");
var folder = parentFolder;

Export Google Sheets to PDF without cell gridlines

I'm trying to export PDF from Google Sheets via Apps Script. I've found useful code online, which works perfectly, except I can't find a way to export it without the grid, or change margins and page size.
function generatePdf() {
var originalSpreadsheet = SpreadsheetApp.getActive();
var sourcesheet = originalSpreadsheet.getSheetByName("TestSheet");
var sourcerange = sourcesheet.getRange('B1:K55'); // range to get - here I get all of columns which i want
var sourcevalues = sourcerange.getValues();
var data = sourcesheet.getDataRange().getValues();
var number = originalSpreadsheet.getRange('G9:H9').getValue();
var newSpreadsheet = SpreadsheetApp.create("Invoice pdf"); // can give any name.
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var projectname = SpreadsheetApp.getActiveSpreadsheet();
var sheet = sourcesheet.copyTo(newSpreadsheet);
var destrange = sheet.getRange('B1:K55');
destrange.setValues(sourcevalues);
newSpreadsheet.getSheetByName('Sheet1').activate();
newSpreadsheet.deleteActiveSheet();
var invoiceName = "Invoice "+number;
var pdf = DriveApp.getFileById(newSpreadsheet.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(invoiceName);
var folderID = "1Y7n1e_tzQWvzVykHJf_DSm9lBVmokDHA"; // Folder id to save in a folder.
var folder = DriveApp.getFolderById(folderID);
var newFile = folder.createFile(theBlob);
DriveApp.getFileById(newSpreadsheet.getId()).setTrashed(true);
}
I've been looking for answers everywhere, but I cannot apply some of the solutions I find to my code.
I'm not sure how to do it with the code, but if you want to do it without code... when downloading from Google Sheets, you have the option to remove the cell gridlines. Here are the directions:
File > Download > PDF Document (.pdf)
This will open a preview screen. Sidebar on the right has a dropdown menu called "Formatting."
Under "Formatting," uncheck the box labeled "Show gridlines."
Thats it!
It’s not possible to pass options into the getAs function, but you can export the file yourself and download the URL:
function getPdf(spreadsheet) {
var options = {
format: 'pdf',
exportFormat: 'pdf',
size: 7, // A4
portrait: true,
gridlines: false,
};
// construct export URL
var query = Object.keys(options).map(function (key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(options[key]);
}).join('&');
var exportUrl = spreadsheet.getUrl().replace(/\/edit.*$/, '/export?' + query);
var response = UrlFetchApp.fetch(exportUrl, {
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
});
return {
fileName: spreadsheet.getName() + '.pdf',
content: response.getBlob().getBytes(),
mimeType: MimeType.PDF,
};
}
The full list of export options can be found at https://stackoverflow.com/a/46312255.