Save Excel file via web page using java script - javascript

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

Related

How do I pause/resume in Photoshop with a JS code script?

I'm currently trying to automate a certain task in Photoshop (the latest version) with a JS code script. The each process is that 1. load an image -> 2. do something -> 3. implement an action -> 4. save the image -> 5. repeat this. Pretty simple, right? Cut to the chase, it's my code snippet below.
var opts;
opts = new ExportOptionsSaveForWeb();
opts.format = SaveDocumentType.PNG;
opts.PNG8 = false;
for(var i = 1; i < 6; i ++){
var filename = '/Users/abcde/Desktop/ap/' + i.toString() + '.PNG';
var file = File(filename);
var document = app.open(file);
// do something in Photoshop manually !!
app.doAction('bbbb', 'aaaa');
var savename = '/Users/abcde/Desktop/ap_save/' + i.toString() + '.PNG';
var savefile = new File(savename)
app.activeDocument.exportDocument(savefile, ExportType.SAVEFORWEB, opts);
}
So, my question is how do I pause the program when it loaded an image and do something, and get an input key like 'w' and resume the entire process again?
With my question, the code snippet is going to be like below
var opts;
opts = new ExportOptionsSaveForWeb();
opts.format = SaveDocumentType.PNG;
opts.PNG8 = false;
for(var i = 1; i < 6; i ++){
var filename = '/Users/abcde/Desktop/ap/' + i.toString() + '.PNG';
var file = File(filename);
var document = app.open(file);
// pause this code script (which type of code can I put in here?)
// do something(I'm going to do something manually in the Photoshpp when this script's been paused, this part doesn't has to be written in code)
// resume when it gets a key input(I want to type 'w' when that something task has been done, again.. which type of code function can I put?)
app.doAction('bbbb', 'aaaa');
var savename = '/Users/abcde/Desktop/ap_save/' + i.toString() + '.PNG';
var savefile = new File(savename)
app.activeDocument.exportDocument(savefile, ExportType.SAVEFORWEB, opts);
}
Please help me.
If either it's impossible to build or I need to clarify this question more let me know too.
Thanks.
I would restructure the script to run the export first (in case there is already a file open and then open the next document. Then, when the script is finished, the user can do something with the open document in Photoshop. Once they are done with that, they run the script again.
This needs a bit of extra checking if there is a document already open and also if there are any files left to handle. But it would basically look like this:
// set export options
var opts;
opts = new ExportOptionsSaveForWeb();
opts.format = SaveDocumentType.PNG;
opts.PNG8 = false;
// find out, which destination files already exists, to know which new one to open
// increase i until it finds an index that does not exist yet
var i = 1;
while( File('/Users/abcde/Desktop/ap_save/' + i.toString() + '.PNG').exists ) {
i++;
}
// if a document is already open, run the action on it and export it
if(app.documents.length) {
app.doAction('bbbb', 'aaaa');
var savename = '/Users/abcde/Desktop/ap_save/' + i.toString() + '.PNG';
var savefile = new File(savename)
app.activeDocument.exportDocument(savefile, ExportType.SAVEFORWEB, opts);
app.activeDocument.close();
// increase i once more to jump to the next file
i++;
}
// try to open a new source file, if there is one left
var srcFile = File('/Users/abcde/Desktop/ap/' + i.toString() + '.PNG)'
if(!srcFile.exists) {
// no further source file does exist, exit the script
exit();
}
var document = app.open(file);
// script ends here and the user can do stuff
// and then use a hot key to run the script again

How to update URL address using ASP when based on JSON object

I'm making an application of a list of races in a table, this information is gotten from a JSON api. Upon selecting a race in a table I need a window to pop up with the name of the race in the url address bar, so something like asp?=race_name at the end.
How would I go about completing this?
I've looked this up but can't seem to find an answer, my guess is I'm googling the wrong thing as I'm not good at explaining
for (let i = 0; i < jsonObj.length; i++) {
document.getElementById(jsonObj[i].id).onclick = function () {
var newWin = window.open("","","width=700,height=700");
newWin.onload = function () {
var doc = newWin.document; // Create new document in window
var raceName = document.createElement('h3');
var distance = document.createElement('p');
var location = document.createElement('p');
var curPos = document.createElement('p');
var difference = document.createElement('p');
raceName.textContent = jsonObj[i].race_name;
distance.textContent = jsonObj[i].distance;
location.textContent = jsonObj[i].venue_name;
doc.body.appendChild(raceName);
doc.body.appendChild(distance);
doc.body.appendChild(location);
}
}
Here the window pops up and includes the correct information, I now just need to include code that would update the url address to include race name.

createFile() in google Apps Script is not functioning properly

I am trying to create a file. It works fine when I run the following code segment from the debugger in apps script. However, when I run it real time from the spreadsheet, it says I do not have permission to call createfile. Everything that is logged is identical. The issue is not I do not have authority as I am the only one in the spreadsheet and am the owner. The purpose of the CSV is to move it from my google drive into data for BigQuery
function saveAsCSV(row) { //Doc to Csv
//row = 3; //when this is uncommented and ran from the debugger, it works.
try{
var fileName= Date.now()
fileName = fileName + ".csv";
var csvFile = convertRangeToCsvFile_(fileName,row);
Logger.log(csvFile); //Both times ran on the spreadsheet and from debug equals the same.
DriveApp.createFile(fileName, csvFile);
SpreadsheetApp.getActiveSpreadsheet().getSheetByName("New and Open").getRange("J" + row.toString()).setValue("");
loadCsv(fileName);
}
catch(e){Logger.log("B" + e.message);} //No permission to create file
}
function convertRangeToCsvFile_(csvFileName, r) {
var ws = SpreadsheetApp.getActiveSpreadsheet();
try {
//var data = ws.getValues();
var csvFile = undefined;
var csv = "";
var row = r;
var datArray = Create2DArray(1,19);
datArray[0][0] = ws.getRange("A" + row.toString()).getValue().toString().toUpperCase();
datArray[0][1] = ws.getRange("B"+row.toString()).getValue().toString().toUpperCase();
datArray[0][2] = ws.getRange("C"+row.toString()).getValue().toString().toUpperCase();
datArray[0][3] = ws.getRange("D"+row.toString()).getValue().toString().toUpperCase();
datArray[0][4] = ws.getRange("E"+row.toString()).getValue().toString().toUpperCase();
datArray[0][5] = ws.getRange("F"+row.toString()).getValue().toString().toUpperCase();
datArray[0][6] = ws.getRange("G"+row.toString()).getValue().toString().toUpperCase();
datArray[0][7] = ws.getRange("H"+row.toString()).getValue().toString().toUpperCase();
datArray[0][8] = ws.getRange("I"+row.toString()).getValue().toString().toUpperCase();
datArray[0][9] = new Date(ws.getRange("K"+row.toString()).getValue().toString()).getHours();
datArray[0][10] = new Date(ws.getRange("K"+row.toString()).getValue().toString()).getMinutes();
datArray[0][11] = new Date(ws.getRange("L"+row.toString()).getValue().toString()).getHours();
datArray[0][12] = new Date(ws.getRange("L"+row.toString()).getValue().toString()).getMinutes();
datArray[0][13] = new Date(ws.getRange("M"+row.toString()).getValue().toString()).getHours();
datArray[0][14] = new Date(ws.getRange("M"+row.toString()).getValue().toString()).getMinutes();
datArray[0][15] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getTime();
datArray[0][16] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getFullYear();
datArray[0][17] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getMonth();
datArray[0][18] = new Date(ws.getRange("N"+row.toString()).getValue().toString()).getDate();
for(var i = 0; i < 19; i++){
if(datArray[0][i] == ""){if(i > 9){datArray[0][i] = 0;} else{datArray[0][i] = "nil";} }
if(i < 18){csv += '"' + datArray[0][i] + '"' + ",";}
else{ csv += '"' + datArray[0][i] + '"'; }
}
Logger.log("A " + csv);
Logger.log(csv + "\n" + datArray[0].join(","));
csvFile = csv;
return csvFile;
}
catch(err) {
Logger.log("C" + err);
Browser.msgBox(err);
}
}
You mention in your comment on my answer that you are using onEdit to trigger the script. Since this is a Simple Trigger, your current approach will not work. When you use simple triggers to run an Apps Script, it runs in a sandbox with reduced permissions.
See: https://developers.google.com/apps-script/guides/triggers/#restrictions
The best I can recommend is create a custom menu option with a UI popup asking for the row number to export. If the code is triggered from a menu by the user, it runs with full permission to access that users account.
Depending on your use-case, a scheduled trigger might work too. It could run every 10 minutes or every Hour and export any changes to the spreadsheet. In this case the Apps Script runs as you, with permission to access your account, and the resulting CSV would be created on your drive.
Details on how to create a custom menu: https://developers.google.com/apps-script/guides/triggers/#onopen
Details on how to create a form for the user: https://developers.google.com/apps-script/guides/ui-service
Details on time driven triggers: https://developers.google.com/apps-script/guides/triggers/installable#time-driven_triggers

Save instead of saveAs using excel activeX

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

Jscript ReadLine() related

Can any one please tell me that we use ReadLine() to read a particular line from a file (.txt). Now I want to read the total content of the file (not only the first line). For that what method I need to use. I googled a lot but I cant get the solution.
My Code is given below:
var ForReading = 1;
var TristateUseDefault = -2;
var fso = new ActiveXObject("Scripting.FileSystemObject");
var newFile = fso.OpenTextFile(sFileName, ForReading, true, TristateUseDefault);
var importTXT = newFile.ReadLine();
This is returning the first line of the .txt file by importTXT variable. Now I want to get the total file content in importTXT.
Any suggestion will be very much helpful for me.
You use the ReadAll method:
var importTXT = newFile.ReadAll();
(Don't forget to close the stream when you are done with it.)
Here: ReadAll (msdn)
I found the example given very poor - for example it did not CLOSE the file, so I added this to the msdn page:
function ReadAllTextFile(filename)
{
var ForReading = 1;
var fso = new ActiveXObject("Scripting.FileSystemObject");
// Open the file for input.
var f = fso.OpenTextFile(filename, ForReading);
// Read from the file.
var text = (f.AtEndOfStream)?"":f.ReadAll(); // this is where it is read
f.Close();
return text;
}
var importTXT = ReadAllTextFile(sFileName);

Categories

Resources