Javascript/Excel ActiveX object. Find exact match - javascript

So I am using a SharePoint web part (HTML Form Web Part) that I've built to query an excel file that is hosted on our Sharepoint site. I wrote javascript to create an Excel ActiveX object, and I can search the worksheet just fine.
However, I need to have it search for an exact match (the whole cell) not just part. I know the code that I need, I just can't make it work. I need to find out how to create the correct object type for the "xlWhole" argument of the "Find()" function.
The line of code I am having trouble with is commented out, because that didn't work. Any insight? I've seen the Range.Find method, but I just can't make it work.
var excel = new ActiveXObject("Excel.Application");
var wb = excel.Workbooks.Open("workbook path");
var ws = wb.Worksheets("worksheet name");
var ws = wb.ActiveSheet;
//var cell = ws.Cells.Find(str,excel.XlLookAt.xlWhole);
var cell = ws.Cells.Find(str);
foundRow = cell.Row;

This worked for me:
function searchExcel()
{
var excel =new ActiveXObject("Excel.Application");
excel.visible=true;
var wb = excel.workbooks.open("D:\\Analysis\\tmp\\Book1.xlsx");
var ws = wb.sheets(1);
var str="Value1";
// .Find(What, After, LookIn, LookAt, SearchOrder, SearchDirection,
// MatchCase, MatchByte, SearchFormat)
var cell = ws.Cells.Find(str,ws.Cells(1),-4163,1)
alert(cell?cell.Row:(str+" not found"));
excel.quit();
}
I guess you cannot skip over parameters when using COM from js (but you can leave them off the end).

Related

Copy worksheet to same workbook and rename it using Javascript

I am trying to write a function where a specified workbook is opened and then we need to copy existing sheet and make a copy of it in the same workbook and rename that worksheet.
I saw this feature is implemented In VBA using the code below.
Worksheets("Sheet1").Copy After:=Worksheets("Sheet3")
In Javascript I am trying to do
var xlApp = new ActiveXObject("Excel.Application");
var xlWorkbooks = xlApp.Workbooks;
var xlWorkbook = xlWorkbooks.Open(xlFileName);
var xlWorksheets = xlWorkbook.Worksheets;
var xlWorkSheet = xlObj.getWorksheet("PRC1.1");
xlWorkSheet.copy();
This code is creating a copy in new workbook but I want in the same workbook.
Any Answers would be highly appreciated.
Thanks in Advance.

Retrieving Cell Values from an Excel Spreadsheet using JavaScript

I am looking to retrieve cells from an excel spreadsheet using JavaScript, to use the values in an HTML page. Currently, I do not know how to use SheetJS, and I am not able to use it to parse the worksheets.
What I am looking to do is: Retrieve Cell A1 -> Create a variable with the value of cell A1
Could anyone help me access the worksheet from JS and then get the value from an XLSX sheet? I have to use Excel for the purpose of this project.
Thanks!
function ReadData(cell, row) {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("C:\\RS_Data\\MyFile.xls");
var excel_sheet = excel.Worksheets("Sheet1");
var data = excel_sheet.Cells(cell, row).Value;
document.getElementById('div1').innerText = data;
}
I had the same error.
You should try your path:
excel.Workbooks.Open("C://RS_Data//MyFile.xls");
// --> instead of --> \

How can I modify a javascript event in a PDF file programmatically?

