how to open excel using javascript - javascript

I tried the below code to open excel file using javascript.
I tried in IE, Chrome, and Firefox but it's not opening the file.
<html>
<body>
<form name="form1">
<input type=button onClick="test()" value="Open File">
<br><br>
</form>
<script type="text/javascript">
function test() {
var Excel = new ActiveXObject("Excel.Application");
Excel.Visible = true;
Excel.Workbooks.Open("teste.xlsx");
}
</script>
</body>
</html>
Thanks in Advance!

Try using Absolute Path of the file you are trying to open
eg:
Excel.Workbooks.Open("E:\\test.xlsx");

ActiveXObject is only supported by IE, other browsers don't support it.
Excel.Workbooks.Open("teste.xlsx");
There is no path specified for teste.xlsx, provide appropriate file path. The file should be accessed by the browser in the client system, so path should be set accordingly like C:\\Temp\\teste.xlsx (something similar with appropriate system drive).

Related

Google Apps Script file upload (by HTML form) only works when script is "bound" (when standalone script tested, HTTP 403 error)

To upload a local file to Google Drive, I have an HTML <form></form> (see code below) that displays in a modal overtop a Google Sheet the user has open. The HTML form has <input type="file" name="..."> in it, and when I click to send the form object, I successfully upload the file if this Google Apps Script is "bound" to a specific Sheets file (and was written using the Tools > Script Editor... menu).
If I save the script as a standalone script and then test it (installed and enabled) on a Sheets file of my choosing, then the <form>'s onclick action and the attempt to call google.script.run.aServerFunction(...) causes a "NetworkError: Connection failure due to HTTP 403". To clarify this is what I mean by creating a standalone script and testing it on a Sheets file: https://developers.google.com/apps-script/add-ons/#understand_the_development_cycle. In earlier code iterations I alternatively got a authorization scriptError of some kind. Same error when script is published privately for testers to use on a Sheet. Unfortunately, I think I need this as a standalone script that is later publishable as an add-on- not a side script bound to a single Sheet using the Tools > Script Editor... menu.
My first post to Stack Overflow- please forgive any jargon or typography mistakes, and thank you!
HTML adapted from tutorials:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" name="myFile">
<input type="submit" value="Upload File"
onclick="google.script.run.withFailureHandler(failed)
.uploadFiles(this.parentNode);
return false;">
</form>
<div class="response"></div>
</body>
</html>
In the code.gs:
function uploadFiles(formObject) {
/*var sheet1 = SpreadsheetApp.getActiveSheet();
sheet1.setActiveRange(sheet1.getRange(2, 2, 4, 4));
var formBlob = formObject.myFile;
var driveFile = DriveApp.createFile(formBlob);
driveFile.addEditor("...");
SpreadsheetApp.getActive().toast(driveFile.getUrl());
sheet1.getRange(1,1,1,1).setValue(driveFile.getUrl());
return driveFile.getUrl();*/
return "it worked";
}
I believe the reason you are getting the HTTP 403 error is because form DOM elements are illegal arguments in google.script.run.myfunction(...) in sheet addons. Even though they are mentioned here as legal parameters here, I think add-on have the added restriction of not being able to pass any kind of DOM elements.
The solution I came up with is to convert the uploaded file to base64 encode string using Filereader.readAsDataUrl() function in native javascript and passing the string to google script and converting it back to a file to be uploaded into google drive.
The base64 encode string starts like this:
data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTG....
GAS
function uploadFiles(formObject) {
// extract contentType from the encoded string
var contentType = formObject.split(",")[0].split(";")[0].split(":")[1]
// New Blob(data,contentType,name)
// Use base64decode to get file data
var blob = Utilities.newBlob(Utilities.base64Decode(formObject.split(",")[1]), contentType, "trial")
var driveFile = DriveApp.getFolderById("your Folder ID here").createFile(blob);
//return contentType, can be anything you like
return blob.getContentType()
}
HTML script
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
</head>
<body>
<form id="myForm">
<label>Your Name</label>
<input type="text" name="myName">
<label>Pick a file</label>
<input type="file" id = "filemy" name="myFile">
<input type="button" value="Upload File"
onclick="upload(this.parentNode)">
</form>
<div class="response"></div>
</body>
<script>
function failed(event) {
$("div.response").text(event);
//google.script.run.selectStuff();
//google.script.host.close();
}
function upload(frmData){
var file = document.getElementById("filemy").files[0]
var reader = new FileReader()
//reader.onload is triggered when readAsDataURL is has finished encoding
//This will take a bit of time, so be patient
reader.onload = function(event) {
// The file's text will be printed here
console.log("File being Uploaded")
//console.log(event.target.result)
google.script.run.withFailureHandler(failed).withSuccessHandler(failed)
.uploadFiles(event.target.result);
};
reader.readAsDataURL(file);
console.log(reader.result)
}
</script>
</html>
Final notes: I have not extensively tested the code, I have got it to work with a pdf file and an image/png file with a Maximun size of 2.6MB. So please try these 2 file types out before going on to further types of file!
Also, files do take a while to upload so be patient(~5-10sec). Especially since there is no progress bar to show the upload progress, it feels like nothing is happening.
Hope that helps!

Get file path on google chrome

