How to read Headerless file in Selenium DataSource API? - java

I am using Selenium DataSource API to read excel in my project. I need to read excal as headerless but everytime it taking my first row as header.
Please tell how can i read file excel sheet as headerless file.
Please find Code below
public static void main(String[] args) {
String basePath = "C:\\excel file path";
DataTable table = new DataTable();
table.ImportSheet(basePath+"myTestingFile.xlsx");
System.out.println(Arrays.toString(table.getHeaderValues().toArray()));
for(int i = 1 ; i < table.getRowCount();i++){
table.setRowIndex(i);
System.out.println(table.getValueAt(0));
}
}
Please help me out in this scenario.

Which version you are using right now. Cause in version 0.7, This issue has been fixed.
Now you can use Excel Sheet as Headerless file.
Find the Code below
String basePath = "C:\\excel file path";
DataTable table = new DataTable();
table.setHeaderless();
table.ImportSheet(basePath+"myTestingFile.xlsx");
System.out.println(Arrays.toString(table.getHeaderValues().toArray()));
for(int i = 1 ; i < table.getRowCount();i++){
table.setRowIndex(i);
System.out.println(table.getValueAt(0));
}
Please try with this code.

As per provided code
System.out.println(table.getValueAt(0));
here need to use column name like below
String name = dt.getValueAt("<-Name of Column->");
System.out.println(name);
but used '0' that is the reason why it displaying unexpected results. Please refer doc here

Related

Reading a CSV file into a 2d Array

I've been trying for days to learn how to create this code. It's a homework example. Beginner Java Final Project. I'm about to rip out my hair, if you could guide me a little, I'd appreciate it. I can't seem to figure out how to parse the csv file into a proper 2d array. The delimiter is a ",". I need to maniuplate one column of data (such as the year), but ignore the first (0,0), (0,1), (0,2) row as it only carries the labels I believe. I'm so lost. What I have prints out the first column, but how would I ignore the label at (0,0), and how would I store this information so I could manipulate it in a method? I don't need help on most of the assignment except how to read the values properly and then be able to manipulate them. Thank you.
import java.util.*;
import java.io.*;
public class BasicFileIO{
public static void main (String[] args) {
String fileName = "Crime.csv";
File file = new File(fileName);
try {
Scanner input = new Scanner(file);
while (input.hasNext()) {
String data = input.nextLine();
String[] values = data.split(",");
System.out.println(values[0]);
}
}catch (Exception e) {
System.out.printf("Error");
}
}
}
HERE IS AN IMAGE OF THE CSV FILE. I couldn't upload it. This is how it looks in google docs, but if I open it in atom it's just a file with commas and values (not in cells).
CSV screenshot
You can read and parse scv files with apache commons-csv. Here's an example for reading the columns with this library:
Reader in = new FileReader("path/to/file.csv");
Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(in);
for (CSVRecord record : records) {
String lastName = record.get("Last Name"); // or you can pass the index of column
String firstName = record.get("First Name");
}

Using SQLite in Codename One Application