My PDF file has an event attached to a button. I need to be able to modify that event programmatically. I tried this way using iTextSharp, but it didn't change the javascript in the new file:
var pdfReader = new PdfReader(originalPdfDocumentPath);
pdfReader.RemoveUsageRights();
var pdfStamper = new PdfStamper(pdfReader, new FileStream(
newPdfDocumentPath, FileMode.Create, FileAccess.Write, FileShare.None),
'\0', true);
var originalXml = pdfReader.AcroFields.Xfa.DomDocument.InnerXml;
var newXml = originalXml.Replace(
"Table2.Row1.instanceManager.removeInstance(1)",
"Table2._Row1.removeInstance(this.parent.parent.index)");
// Unfortunately, this line does nothing.
pdfStamper.AcroFields.Xfa.DomDocument.InnerXml = newXml;
pdfStamper.Close();
pdfReader.Close();
Any help would be greatly appreciated.
I found that it works if, instead of changing the XML directly, I change the DomDocument and mark the XFA as changed. Below is the corrected code:
var pdfReader = new PdfReader(originalPdfDocumentPath);
pdfReader.RemoveUsageRights();
var pdfStamper = new PdfStamper(pdfReader, new FileStream(newPdfDocumentPath, FileMode.Create, FileAccess.Write, FileShare.None), '\0', true);
var originalXml = pdfReader.AcroFields.Xfa.DomDocument.InnerXml;
var newXml = originalXml.Replace("Table2.Row1.instanceManager.removeInstance(1)", "Table2._Row1.removeInstance(this.parent.parent.index)");
/* New Code */
var doc = new XmlDocument();
doc.LoadXml(newXml);
pdfStamper.AcroFields.Xfa.DomDocument = doc;
pdfStamper.AcroFields.Xfa.Changed = true;
/* End of New Code */
pdfStamper.Close();
pdfReader.Close();
I should note that, even though this code changes the javascript in the PDF file, it also disables the extended features in Adobe Acrobat Reader. You can find more information regarding this here:
http://developers.itextpdf.com/question/why-do-i-get-error-saying-use-extended-features-no-longer-available
"The problem is related to whether or not your document is Reader Enabled. Reader-enabling can only be done using Adobe software. It is a process that requires a digital signature using a private key from Adobe. When a valid signature is present, specific functionality (as defined in the usage rights when signing) is unlocked in Adobe Reader.
You change the content of such a PDF, hence you break the signature."

Solution to map different excel files to db

