Save instead of saveAs using excel activeX - javascript

I am using javascript and activeX to save and edit data of an excel document. So far everything works. But now i would like to write a new version where I can update a specific cell and keep the other cells as they where.
Here is the code i am using:
function Write() {
var Excel, Book; // Declare the variables
Excel = new ActiveXObject("Excel.Application"); // Create the Excel application object.
Excel.Visible = false; // Make Excel invisible.
Book = Excel.Workbooks.Add() // Create a new work book.
Book.ActiveSheet.Cells(1,1).Value = document.A1.value;
Book.SaveAs("G:/whiteboard.xls");
Excel.Quit(); // Close Excel with the Quit method on the Application object.
alert("Uppgifter sparade");
}
And I want to save, instead of saveAs.
Any ideas?

In case anyone still looking for this.
Use excelObj.ActiveWorkbook.Save(); to save the Excel file.
Here is an example.
function saveExcel() {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var path = "file:\\\\C:\\Users\\User\\Desktop\\TestFile.xls";
var excel_file = excel.Workbooks.Open(path);
var excel_sheet = excel_file.Worksheets(1);
//Editing all cells from Row 6 to 10 and Column 1 to 5
for (var row = 6; row <=10; row++) {
for (var col = 1; col <=5 ; col++) {
excel_sheet.Cells(row,col).Value = "Setting New Cell Data";
};
};
//Save Excel
excel.ActiveWorkbook.Save();
alert("Excel Saved!");
//showing excel are editing is done.
excel.Visible = true;
excel = null;
excel_file = null;
};

Related

I need 2 different buttons, to create new folder and create a new PDF in that folder

I've been struggling to build a specific weekly stock system reports. So to give you a basic overview, I have a mastersheet that I want to generate reports from, triggered by an UI button. The first step however is to create a folder for that week to place the PDF's in. I can create the folder, and I can generate the PDF in my root Google Drive folder, but I can't seem to move the PDF anywhere after that. I have attempted to use .moveTo() but I can't get that to work. Does anyone have any advise?
function onOpen(e)
{
SpreadsheetApp.getUi()
.createMenu('Physical')
.addItem('New folder','newFolder')
.addItem('Generate PDF','generatePDF')
.addToUi();
}
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId)
var destFolder = parFolder.createFolder('Week ' + week);
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var speadsheetFile = ss.getId();
var file = DriveApp.getFileById(speadsheetFile);
var folderId = file.getParents().next().getId();
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Description
These types of situations are hard to test because the circumstances are specific to the OP questioner. However, I believe this will work.
Using the PropertyService Script Properties, store the newly created folderId and then get that id from Script Properties to move the file.
A note of caution, I didn't check for the case if the week changes and a new folder is not created, the pdf will go to the previous week folder.
Regarding creating a button and linking a function to the button see this article Buttons in Google Sheets
Script
function newFolder(){
var today = new Date();
var week = Utilities.formatDate(today, "Europe/Amsterdam", "w"); //need to find a way to minus 1 for the current week
var spreadsheetId = SpreadsheetApp.getActiveSpreadsheet().getId(); //time to create a new folder
var spreadsheetFile = DriveApp.getFileById(spreadsheetId);
var folderId = spreadsheetFile.getParents().next().getId();
var parFolder = DriveApp.getFolderById(folderId);
var folderName = 'Week '+week;
// check if folder already exists
var subFolders = parFolder.getFoldersByName(folderName);
var destFolder = null;
if( subFolders.hasNext() ) {
SpreadsheetApp.getUi().alert("Folder "+folderName+" already exists");
destFolder = subFolders.next();
}
else {
destFolder = parFolder.createFolder(folderName);
}
// store folder id to Script Properties
var props = PropertiesService.getScriptProperties();
props.setProperty("foldeId",destFolder.getId());
}
function generatePDF(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
// get folder id from Script Properties
var folderId = PropertiesService.getScriptProperties("folderId");
if( !folderId ) {
SpreadsheetApp.getUi().alert("Property folderId not found");
return;
}
var pdf = DriveApp.createFile(ss.getBlob())
pdf.moveTo(folderId); //find way to move file either to destination folder or to parent folder
}
Reference
SpreadsheetApp.getUi().alert()
PropetiesService

