TypeError: Cannot read property 'getRow' of undefined - protractor

Tried with
cellValue= worksheet.getRow(1).getCell(1).value;
and
cellValue=console.log(worksheet.getCell('A1'))
please find below my code :
cellread2=function(){
var Excel;
var filePath = path.resolve(__dirname,'E:/excel.xlsx');
if (typeof require !== 'undefined') {
Excel = require('C:/Users/user/AppData/Roaming/npm/node_modules/exceljs/dist/exceljs');
}
var wb = new Excel.Workbook();
console.log(wb);
wb.xlsx.readFile(filePath);
var worksheet = wb.getWorksheet('Sheet1');
//cellValue= worksheet.getRow(1).getCell(1).value;//Error :TypeError: Cannot read property 'getRow' of undefined
cellValue=console.log(worksheet.getCell('A1'))// TypeError: Cannot read property 'getCell' of undefined
console.log(cellValue);
}

There is a problem with the existing library code. If you want to make it work you will have to make few changes in the existing code in file AppData\Roaming\npm\node_modules\exceljs\dist\es5\xlsx\xform\sheet\worksheet-xform.js. Replace the code at line 284 with the following :
if (drawing.anchors && drawing.anchors.length > 0) {
drawing.anchors.forEach(function (anchor) {
if (anchor.medium && anchor.range) {
var image = {
type: 'image',
imageId: anchor.medium.index,
range: anchor.range
};
model.media.push(image);
}
});
}
And as for the code for reading the file use the following code.
Note: I installed exceljs library globally and I am using version 4.6.1
var path = require('path');
var Excel = require('exceljs');
var cellread2 = function () {
var filePath = path.resolve('E:', 'excel.xlsx');
var wb = new Excel.Workbook();
wb.xlsx.readFile(filePath).then(function (data) {
var worksheet = wb.getWorksheet('Sheet1');
var cellValue = worksheet.getRow(1).getCell(1).value;
console.log('cellValue', cellValue);
}).catch(function (e) {
console.log(e);
});
}
cellread2();

It may occurs due to objects are mapped into the excel sheet instead of textual data.
Please create another excel sheet and check it again will resolve this issue.'
Sample code to read excel sheet using node.js is given below,
var Excel = require('exceljs');
var wb = new Excel.Workbook();
var path = require('path');
var filePath = path.resolve(__dirname,'sample.xlsx');
wb.xlsx.readFile(filePath).then(function(){
var sh = wb.getWorksheet("Sheet1");
sh.getRow(1).getCell(2).value = 32;
wb.xlsx.writeFile("sample2.xlsx");
console.log("Row-3 | Cell-2 - "+sh.getRow(3).getCell(2).value);
console.log(sh.rowCount);
//Get all the rows data [1st and 2nd column]
for (i = 1; i <= sh.rowCount; i++) {
console.log(sh.getRow(i).getCell(1).value);
console.log(sh.getRow(i).getCell(2).value);
}
});

In my case the sheet name did not match with 'Sheet1', since I was modifying an existing excel file. Replacing the sheet name resolved the issue.

Related

doGet failed on google addon script file

I am trying to trace email status with using inline image in an email.
For getting response i am using following code.
// handles the get request to the server
function doGet(e) {
Logger.log(e.parameter);
var method = e.parameter['method'];
switch (method) {
case 'track':
var email = e.parameter['email'];
updateEmailStatus(email);
default:
break;
}
}
function updateEmailStatus(emailToTrack) {
// get the active spreadsheet and data in it
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet = SpreadsheetApp.openById(id).getActiveSheet();
var data = sheet.getDataRange().getValues();
// get headers
var headers = data[0];
var emailOpened = headers.indexOf('status') + 1;
// declare the variable for the correct row number
var currentRow = 2;
// iterate through the data, starting at index 1
for (var i = 1; i < data.length; i++) {
var row = data[i];
var email = row[0];
if (emailToTrack === email) {
// update the value in sheet
sheet.getRange(currentRow, emailOpened).setValue('opened');
break;
}
currentRow++;
}
}
Here is the sheet
it works in a stand alone file but not working in a addon script project. Is there any way to trace out the send email using apps script ?
Any help on this issue will be highly appreciated. Thank you
I have solved the issue. I have change the code little bit and create a new draft as more than one inline image was added to the existing draft.
The change is here
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Email_Status');
After this few changes i deployed as new webapp and it started working. Thank you for contribution
Try this:
//var id = SpreadsheetApp.getActiveSpreadsheet().getId(); remove this
var sheet = SpreadsheetApp.openById(id);//change this by hardcoding the id

Corrupt records from OpenXML Spreadsheet creation

I'm trying to generate a simple XLSX file using OpenXML but I'm getting an error when I open my file and the only info in the repairedRecord part of the log file is this:
Repaired Records: Cell information from /xl/worksheets/sheet1.xml part
The strange thing is that all the cells I'm trying to write do have the value I expect them to have. I'm just trying to write a single header row right now, where the headers is just an IEnumerable<string>:
using (var doc = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook)) {
var workbookPart = doc.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
var worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
worksheetPart.Worksheet = new Worksheet();
var sheets = workbookPart.Workbook.AppendChild(new Sheets());
var sheet = new Sheet {
Id = workbookPart.GetIdOfPart(worksheetPart),
SheetId = 1,
Name = "Sheet 1"
};
sheets.Append(sheet);
workbookPart.Workbook.Save();
var sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());
var row = new Row { RowIndex = 1 };
var column = 1;
foreach (var header in headers)
row.AppendChild(new Cell {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.SharedString,
CellValue = new CellValue(header)
});
sheetData.Append(row);
workbookPart.Workbook.Save();
}
If you're inserting a string value, you should be using CellValues.InlineString
foreach (var header in headers)
row.AppendChild(new Cell (new InlineString(new Text(header))) {
CellReference = GetColumnLetter(column++) + "1",
DataType = CellValues.InlineString
});