I have to map a lot of different files with different structures to a db. There is a lot of different tables in those xlsx so I thought about schemeless noSQL approach, but I'm quite newbie in this field.
It should be a microservice with client interface for choosing tables/cells for parsing xlsx files. I do not have strict technology; it could be JAVA, GROOVY, Python or even a JavaScript engine.
Do you know any working solution for doing it?
Here is example xlsx (but I've got also other files, also in xls format): http://stat.gov.pl/download/gfx/portalinformacyjny/pl/defaultaktualnosci/5502/11/13/1/wyniki_finansowe_podmiotow_gospodarczych_1-6m_2015.xlsx
The work you have to do is called ETL (Extract Transform Load). You need to either find a good ETL software (here is a discussion about open source ETL) or to script your own solution in a language you are used with.
The advantage of a ready made GUI software is that you just have to drag and drop data but if you have some custom logic or semi structured data like in your xlsx example, you have limited support.
The advantage of writing your own script is you have all the freedom you need.
I have done some ETL work and I used successfully Groovy for writing my own solution with custom logic and so on, and in terms of GUI I used Altova Mapforce when I had to import some exotic file types.
If you decide to write your own solution you have to:
Convert all data to an easy to load format. In your case you have to convert each xls or xlsx tab to CSV with a naming convention.
Load your files in your chosen language for transforming
Do your logic to put data in a desirable format
Save it in a database (SQL or noSQL)
Maybe you should try Google Sheets to display excel and Google Apps Script (https://developers.google.com/apps-script/overview) to write custom add-on for parsing data to JSON.
Spreadsheet Service (https://developers.google.com/apps-script/reference/spreadsheet/) has plenty methods to access data in sheets.
Next you can send this JSON over API (https://developers.google.com/apps-script/reference/url-fetch/url-fetch-app) or put directly into database (https://developers.google.com/apps-script/guides/jdbc).
Maybe isn't clean, but fast solution.
I had a project that done work almost the same as your problem but it seem easier as I had a fixed structure of xlsx files.
For xlsx parsing, I had experiment with Python and Openpyxl and had no struggle while working with them, they are simple, fast and easy to use.
For database, I recommend using MongoDB, you can deal with documents and collections in MongoDB just as simple as working with JSON objects or a set of JSON objects. PyMongo is the best and recommended way to work with MongoDB from Python I think.
The problem is you have different files with different structures. I cannot recommend anything deeper on this without viewing your data. But you should find the general structure of them or you have to figure out the way to classify them into common sets, each set will be parsed using appropriate algorithm.
Javascript solution, as xlsx2csv (you can make export anywhere):
var def = "1.xlsx";
if (WScript.Arguments.length>0) def = WScript.Arguments(0);
var col = [];
var objShell = new ActiveXObject( "Shell.Application" );
var fs = new ActiveXObject("Scripting.FileSystemObject");
function flush(){
WScript.Echo(col.join(';'));
}
function import_xlsx(file) {
var strZipFile = file; // '"1.xlsx" 'name of zip file
var outFolder = "."; // 'destination folder of unzipped files (must exist)
var pwd =WScript.ScriptFullName.replace( WScript.ScriptName, "");
var i,j,k;
var strXlsFile = strZipFile;
var strZipFile = strXlsFile.replace( ".xlsx",".zip").replace( ".XLSX",".zip");
fs.CopyFile (strXlsFile,strZipFile, true);
var objSource = objShell.NameSpace(pwd+strZipFile).Items();
var objTarget = objShell.NameSpace(pwd+outFolder);
for (i=0;i<objSource.Count;i++)
if (objSource.item(i).Name == "xl"){
if (fs.FolderExists("xl")) fs.DeleteFolder("xl");
objTarget.CopyHere(objSource.item(i), 256);
}
var xml = new ActiveXObject("Msxml2.DOMDocument.6.0");
xml.load("xl\\sharedStrings.xml");
var sel = xml.selectNodes("/*/*/*") ;
var vol = [];
for(i=0;i<sel.length;i++) vol.push(sel[i].text);
xml.load ("xl\\worksheets\\sheet1.xml");
ret = "";
var line = xml.selectNodes("/*/*/*");
var li, line2 = 0, line3=0, row;
for (li = 0; li< line.length; li++){
if (line[li].nodeName == "row")
for (row=0;row<line[li].childNodes.length;row++){
r = line[li].childNodes[row].selectSingleNode("#r").text;
line2 = eval(r.replace(r.substring(0,1),""));
if (line2 != line3) {
line3 = line2;
if (line3 != 0) {
//flush -------------------------- line3
flush();
for (i=0;i<col.length;i++) col[i]="";
}
}
try{
t = line[li].childNodes[row].selectSingleNode("#t").text;
//i = instr("ABCDEFGHIJKLMNOPQRSTUVWXYZ", left(r,1))
i = ("ABCDEFGHIJKLMNOPQRSTUVWXYZ").indexOf(r.charAt(0));
while (i > col.length) col.push("");
if (t == "s"){
t = eval(line[li].childNodes[row].firstChild.text)
col[i] = vol[t];
} else col[i] = line[li].childNodes[row].firstChild.text;
} catch(e) {};
}
flush();
}
if (fs.FolderExists("xl")) fs.DeleteFolder("xl");
if (fs.FileExists(strZipFile)) fs.DeleteFile(strZipFile);
}
import_xlsx(def);

CRUD Excelsheets using Javascript for creation Automation Framework with Protractor

I have worked with Selenium in creating framework for Quality Automation Testing. This was having separate files for Test Cases(Excelsheets file format), Object Map (XML format), ec.
My company has started using AngularJS and I am thinking of creating a similar Quality Automation framework using Protractor.
Since, Protractor is based on Javascript, I am wondering
1. If I can read an excel file using Javascript ?
2. Whats the best way to do so ?
I read few online forums, blogs asking is it server side or client side; suggesting various things like converting it to XML, JSON, blah blah. Also, I found JS XLS and JS XLSX. Its all confusing and wanted insights into this with clear perspective of its use with Protractor / Javascript.
Thanks for your help, suggestions and advices.
Hi please do it like below to read xlsx file via javascript for automating angular based websites using protractor (for more info plz visit https://www.npmjs.com/package/xlsx)
This is my first js file with name excelReader.js
var excelReader = function(){
if(typeof require !== 'undefined')XLSX = require("../path/xlsx"); // path for xlxs directory that you have downloaded via npm
var workbook = XLSX.readFile("C:\\Users\\path\\Desktop\\nameofexcel.xlsx");
var first_sheet_name = workbook.SheetNames[0];
this.Reader = function(cellValue){
var address_of_cell = cellValue;
var worksheet = workbook.Sheets[first_sheet_name];
var desired_cell = worksheet[address_of_cell];
var desired_value = desired_cell.v;
return desired_value;
};
}
module.exports = new excelReader();
and in main test you can use it like below (i have used jasmine data provider)
var DataProvider = require("../path/excelReader.js"); // call the excelReader.js file
var using = require("../path/jasmine-data-provider"); // calling jasmine data provoider if u want u can leave it.
describe("you text suite",function(){
var dataProvider = {
"Case 1 : Valid username and Invalid password" : {UN : DataProvider.Reader("C2"),PWD : DataProvider.Reader("D2")}, // C2 and D2 are excel cell value
};
using(dataProvider, function(Parameter, description) {
xit("your spec file(login example) " + description,function(){
LoginPage.UserName(Parameter.UN); // here i have called the excel value which contains username and password
LoginPage.Password(Parameter.PWD);
LoginPage.SignIn();
});
});
});
hope this helps you in case of any query plz ask.

Categories