I have a working sqlite db which I have place in my /src folder.
I then went onto the Codename One website and followed their doc example
Database db = null;
Cursor cur = null;
try {
db = Display.getInstance().openOrCreate("MyDb.db");
if(query.getText().startsWith("select")) {
cur = db.executeQuery(query.getText());
int columns = cur.getColumnCount();
frmMain.removeAll();
if(columns > 0) {
boolean next = cur.next();
if(next) {
ArrayList<String[]> data = new ArrayList<>();
String[] columnNames = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
columnNames[iter] = cur.getColumnName(iter);
}
while(next) {
Row currentRow = cur.getRow();
String[] currentRowArray = new String[columns];
for(int iter = 0 ; iter < columns ; iter++) {
currentRowArray[iter] = currentRow.getString(iter);
}
data.add(currentRowArray);
next = cur.next();
}
Object[][] arr = new Object[data.size()][];
data.toArray(arr);
frmMain.add(BorderLayout.CENTER, new Table(new DefaultTableModel(columnNames, arr)));
} else {
frmMain.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
frmMain.add(BorderLayout.CENTER, "Query returned no results");
}
} else {
db.execute(query.getText());
frmMain.add(BorderLayout.CENTER, "Query completed successfully");
}
frmMain.revalidate();
} catch(IOException err) {
frmMain.removeAll();
frmMain.add(BorderLayout.CENTER, "Error: " + err);
frmMain.revalidate();
} finally {
Util.cleanup(db);
Util.cleanup(cur);
}
However when I run the example and try and execute a simple select query I get this error ...
java.sql.SQLException: [SQLITE_ERROR] SQL error or missing database (no such table: MyTable)
So I have added the DB
I have used the 'openOrCreate' statement
Have I missed a step?
Thanks
Are you shure that you current working directory at execution is ./src ?
Try
db = Display.getInstance().openOrCreate("./src/MyDb.db");
or open with absolute filename:
db = Display.getInstance().openOrCreate("/path/to/src/MyDb.db");
You can try this cn1lib https://github.com/shannah/cn1-data-access-lib
I have used it and it works a charm, except doesn't work for 2 tables in the same query and can't perform delete operations.
Cheers
Thanks for all the input guys.
Unfortunately none of the advice worked for me.
However I did solve it in the end.
It turns out that there is a folder in my home directory called '.cn1/database'. Once I placed the DB into this folder it worked.
Two things:
1] If the db does not exist then it will create it and place it into this directory
2] The db does not show up anywhere in Netbeans (well not that I could see anyway)
Thanks again
From the developer guide:
Some SQLite apps ship with a "ready made" database. We allow you to
replace the DB file by using the code:
String path = Display.getInstance().getDatabasePath(“databaseName”);
You can then use the FileSystemStorage class to write the content of
your DB file into the path. Notice that it must be a valid SQLite
file!
Important: getDatabasePath() is not supported in the Javascript port. It
will always return null.
This is very useful for applications that need to synchronize with a
central server or applications that ship with a large database as part
of their core product.
You are relying on paths that make sense in the simulator, in the device you need to copy a resource into location. Check out the SQL demo where this is implemented: https://www.codenameone.com/blog/sql-demo-revisited.html
Use following code to copy database to Codenameone storage after put the database file in src folder, the database will copy to directory ".cn1/database" after running
String DB_NAME = "DBNAME.db";
Database temp_db = Database.openOrCreate(DB_NAME); //To create an empty file before copy, otherwise Android will throw file not found exception
temp_db.close();
String p = Database.getDatabasePath(DB_NAME);
OutputStream o = FileSystemStorage.getInstance().openOutputStream(p);
InputStream i = Display.getInstance().getResourceAsStream(getClass(), "/" + DB_NAME);
Util.copy(i, o);
This doesn't seem like a complete answer.
I'm going through the demo, and something seems to be missing:
Shouldn't a build task copy this db resource to the correct target folder? Otherwise how can a deployment ever work? (if the db doesnt get packaged up then how will it get deployed?) without it the app cant run

smartXLS - sheetRangeToImage not working

