I would like to import an excel file into javascript.
I already have got a code that works (kind of).
This is my code:
function GetData(cell,row){
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("U:\\File1.xls");
var excel_sheet = excel.Worksheets("Sheet1");
var data = excel_sheet.Cells(cell,row).Value;
return data;
}
The code only works in IE (because of ActiveX), and it is incredibly slow.
Another problem is that it can only get the data from the first 100 rows or so, after that it just loads for hours and I get an ObjectError.
Another way to import excel files, or something that works the same way, would be greatly appreciated.
Updated Code:
Opens the file just once. But now i get an Object Error inside of the try-catch, when i try to run the GetData(i,2) method.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("U:\\Datei.xls");
var excel_sheet = excel.Worksheets("Sheet 1");
function GetData(cell,row){
var data = excel_sheet.Cells(cell,row).Value;
return data;
}
function main(){
try{
for(var i=1; i<5000;i++){
if(text1 == GetData(i,2)){
alert(GetData(i,6));
throw "Entry found";
}
}
}
catch(e) {
alert(e)
}
}
Related
I'm trying to get attachment from Gmail to Google Drive. After create a new file into the folder, I have encountered a problem accessing the new file that script created.
same as the makeCopy Function
err: Exception: The document is inaccessible. Please try again later. at myFunction(Code:21:37)
Appreciated any help and suggestions. Thank you!
function myFunction() {
const files = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxx").getFiles();
while (files.hasNext()){
var file = files.next();
var filename = file.getName();
const aname = "xxxx.docx"
if (filename == aname){
var oldid = file.getId();
var copyfile = file.makeCopy().setName("COPYYYYY");
var newid = copyfile.getId();
}
}
var body = DocumentApp.openById(newid).getBody();
Logger.log(oldid);
Logger.log(newid);
Logger.log(body);
}
Modification points:
In your script, I think that when file of var copyfile = file.makeCopy().setName("COPYYYYY"); is Google Document, the script works. But from your error message and const aname = "xxxx.docx", I thought that you might try to have directly opened the DOCX file using DocumentApp.openById. If it's so, the reason of your issue is this.
In order to open the DOCX file using DocumentApp.openById, in the current stage, it is required to convert the DOCX file to Google Document.
When above points are reflected to your script, it becomes as follows.
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
function myFunction() {
const files = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxx").getFiles();
var newid = "";
while (files.hasNext()){
var file = files.next();
var filename = file.getName();
const aname = "xxxx.docx";
if (filename == aname){
var oldid = file.getId();
if (file.getMimeType() == MimeType.MICROSOFT_WORD) {
var copyfile = Drive.Files.copy({title: "COPYYYYY"}, oldid, {convert: true});
newid = copyfile.id;
}
}
}
if (newid) {
var body = DocumentApp.openById(newid).getBody();
Logger.log(oldid);
Logger.log(newid);
Logger.log(body);
}
}
In this modified script, the DOCX file is converted by the method of "Files: copy" of Drive API.
Reference:
Files: copy
I’m trying to attach a file to an email I send in Google Apps Script with MailApp.sendEmail(). In the browser JavaScript I read in the file manually with this code because I’ve already processed the equivalent of the submit button in my HTML form, and it works:
var file = document.getElementById('myfile');
var fileInfo = [];
if(file.files.length) // if there is at least 1 file
{
if (file.files[0].size < maxEmailAttachmentSize) // and its size is < 25M
{
var reader = new FileReader();
reader.onload = function(e)
{
fileInfo[0] = e.target.result;
};
reader.readAsBinaryString(file.files[0]);
fileInfo[1] = file.files[0].name;
fileInfo[2] = file.files[0].type;
fileInfo[3] = file.files[0].size;
}
console.log(fileInfo); // here I see the full file and info. All looks correct.
}
Then I send it up to the server.
google.script.run.withSuccessHandler(emailSent).sendAnEmail(fileInfo);
On the server I pull out the fields and send the email like so:
var fname = fileInfo[1];
var mimeType = fileInfo[2];
var fblob = Utilities.newBlob(fileInfo[0], mimeType, fname);
// all looks right in the Logger at this point
try {
GmailApp.sendEmail(emaiRecipient, emailSubject, emailBody,
{
name: 'Email Sender', // email sender
attachments: [fblob]
}
);
catch …
This works fine when the file is a text file or HTML file but doesn’t when the file is anything else. The file is sent but it's empty and apparently corrupt. Can anyone see what’s wrong with this code? (It doesn’t work with MailApp.sendEmail() either.) I did see in another stackoverflow post that the document has to be saved once, but that is something I definitely don’t want to do. Isn’t there any other way? What am I missing?
Modification points:
FileReader works with the asynchronous process. This has already been mentioned by Rubén's comment.
In the current stage, when the binary data is sent to Google Apps Script side, it seems that it is required to convert it to the string and byte array. This has already been mentioned by TheMaster's comment.
In order to use your Google Apps Script, in this case, I think that converting the file content to the byte array of int8Array might be suitable.
For this, I used readAsArrayBuffer instead of readAsBinaryString.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML&Javascript side:
// Added
function getFile(file) {
return new Promise((resolve, reject) => {
var reader = new FileReader();
reader.onload = (e) => resolve([...new Int8Array(e.target.result)]);
reader.onerror = (err) => reject(err);
reader.readAsArrayBuffer(file);
});
}
async function main() { // <--- Modified
var file = document.getElementById('myfile');
var fileInfo = [];
if(file.files.length) {
if (file.files[0].size < maxEmailAttachmentSize) {
fileInfo[0] = await getFile(file.files[0]); // <--- Modified
fileInfo[1] = file.files[0].name;
fileInfo[2] = file.files[0].type;
fileInfo[3] = file.files[0].size;
}
console.log(fileInfo); // here I see the full file and info. All looks correct.
google.script.run.withSuccessHandler(emailSent).sendAnEmail(fileInfo);
}
}
Although I'm not sure about your whole script from your question, at the modified script, it supposes that main() is run. When main() is run, the file is converted to the byte array and put it to fileInfo[0].
At Google Apps Script side, from fileInfo, var fblob = Utilities.newBlob(fileInfo[0], mimeType, fname); has the correct blob for Google Apps Script.
Google Apps Script side:
In this modification, your Google Apps Script is not modified.
References:
FileReader
FileReader.readAsArrayBuffer()
Added:
This code looks good but we can't use it because we are running on the Rhino JavaScript engine, not V8. We don't have support for newer JavaScript syntax. Could you give us an example of how it's done with older syntax? Ref
From your above comment, I modified as follows.
Modified script:
HTML&Javascript side:
function main() {
var file = document.getElementById('myfile');
var fileInfo = [];
if(file.files.length) {
if (file.files[0].size < maxEmailAttachmentSize) {
var reader = new FileReader();
reader.onload = function(e) {
var bytes = new Int8Array(e.target.result);
var ar = [];
for (var i = 0; i < bytes.length; i++) {
ar.push(bytes[i]);
}
fileInfo[0] = ar;
fileInfo[1] = file.files[0].name;
fileInfo[2] = file.files[0].type;
fileInfo[3] = file.files[0].size;
console.log(fileInfo); // here I see the full file and info. All looks correct.
google.script.run.withSuccessHandler(emailSent).sendAnEmail(fileInfo);
}
reader.onerror = function(err) {
reject(err);
}
reader.readAsArrayBuffer(file.files[0]);
}
}
}
Google Apps Script side:
In this modification, your Google Apps Script is not modified.
Protractor Query: our application generate a excel file which contains aome formulas. Now until I don't open the excel, it won't readable by exceljs. Is there any way I can open the excel and close it like we do robot in selenium?
Please Note that if i Open the file and keep at specified location below code works fine, but when i download the same from application and try to read it it wont work.
function compareExcelFromScreen(VerificationSection, file, row, column, SheetName, callback) {
var wrkbook = new Excel.Workbook();
var valFromExcel = null;
var filteredExcelValue = null;
var filteredScreenvalue = null;
var temp = null;
wrkbook.xlsx.readFile(file.toString()).then(function () {
var worksheet = wrkbook.getWorksheet(SheetName);
valFromExcel = worksheet.getRow(parseInt(row)).getCell(parseInt(column)).value;
}
}
I have a function where I need to write a value in an excel file at a specific row.
var Excel = require('exceljs');
setExcelData: function (sheetName, keyword, value123, callback) {
var workbook = new Excel.Workbook();
workbook.xlsx.readFile('example.xlsx').then(function () {
var worksheet = workbook.getWorksheet(sheetName);
var y = worksheet.getColumn(1).values;
for (var i = 1; i <= y.length; i++) {
var q = worksheet.getRow(i).values;
if (q[1] == keyword) {
worksheet.getRow(i).getCell(2).value = value123;
workbook.xlsx.writeFile('example.xlsx');
break;
}
}
});
callback();
},
First I read the file and find the row where the keyword is present in first column. Then I try to write "value123" in the second column of the same row. But when i execute this function, the excel file gets corrupted and I cannot open it anymore.
I faced the same issue in Ubuntu if I am modifying the file in LibreOffice. So i created a doc in google drive as suggested in
https://github.com/guyonroche/exceljs/issues/35#issuecomment-283440743. and downloaded to perform modification on excel
Below is the code worked for me.
var Excel = require('exceljs');
async function excelOp() {
let workbook = new Excel.Workbook();
workbook = await workbook.xlsx.readFile('question_50508131.xlsx'); // replace question_50508131.xls with your file
let worksheet = workbook.getWorksheet('Inventory'); // replace solution with youe sheet name
let columnValues = worksheet.getColumn(1).values;
for (let row = 1; row <= columnValues.length; row += 1) {
var rowValues = worksheet.getRow(row).values;
if (rowValues[1] == 'Laptop') { // replace Laptop with required value
worksheet.getRow(row).getCell(2).value = 350; // replace 350 with replacable value
workbook.xlsx.writeFile('question_50508131.xlsx');
break;
}
}
}
excelOp();
PreModification Excel data
PostModification Excel data
I know this types of question doesn't belong to here but this is my last hope to get answer and solution for this. I had made a html and javascript program to read excel file through Active X, but problem is that whenever I run that page the it runs fine but when i closed it the excel file remain open and if I run this page 100 times and then close it then there will be 100 unclosed excel file which leads to slowdown my PC. And second problem is that when I try to open that excel file which is being used by that application(the application is not currently running when i tried to open excel file) it does not open without giving an error,an window of excel file open and closed with in a small part of second..I don't know what to do to resolve this. If there is any problem in my code then here it is
var xVal = 1;
var yVal = 2
function readdata(x,y) {
x = xVal;
y = yVal;
try {
var excel = new ActiveXObject("Excel.Application");
excel.Visible = false;
var excel_file = excel.Workbooks.Open("D:\\Test1.xls");// alert(excel_file.worksheets.count);
var excel_sheet = excel_file.Worksheets("Sheet1");
var data = excel_sheet.Cells(x, y).Value;
//alert(data);
drawWithexcelValue(data);
xVal = xVal + 1;
}
catch (ex) {
alert(ex);
}
}
this is the code through which I am reading the excel file.
Try
data = null;
excel_sheet = null;
excel_file.Close(); // important
excel_file = null;
excel.Quit();
excel = null;
in this (reverse) order. This is (almost) equivalent to setting these values to Nothing in VBA.