Protractor e2e testing

I am writing Protractor e2e testing .I need to Dynamically read the values from Excel .Can anyone help me out from this..
Inititally add xlsjs to node, and then try this code
var sheetNumber = 0;
//Define file Path name
var path = require('path');
var fileNamePath = path.resolve(__dirname, 'E:/excel.xls');
//NodeJs read file
var XLS;
if (typeof require !== 'undefined') {
XLS = require('E:/node/node_modules/xlsjs');
}
//Working with workbook
var workbook = XLS.readFile(fileNamePath);
var sheetNamelist = workbook.SheetNames;
var value = workbook.Sheets[sheetNamelist[sheetNumber]][cellId].v;
In the above sheet number means, in the Excel sheet your data is located in which sheet and cellId is in that sheet which shell data do you want. your data was stored in the variable value, you can use that data in any type.

epplus dispose don't work

I open with epplus an excel file.
After reading some data, I would like to close the package:
pck.Stream.Close()
pck.Dispose()
Unfortunatelly the excel file is still blocked. I need to close the whole application to get the excel file unlocked.
I have googled, but found nothing useful except the above.
How are you opening the file? The following creates, saves, reopens, prints, and finally deletes all withing the same thread without issue. I can even set a breakpoint anywhere and delete the file. Reading the file this way should not lock the file since it is pulled into memory:
[TestMethod]
public void OpenReopenPrintDeleteTest()
{
//Create some data
var existingFile = new FileInfo(#"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
workbook.Worksheets.Add("newsheet");
package.Save();
}
using (var package = new ExcelPackage(existingFile))
{
var workbook = package.Workbook;
var worksheet = workbook.Worksheets.First();
//The data
worksheet.Cells["A1"].Value = "Col1";
worksheet.Cells["A2"].Value = "sdf";
worksheet.Cells["A3"].Value = "ghgh";
worksheet.Cells["B1"].Value = "Col2";
worksheet.Cells["B2"].Value = "Group B";
worksheet.Cells["B3"].Value = "Group A";
worksheet.Cells["C1"].Value = "Col3";
worksheet.Cells["C2"].Value = 634.5;
worksheet.Cells["C3"].Value = 274.5;
worksheet.Cells["D1"].Value = "Col4";
worksheet.Cells["D2"].Value = 996440;
worksheet.Cells["D3"].Value = 185780;
package.Save();
}
//Reopen the file
using (var package = new ExcelPackage(existingFile))
{
var workBook = package.Workbook;
if (workBook != null)
{
if (workBook.Worksheets.Count > 0)
{
var currentWorksheet = workBook.Worksheets.First();
var lastrow = currentWorksheet.Dimension.End.Row;
var lastcol = currentWorksheet.Dimension.End.Column;
for (var i = 1; i <= lastrow; i++)
for (var j = 1; j <= lastcol; j++)
Console.WriteLine(currentWorksheet.Cells[i, j].Value);
}
}
}
//Delete the file
existingFile.Delete();
}
I was having the same problem... But I found the solution:
During the "SaveAs" method, I was creating a FileStream that was not being disposed.
Before:
ExcelPackage excel_package = new ExcelPackage(new MemoryStream());
//...
//Do something here
//...
excel_package.SaveAs(new FileStream("filename.xlsx", FileMode.Create));
excel_package.Dispose();
After:
ExcelPackage excel_package = new ExcelPackage(new MemoryStream());
//...
//Do something here
//...
var file_stream = new FileStream("filename.xlsx", FileMode.Create);
excel_package.SaveAs(file_stream);
file_stream.Dispose();
excel_package.Dispose();
Note that the Memory Stream opened during the ExcelPackage declaration was not explicitly disposed, because the last command "excel_package.Dispose()" already does this internally.
Hope it help.
c# excel epplus

How can I delete a row from a Table in SAPUI5 Application when I used Model as XMLModel?

I have created SAPUI5 application, in that I have loaded data from external .xml file into a table, it was fine. Now, I am trying to delete a specific row from that table.
For this purpose, I use this code:
var oModel = new sap.ui.model.xml.XMLModel();
oModel.loadData("Deployments.xml", "", false);
sap.ui.getCore().setModel(oModel);
oTable.bindRows("/service"); // here "service" is the root element of xml file
var oTable = new sap.ui.commons.Button({
text: "Delete Service",
press: function() {
var idx = oTable.getSelectedIndex();
if (idx !== -1) {
var m = oTable.getModel();
var data = m.getData();
var removed = data.splice(idx, 1); // error showing at this line
m.setData(data);
sap.m.MessageToast.show(JSON.stringify(removed[0]) + 'is removed');
} else {
sap.m.MessageToast.show('Please select a row');
}
}
});
But, I am getting error at the line: var removed = data.splice(idx, 1);. However, the same code is good for when model is JSON. How can I delete a specific row from a table when model XMLModel?
It is a lot easier an more reliable to use a Bindings BindingPath to manipulate data belonging to a particular binding. Here is your adapted sample for a XMLModel:
press: function() {
var iIdx = oTable.getSelectedIndex();
var sPath = oTable.getContextByIndex(iIdx).getPath();
var oObj = oTable.getModel().getObject(sPath);
oObj.remove();
oTable.getModel().refresh();
}
This way you save the hazzle of dealing with the XML structure and furthermore this will scale with any change in the binding path you might introduce in the future.
BR
Chris
var data = m.getData();
data is not an Array. It is a XML document.
To remove an entry from the document:
var root = data.childNodes[0];
var aEntry = root.getElementsByTagName("entry");
root.removeChild(aEntry[idx]);