I have existing codes that work to get a particular cell from an excel sheet.
is that possible to read particular content within the cell?
excel reader:
public String ReadCellData(int vRow, int vColumn)
{
String value=null; //variable for storing the cell value
Workbook wb=null; //initialize Workbook null
try
{
//reading data from a file in the form of bytes
FileInputStream fis=new FileInputStream(RunConfiguration.getProjectDir() + "/Data Files/testmatrix.xlsx");
//constructs an XSSFWorkbook object, by buffering the whole stream into the memory
wb=new XSSFWorkbook(fis);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e1)
{
e1.printStackTrace();
}
Sheet sheet=wb.getSheetAt(0); //getting the XSSFSheet object at given index
Row row=sheet.getRow(vRow); //returns the logical row
Cell cell=row.getCell(vColumn); //getting the cell representing the given column
//value=cell.getStringCellValue(); //getting cell value
//return value; //returns the cell value
}
}
codes to get and print data
//read excel cell C11, ignore first row column A1. (int vRow, int vColumn)
def exceldata = CustomKeywords.'test.readexcel.ReadCellData'(11, 2)
String jsondata = JsonOutput.prettyPrint(exceldata.toString())
println(jsondata)
WebUI.delay(1)
//call the object and post the above data as API HTTP request body
def post = ((findTestObject('Object Repository/Web Service Request/test-service/Post')) as RequestObject)
post.setBodyContent(new HttpTextBodyContent(jsondata))
WebUI.delay(2)
//POST and verification
def response = WS.sendRequestAndVerify(post)
println(response.statusCode)
assert response.getStatusCode() == 201
excel data at Cell C11
I want to get the value of key testId.
{
"testId": "test123",
"created": "2020-02-06T17:02:39.257Z",
}
You will need to parse the response:
def parsedResponse = new JsonSlurper().parseText(response.getResponseText())
println parsedResponse.get("testId")
(don't forget to import groovy.json.JsonSlurper)
Related
I'm trying to save list of user defined object in excel i.e .xlsx format from a REST API. which creates a XSSFWorkbook and stores the data in workbook. returns ByteArrayInputStream. In my Entity class i'm storing it as
#Column(name = "created_date", columnDefinition = "timestamp with time zone")
#Temporal(TemporalType.TIMESTAMP)
private Date createdDate;
Here is piece of code for writing list to Workbook in service.
XSSFWorkbook workbook = new XSSFWorkbook();
// Create a blank sheet
XSSFSheet sheet = workbook.createSheet("Survey");
String[] columns = {"Name","createdDate"};
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int rownum = 1;
for (Integer key : keyset) {
// this creates a new row in the sheet
Row row = sheet.createRow(rownum++);
Survey survey = data.get(key);
row.createCell(0).setCellValue(survey.getName());
row.createCell(1).setCellValue(survey.getCreatedDate());
}
try {
workbook.write(outputStream);
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}finally {
workbook.close();
}
return new ByteArrayInputStream(outputStream.toByteArray());
In the controller i'm setting the header contentType and content-disposition and returning as ResponseEntity.
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Content-Disposition", "attachment; filename=" + "AuditTrial.xlsx");
return ResponseEntity.ok().headers(headers).body(isr);
Actual data is given below, i.e data coming from the database
[{
"createdDate": "2019-07-15T07:45:48.555Z",
"name": "abc"
},{
"createdDate": "2019-07-15T07:45:48.555Z",
"name": "xyz" }]
problem is when i tried to open excel which will be produced after calling the above api,the date format is not proper. it is as below.
How to save the date in proper format in excel ? where i'm getting it wrong. Any helps and suggestions welcomed.
Your entity is not related to apache poi's cell.
In your entity's createdDate you are setting that it is a timestamp but it tells nothing to apache poi.
When you want to create a date cell you need to:
create a CellStyle
set date format for that CellStyle
apply that CellStyle to the desired Cell(s)
For example:
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
...
for (Integer key : keyset) {
// this creates a new row in the sheet
Row row = sheet.createRow(rownum++);
Survey survey = data.get(key);
row.createCell(0).setCellValue(survey.getName());
Cell dateCell = row.createCell(1);
dateCell.setCellStyle(cellStyle);
dateCell.setCellValue(survey.getCreatedDate());
}
I'm using the XLSXReader to read an Excel file, but it is failing to read the first row. I need to read the first row since it contains data and not headers.
Using test data, I put in a blank first row, but it still skipped the first row with data:
I copied the first row and duplicated it and it read the row:
I don't know why it is automatically skipping the first row.
Here is the action button code that imports the file, saves it, and reads it:
public PXAction<PMProject> importCostBudget;
[PXButton(CommitChanges = true)]
[PXUIField(DisplayName = "Import Cost Budget")]
protected void ImportCostBudget()
{
if (ImportCostBudgetView.AskExt() == WebDialogResult.OK)
{
const string PanelSessionKey = "ImportCostBudget";
PX.SM.FileInfo info = (PX.SM.FileInfo)PX.Common.PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[PanelSessionKey];
Byte[] bytes = info.BinData;
System.Web.HttpContext.Current.Session.Remove(PanelSessionKey);
if (info != null)
{
PXNoteAttribute.AttachFile(Base.Project.Cache, Base.Project.Current, info);
using (PX.Data.XLSXReader reader = new XLSXReader(bytes))
{
//List<PMCostBudget> costBudgets = new List<PMCostBudget>();
reader.Reset();
//This is to read the first row
RowRead(reader);
while (reader.MoveNext())
{
RowRead(reader);
}
}
}
}
}
Is there a way I can force read the very first row using the reader?
Header row is likely treated as a special case intended for reading column names.
You should be able to access it from the XLSXReader IndexKeyPairs collection:
public IDictionary<int, string> IndexKeyPairs
{
get { return _header; }
}
I am Using Selenium WebDriver and reading Data from a excel sheet that contains
Username and Password but the problem is this sheet contains both numeric Values and String Values due to which its throwing error:
Cannot get a STRING value from a NUMERIC cell
Username: rainrrr , shamz, tabraiz
Password: rainrrr ,123456,123456
Please Help
public void AdminLogin(String UserName, String Password) throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\amomin\\Desktop\\selinium\\chromedriver.exe");
driver =new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("My Path");
driver.findElement(By.xpath(".//*[#id='UserName']")).sendKeys(UserName);
driver.findElement(By.xpath(".//*[#id='Password']")).sendKeys(Password);
driver.findElement(By.xpath(".//*[text()='Submit']")).click();
Thread.sleep(5000);
Assert.assertTrue(driver.getTitle().contains("Dashboard - RainMaker"),"Login Fail");
System.out.println("User Login Successfully");
}
public Object[][] LoginData()
{
libDDT config=new libDDT("C:\\Users\\amomin\\workspace\\DataDrivenTest\\TestData\\TestData.xls");
int rows=config.getRowCount(0);
Object[][] data = new Object[rows][2];
for(int i=0;i<rows;i++)
{
data[i][0]=config.getdata(0, i, 0);
data[i][1]=config.getdata(0, i, 1);
}
return data;
}
Try this by saving Numeric values in text format.
If the string is starting with number, in excel, format data as text by prefixing numeric value with single quotation ('). Ex: 123 as '123
I have the following code which writes data to the CSV file.
But instead of writing the headers each in different cell it writes all in the same cell.
When i change to "UTF-8" it works fine but writs "Gibberish" instead of correct letters when opened in Office Excel.
CSVWriter csvWrite = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file),
"UTF-16"), CSVWriter.DEFAULT_SEPARATOR ,CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
//Add Columns headers to the excel file
String columnHeaders[] = {"אאא","בבב","גגג"};
csvWrite.writeNext(columnHeaders);
//Collect Data
ArrayList<String[]> listData = collectDataFromDBToList();
//Write/Add all line from list to the csv file
csvWrite.writeAll(listData);
csvWrite.close();
Received output
Wanted output
Thank phoenix but it did not helped.
I found the solution :) , it was just to use tab separator instead of the default one.
use: '\t' instead of CSVWriter.DEFAULT_SEPARATOR
CSVWriter csvWrite = new CSVWriter(new OutputStreamWriter(new FileOutputStream(file),
"UTF-16"),'\t' ,CSVWriter.NO_QUOTE_CHARACTER,
CSVWriter.DEFAULT_ESCAPE_CHARACTER, CSVWriter.DEFAULT_LINE_END);
Here is this code that i wrote for a project..the values outside for loop ( "WSDL Name" and "Tags" are the column header and list will contain values to be inserted). It will generate test.csv
import java.io.FileWriter;
import java.io.IOException;
public class genCSV
{
public static void main(String [] args)
{
generateCsvFile("c:\\test.csv");
}
private static void generateCsvFile(String sFileName)
{
try
{
FileWriter writer = new FileWriter(sFileName);
writer.append("WSDLName");
writer.append("Tags");
writer.append('\n');
for(int i=0;i<list.size();i++){
writer.append(list.getKey);
writer.append(list.getValueForKey);
writer.append('\n');
}
//generate whatever data you want
writer.flush();
writer.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
I am using LWUIT and showing data with Table, say, flight information!
Instead of writing air companies with text I just like to replace them with icons.
So, I need to override protected Component createCell(Object value, final int row, final int column, boolean editable) method of Table.
This is how I've implemented:
Initializing
imgAln[i]=null;
try {
imgAln[i] = Image.createImage(strPathToImage[i]);
//e.g /uta.png,/somonair.png and so on
lAln[i] = new Label(imgAln[i]);
} catch (IOException e) { }
Creating Table object
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
final Component c = super.createCell(value, row, column, editable);
if (column == 6) {
return lAln[value]; //it does not work here
}
}
};
need help to add Image to table cell!!!
Is there any example??? links are welcome!
The problem in your createCell(...) implementation is that it does not return the super.createCell(...) when the column is not 6. Also your array of labels (lAln) may not be properly created. Try my implementation below, but make sure you store the appropriate image name in the table models' column 0.
This should solve it:
TableModel model = new DefaultTableModel(
new String[]{"Uneditable", "Editable", "CheckBox", "Multiline"},
new Object[][]{
{"/animations.png", "", new Boolean(false), "Multi-line text\nright here"},
{"/buttons.png", "", new Boolean(true), "Further text that\nspans lines"},
{"/dialogs.png", "", new Boolean(true), "No span"},
{"/fonts.png", "", new Boolean(false), "Spanning\nFor\nEvery\nWord"},
});
Table table = new Table(model) {
protected Component createCell(Object value, final int row,
final int column, boolean editable) {
if (row != -1 && column == 0) {
try {
//In my case Column 0 store the resource path names
return new Label(Image.createImage((String)value));
} catch (Exception ex) {
ex.printStackTrace();
}
}
return super.createCell(value, row, column, editable);
}
};
NOTE: If you see the names instead of images in column 0 it means the image path is incorrect, fix it to see the images.
Did you manage to have a look at TableLayoutDemo.java in project LWUITDemo? If i remember it correct, this comes bundled download package LWUIT1.5.zip (or you can always google it).
Let me know if you need more specific help.