GAS how upload multiple file in google drive

I'm trying to upload multiple files into Google Drive Using Google Apps Script.
My code work fine when I want to upload one file
// UPLOAD IMG IN GOOGLE DRIVE
var url = 'http://www.pngall.com/wp-content/uploads/2/1-Number-PNG-Picture.png';
var response = UrlFetchApp.fetch(url); // get api endpoint
var rc = response.getResponseCode();
if(rc=200){
var fileBlob = response.getBlob();
var folder = DriveApp.getFolderById("xxxxxx")
if(folder !=null) {
var file_img = folder.createFile(fileBlob)
var img = file_img.getUrl();
}
}
} else {
var img = "";
}
// APPEND VALUE TO SHEET
sheet.appendRow([img]);
I'm trying to modify the above script in order to upload multiple files into google drive, but my code doesn't works.
This is my (not working) code:
// UPLOAD IMG IN GOOGLE DRIVE
var url = ['http://www.pngall.com/wp-content/uploads/2/1-Number-PNG-Picture.png', 'https://www.yourcloudworks.com/wp-content/uploads/2019/09/number-digit-2-png-transparent-images-transparent-backgrounds-Number-2-PNG-images-free-download_PNG14949.png'];
for(var i=0; i<url.length; i++){
var response = UrlFetchApp.fetchAll(url);
var rc = response.getResponseCode();
if(rc=200){
var fileBlob = response.getBlob();
var folder = DriveApp.getFolderById("xxxxxx")
if(folder !=null) {
var file_img = folder.createFile(fileBlob[i])
var img = file_img.getUrl()[i];
}
}
} else {
var img = "";
}
// APPEND VALUE TO SHEET
sheet.appendRow(img[i]);
}
TypeError: response.getResponseCode is not a function
Any help?
Modification points:
In your script, for(var i=0; i<url.length; i++){}else{} is used. I thought that you might misunderstand the if statement and for loop.
When you want to compare the value at the if statement, please modify if(rc=200){ to if(rc==200){.
The response value from UrlFetchApp.fetchAll(url) is an array.
I think that the reason of the error message is this.
folder.createFile(fileBlob[i]) is folder.createFile(fileBlob).
file_img.getUrl()[i] is file_img.getUrl().
When file_img.setTrashed(true) is used, the downloaded files are moved to the trashbox. If you don't want to move them to the trashbox, please remove the line.
I think that when the values are put to the Spreadsheet by one request, the process cost will be low. In your script, I would like to propose to use setValues instead of appendRow.
When above points are reflected to your script, it becomes as follows.
Modified script:
Please copy and paste the following modified script. And please set the variable of sheet, and the folder ID.
function myFunction() {
// var sheet = SpreadsheetApp.getActiveSheet();
var url = ['http://www.pngall.com/wp-content/uploads/2/1-Number-PNG-Picture.png', 'https://www.yourcloudworks.com/wp-content/uploads/2019/09/number-digit-2-png-transparent-images-transparent-backgrounds-Number-2-PNG-images-free-download_PNG14949.png'];
var requests = url.map(u => ({url: u, muteHttpExceptions: true}));
var response = UrlFetchApp.fetchAll(requests);
var imgs = [];
for (var i = 0; i < response.length; i++) {
if (response[i].getResponseCode() == 200) {
var fileBlob = response[i].getBlob();
var folder = DriveApp.getFolderById("xxxxxx");
if (folder != null) {
var file_img = folder.createFile(fileBlob);
imgs.push([file_img.getUrl()]);
// file_img.setTrashed(true); // When this script is used, the downloaded files are moved to the trashbox.
}
}
}
if (imgs.length > 0) {
sheet.getRange(sheet.getLastRow() + 1, 1, imgs.length).setValues(imgs);
}
}
When muteHttpExceptions: true is used, the script can be run even when an error occurs.
References:
fetchAll(requests)
if...else
Loops and iteration

Save Excel file via web page using java script

var myApp = new ActiveXObject("Excel.Application");
myApp.visible = true;
var myWorkbook;
var xlCellTypeLastCell = 11;
myObject = new ActiveXObject("Scripting.FileSystemObject");
if(myObject.FileExists("xyz.xlsx")){
myWorkbook = myApp.Workbooks.Open("xyz.xlsx");
}
else{
myWorkbook=myApp.Workbooks.Add();
}
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate ;
newRow = myApp.ActiveCell.Row + 1;
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value=document.getElementById("table1").rows[1].cells.item(0).innerHTML; myWorksheet.Cells(newRow,2).value=document.getElementById("table1").rows[1].cells.item(4).innerHTML;
myWorksheet.Cells(newRow,3).value=document.getElementById("table1").rows[1].cells.item(5).innerHTML;
myWorkbook.SaveAs("xyz.xlsx");
myApp.Quit();
The above code saves the excel for the first time, in the second loop it pops the window asking to save manually, i am trying to save the file automatically without manual intervention.
You need to switch off display alerts temporarily. This is in VBA. Change it to use myApp
Application.DisplayAlerts = False
' save here
Application.DisplayAlerts = True
The DisplayAlerts documentation is short and worth reading: https://msdn.microsoft.com/en-us/library/office/ff839782.aspx

how to use createAndFillWorkbook() in exceljs?

I followed the documentation
var workbook = createAndFillWorkbook();
and I get this
error Object # has no method 'createAndFillWorkbook'
even if I required exceljs already
var Excel = require("exceljs");
What I wanted to do was to create a report but I am somehow confused on the documentation because it does not say here how to use the createAndFillWorkbook() method it just says here to use it right away.
I referred here in the documentation: https://github.com/guyonroche/exceljs#writing-xlsx
createAndFillWorkbook(); does not mean a function.(maybe pseudo function)
You must create some workbook then fill content.
See below.
// create workbook by api.
var workbook = new Excel.Workbook();
// must create one more sheet.
var sheet = workbook.addWorksheet("My Sheet");
// you can create xlsx file now.
workbook.xlsx.writeFile("C:\\somepath\\some.xlsx").then(function() {
console.log("xls file is written.");
});
var excel = require("exceljs");
var workbook1 = new excel.Workbook();
workbook1.creator = 'Me';
workbook1.lastModifiedBy = 'Me';
workbook1.created = new Date();
workbook1.modified = new Date();
var sheet1 = workbook1.addWorksheet('Sheet1');
var reColumns=[
{header:'FirstName',key:'firstname'},
{header:'LastName',key:'lastname'},
{header:'Other Name',key:'othername'}
];
sheet1.columns = reColumns;
workbook1.xlsx.writeFile("./uploads/error.xlsx").then(function() {
console.log("xlsx file is written.");
});
This is my sample code which works for me.

How to Make a list on Google SpreadSheet of all files in a Google Drive folder

I have a Folder With more than 2000 Files.. And i Need to make a List of all these files on google spreadsheet.. I Found online some Scripts.. but they're not completely working.
When i hit "RUN" i just get a list of 250 Files.
Reading on Google Developers page i found some things about enabling Google Drive advanced services (and i did it)..
And i think i could solve this problem using something named "tokens"??
I don't know.. i'm not a programmer, and i barely know english..
i Tried editing this script making a fusion of what i found online.. But anything works.. i just get errors that i can't even understand..
So.. is there someone able to fix it?
function listFilesInFolder() {
var folder = DocsList.getFolder("Film");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Nome", "Data", "Dimensione"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
];
sheet.appendRow(data);
}
};
This Script works for at least 2200 Files :)
function listFilesInFolder(id) {
var folder = DriveApp.getFolderById('MyFolderID');
var contents = folder.getFiles();
var file;
var name;
var sheet = SpreadsheetApp.getActiveSheet();
var date;
var size;
sheet.clear();
sheet.appendRow(["Nome", "Data", "Dimensione"]);
while(contents.hasNext()) {
file = contents.next();
name = file.getName();
date = file.getDateCreated()
size = file.getSize()
data = [name, date, size]
sheet.appendRow(data);
}
};
The answer above appends a row in every iteration wich is particularly slow and there is a chance you will exceed the maximum execution time (see best practices)) so here is a version that uses an array to collect data and writes the array using a single setValues() .
The other issue is that it gets all the files in your drive, not in the folder you chose...
so below is a version that gets all files that are not Google documents, ie it counts only files that take space (images, pdf...) with a maximum of 4000 files.
full code below :
function listFilesInFolder() {
var folder = DocsList.getFolderById('0B3qSFd3iikE3MS0yMzU4YjQ4NC04NjQxLTQyYmEtYTExNC1lMWVhNTZiMjlhMmI');
var file;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
var data = [];
data.push(["Name", "Data", "Size", "url"]);
var filesresult = folder.getFilesByTypeForPaging(DocsList.FileType.OTHER, 4000);
var files = filesresult.getFiles();
Logger.log(files.length);
for (var i in files) {
file = files[i];
data.push([
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl()
]);
}
sheet.getRange(1,1,data.length,data[0].length).setValues(data);
}
Paging is what you're looking for. When you have a large number of results (like 2000 files), you generally divide the request into 'pages', either to show the user page by page or in this case, to stay within the API limits.
The 'token' isn't a big deal.. it's just how your script remembers the page number while it's dealing with the current page.
So there's information about this here: https://developers.google.com/apps-script/reference/docs-list/files-result
The script at the top of the page is quite apt to your situation. Your script becomes something like...
function listFilesInFolder() {
var folder = DocsList.getFolder("Film");
//var contents = folder.getFiles();
var file;
//var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Nome", "Data", "Dimensione"]);
var pageSize = 200;
var files = null;
var token = null; // use a null token for the first lookup
do {
var result = DocsList.getAllFilesForPaging(pageSize, token);
files = result.getFiles();
token = result.getToken();
for (var i = 0; i < files.length; i++) {
//Logger.log(files[i].getName());
file = files[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
];
sheet.appendRow(data);
}
} while (files.length >= pageSize);
};
I'm not promising this will work.. but I'm sure you can sort it out. Basically the "while loop" on that page replaces the "for loop" from your script. The loop on that page just calls Logger.log(), so you swap that with the sheet.appendRow(data)
I've taken the script suggested by Jonathan Livingston and made some edits.
Now it:
can take a name of a sheet with future report. It can make a new sheet if it doesn't exist,
gives more parameters, including list of editors (e-mails)
Here's the code:
function TESTlistFilesInFolder() {
listFilesInFolder("0B0pifCWzjn-ib0ZWT2x1ekNOWAY", "Files Report");
// ^^^^^^^^ folder ID ^^^^^^^^^ ^sheet Name^
}
// original script: http://stackoverflow.com/a/25730522/5372400
function listFilesInFolder(id, sheetName) {
sheetName = sheetName || id;
var sheet = createSheetIfNotExists(sheetName);
var folder = DriveApp.getFolderById(id);
var contents = folder.getFiles();
sheet.clear();
sheet.appendRow(["Name", "CreatedDate", "Last Updated", "Id", "Url", "Editors", "Viewers", "Owner", "Access", "Permission", "Size"]);
var data = [];
var file;
var info = [];
while(contents.hasNext()) {
data = [];
file = contents.next();
data.push(file.getName());
data.push(file.getDateCreated());
data.push(file.getLastUpdated());
data.push(file.getId());
data.push(file.getUrl());
// convert to string: http://www.w3schools.com/jsref/jsref_join.asp
data.push(getEmails(file.getEditors()).join());
data.push(getEmails(file.getViewers()).join());
data.push(getEmails(file.getOwner()).join());
data.push(file.getSharingAccess());
data.push(file.getSharingPermission());
data.push(file.getSize());
info.push(data);
}
var rows = info.length;
var cols = info[0].length;
var range = sheet.getRange(2,1,rows,cols);
range.setValues(info);
};
function createSheetIfNotExists(name) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
try {ss.setActiveSheet(ss.getSheetByName(name));}
catch (e) {ss.insertSheet(name);}
var sheet = ss.getSheetByName(name);
return sheet;
}
// users: https://developers.google.com/apps-script/reference/base/user
function getEmails(users) {
var emails = [];
var user;
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray(users)) { users = [users]; }
for (var i = 0; i < users.length; i++) {
user = users[i];
emails.push(user.getEmail());
}
return emails;
}

Categories

Resources