I have a problem trying to get the file path on chrome. This is my code with a javascript function:
<html>
<head>
<script language="javascript" type="text/javascript">
function getPath() {
var inputName = document.getElementById('ctrl');
var imgPath;
imgPath = inputName.value;
//alert(imgPath);
var x = document.createElement("INPUT");
x.setAttribute("type", "text");
x.setAttribute("value", imgPath);
document.body.appendChild(x);
}
</script>
</head>
<body>
<input type="file" name ="file1" id="ctrl" webkitdirectory directory multiple/>
<input type="submit" value="Enviar" onclick="getPath()"/>
</body>
</html>
when I press the button, the textfield show me this
C:\fakepath\ART.pdf
I tried to edit the internet explorer settings and it works fine, but I cant get the full path on chrome
Its any way to get the full path on chrome? Thanks
You are using the multiple and directory options so your paths will be avaible under inputName.files
For security reasons these will be relative paths. If you wish to read the files you need to use the FileReader API.
https://developer.mozilla.org/en-US/docs/Web/API/FileReader
I read in the comments that you are trying to save a file to a specific location. This can't be achieved through a browser. You just need to provide the file to be downloaded and the user will decide where to save it. Usually, it will be saved to the OS's default download folder.

Node.js. Working with the real path of local files

I'm new in Node.js and I'm doing a local App with Node.js+HTML5+Javascript with which I would like to move files from one local folder to another local folder. The main functionality of this app is to get a local file "A", read its content, copy this content encrypted in another file "B", and then store "B" in other location and finally delete file "A" in the local system. The problem that I've found is on getting the real path of the first file, and I know that it is difficult to get it (as I've seen in several discussions) for security reasons, but I really need it in order to delete file "A". I realised that with my current code I only can get this real path in IE explorer. The main part of the code involved is the following, in which I'm only able to get the file name in both Firefox and Chrome:
index.ejs:
<!DOCTYPE html>
<html>
<head>
<script src="../scripts/get_file.js"></script>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<form method='get' action='/moveFile'>
<div id="page-wrapper">
<h1>File Browser</h1>
<div>
Select a file:
<input type="file" name="fileInput" id="fileInput">
<input type="submit" value="Upload File"/>
</div>
</div>
</form>
</body>
</html>
get_file.js:
window.onload = function() {
var fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', function(e) {
var file = fileInput.files[0];
});
}
fs_controller.js:
exports.moveFile = function(req,res) {
console.log(req.query.fileInput);
};
I've tried with the following options:
I've seen that bodyparser is only used for express 3.0, and I have
express 4.13.1.
I've tried with Busboy, without results.
I've tried with filepath utility, but it returns the path
where is the main script of the application, so it's not useful for
this case.
Formidable only returns a tmp path.
I've tried with multiparty, and it also returns a tmp path.
The only solution that may be could work is to modify some properties
in Firefox, like
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
and in Chrome, with --allow-file-access-from-files. However, I think
that it's not a clean solution.
I dont know if there are better solutions with Node.js to make this type of app. The main features that I actually need is to work with local files and folders (all types of basic operations with them), and to have a little database for storing the users of the app, and I would like to implement it with a MVC design pattern.
Thanks for your effort!

Running Batch file using Javascript - Firefox

This is important for me as I have a PRN file which can be printed only through command prompt. And I want to delete that file after the print command is given.
So these 2 commands can be executed using batch file only.
And when I try to use activexobject in javascript, my firefox browsers doesnt run it.
<script>
MyObject = new ActiveXObject("WScript.Shell");
function Runbat()
{
MyObject.Run("\"D:\\abc.bat\"");
}
</script>
Together in a html page.
I've found this one and it seems working properly :)
<html>
<head>
<script language="JavaScript" type="text/javascript">
MyObject = new ActiveXObject("WScript.Shell")
function Runbat()
{
MyObject.Run("\"D:\\test.bat\"");
}
</script>
</head>
<body>
<h1>Run a Program</h1>
This script launch the file any bat File<p>
<button onclick="Runbat()">Run bat File</button>
</body>
</html>
Now I don't really know if you are already working with exaclty that solution, if so, and you are still facing this issue in firefox you may need to investigate a little bit more in browser security to know if that is even possible as of this post states that:
No, that would be a huge security breach. Imagine if someone could run
format c:
whenever you visted their website.

how do I get the file content from a form?

How do I get the contents of a file form a HTML form? Here is an example of what I'm working with. All it does it output something like "C:\Fake Path\nameoffile
<html>
<head>
<script type="text/javascript">
function doSomething(){
var fileContents = document.getElementById('idexample').value;
document.getElementById('outputDiv').innerHTML = fileContents;
}
</script>
</head>
<body >
<form name = "form_input" enctype="multipart/form-data">
<input type="file" name="whocares" id="idexample" />
<button type="button" onclick="doSomething()">Enter</button>
</form>
<div id="outputDiv"></div>
</body>
</html>
EDIT:
It seems the solution is difficult to implement this way. What I'm trying to accomplish is sending a file to a python script on my webserver. This is my first time trying this sort of thing so suggestions are welcome. I supposes I could put the python script in my cgi folder and pass the values to it using something like...
/cgi/pythonscript.py?FILE_OBJECT=fileobjecthere&OTHER_VARIABLES=whatever
Would this be a better solution for sending file content to a webserver rather than having javacript open it directly using FileReader?
You can actually do that with the new FileReader Object.
Try this working example
function doSomething()
{
var file = document.getElementById('idexample');
if(file.files.length)
{
var reader = new FileReader();
reader.onload = function(e)
{
document.getElementById('outputDiv').innerHTML = e.target.result;
};
reader.readAsBinaryString(file.files[0]);
}
}
(works with the newest versions of Chrome and Firefox)
yes. Replace line of input as given below, Then it will work :)
<input type="file" ACCEPT="text/html" name="whocares" id="idexample" />
You cannot get the contents of a file in a form without submitting the form to your server.

Categories