I have this problem using smartXLS library for Java
I try to export the sheets of a workbook as .png images using the method
workbook.sheetRangeToImage(row1,col1,row2,col2,file)
The code I use is as follows:
private static void takeValuePics() throws Exception {
WorkBook w = new WorkBook();
w.read(XLS_PATH + DIF_FILE_NAME);
int numSheets = w.getNumSheets();
String out;
for(int i=0;i<numSheets;i++) {
w.setSheet(i);
System.out.println(w.getNumber(1,1));
w.setPrintGridLines(true);
out = VAL_PATH + "values_" + w.getSheetName(i) + ".png";
w.sheetRangeToImage(0,0,LOOPS,3,out);
}
The constants are configured correctly and the file is read correctly.
(The println() prints correct values)
The .png files are created but they are completely empty! Just white rectangles.
Does anybody know what's wrong?
Problem solved by the fantastic SmartXLS support team!
I forward their answer:
You need set the print scale,it use the print scale value when exporting range to image
workBook.setPrintScale(100);
That was all!
Hope this helps people in the future.

Getting error as " org.apache.poi.hssf.usermodel.HSSFRow cannot be cast to org.apache.poi.ss.usermodel.Row"

I am writing java code to read excel file having column name "Key" and "Value". But getting error as unable to cast at this line of code,
Row firstRow =(Row)sheet.getRow(0);
How to resolve this error please help me.
public static void main(String[] args) throws Exception {
FileInputStream fileIn = new FileInputStream("c://param_2003.xls");
POIFSFileSystem fs = new POIFSFileSystem(fileIn);
HSSFWorkbook filename = new HSSFWorkbook(fs);
HSSFSheet sheet = filename.getSheetAt(0);
String column1 = "Key";
String column2 = "Value";
Integer columnNo1 = null;
Integer columnNo2 = null;
List<Cell> cells = new ArrayList<Cell>();
Row firstRow =(Row)sheet.getRow(0);
for(org.apache.poi.ss.usermodel.Cell cell:firstRow){
if (cell.getStringCellValue().equals(column1)){
columnNo1 = cell.getColumnIndex();
}
}
for(org.apache.poi.ss.usermodel.Cell cell:firstRow){
if (cell.getStringCellValue().equals(column2)){
columnNo2 = cell.getColumnIndex();
}
}
System.out.println(columnNo1);
System.out.println(columnNo2);
}
You've got mis-matched Apache POI jars on your classpath. You need to ensure that all of your Apache POI jars are from the same version, things won't work if you combine old an new jars.
To see what jars you need, take a look at the Apache POI Components page which lists them and their dependencies
To work out what jars you're actually using (which may not be what you think you're using), see the code snippet in the first Apache POI FAQ entry
Once you have a consistent set of POI jars (which as of writing would be based off of 3.10), it should be fine
Select only a single POI library.

How to get the page count of a microsoft word document in java?

for a server based j2ee application, I need to retrieve the number of pages from word documents.. any ideas what works?
If the documents are modern Word 2007 format you can use direct XML-based manipulation, through OOXML. This is by far the better long term solution, though I realize it may not be realistic for an entire organization to change overnight.
If they are older Word formats, you're probably stuck with server-side Word/Excel/Powerpoint/Outlook programmable object models, although you're not supposed to do that on the server..
Regarding Office Open XML support, the latest beta of Java-POI is supposed to support it.
Haven't used it before but you could try Apache POI. Looks like it has a WordCount function.
//Open the Word Document
Document doc = new Document("C:\\Temp\\file.doc");
//Get page count
int pageCount = doc.getPageCount();
To read the page count of MS Office files you can use aspose libraries (aspose-words, aspose-cells, aspose-slides).
Examples:
Excel:
number of pages of the printable version of the Woorkbook:
import com.aspose.cells.*;
public int getPageCount(String filePath) throws Exception {
Workbook book = new Workbook(filePath);
ImageOrPrintOptions imageOrPrintOptions = new ImageOrPrintOptions();
// Default 0 Prints all pages.
// IgnoreBlank 1 Don't print the pages which the cells are blank.
// IgnoreStyle 2 Don't print the pages which cells only contain styles.
imageOrPrintOptions.setPrintingPage(PrintingPageType.IGNORE_STYLE);
int pageCount = 0;
for (int i = 0; i < book.getWorksheets().getCount(); i++) {
Worksheet sheet = book.getWorksheets().get(i);
PageSetup pageSetup = sheet.getPageSetup();
pageSetup.setOrientation(PageOrientationType.PORTRAIT);
pageSetup.setPaperSize(PaperSizeType.PAPER_LETTER);
pageSetup.setTopMarginInch(1);
pageSetup.setBottomMarginInch(1);
pageSetup.setRightMarginInch(1);
pageSetup.setLeftMarginInch(1);
SheetRender sheetRender = new SheetRender(sheet, imageOrPrintOptions);
int sheetPageCount = sheetRender.getPageCount();
pageCount += sheetPageCount;
}
return pageCount;
}
Word: number of pages:
import com.aspose.words.Document;
public int getPageCount(String filePath) throws Exception {
Document document = new Document(filePath);
return document.getPageCount();
}
PowerPoint: number of slides:
import com.aspose.slides.*;
public int getPageCount(String filePath) throws Exception {
Presentation presentation = new Presentation(filePath);
return presentation.getSlides().toArray().length;
}

Categories

Resources