I need to load data from database to excel sheet. so when I run the code throw this exception.
This is what i am working with so far.
database table name is pettycash so I need to load data from this table.
private void excelTest(ActionEvent event) {
try {
String cococo = "select * from pettycash";
ResultSet rs = database.DB_Connector.search(cococo);
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet("pettycash");
XSSFRow Header = sheet.createRow(0);
Header.createCell(0).setCellValue("Petty ID");
Header.createCell(1).setCellValue("pettycash_static_ammount");
Header.createCell(2).setCellValue("pettycash_balance");
Header.createCell(3).setCellValue("pettygiv_Date");
Header.createCell(4).setCellValue("pettycash_status");
Header.createCell(5).setCellValue("Rider_idRider");
int index = 1;
while (rs.next()) {
XSSFRow row = sheet.createRow(index);
row.createCell(0).setCellValue(rs.getString("idpettycash"));
row.createCell(1).setCellValue(rs.getString("pettycash_static_ammount"));
row.createCell(2).setCellValue(rs.getString("pettycash_balance"));
row.createCell(3).setCellValue(rs.getString("pettygiv_Date"));
row.createCell(4).setCellValue(rs.getString("pettycash_status"));
row.createCell(5).setCellValue(rs.getString("Rider_idRider"));
index++;
}
FileOutputStream fileout = new FileOutputStream("petycash.xlsx");
wb.write(fileout);
fileout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Look at this solution using MemPOI
private void excelTest(ActionEvent event) {
try {
String cococo = "select * from pettycash";
PreparedStatement prepStmt = database.DB_Connector.preparedStatement(cococo);
File file = new File("petycash.xlsx");
new MempoiBuilder()
.setFile(file)
.addMempoiSheet(new MempoiSheet(prepStmt))
.build()
.prepareMempoiReportToFile()
.get();
} catch (Exception e) {
e.printStackTrace();
}
}
You can use this library to perform what you are trying to do manually. One line of code:
writer.writeAll(rs, includeHeaders);
Related
I want to write the output of the displayDirectoryContents to a excel sheet
I have tried using the Apache POI method I want to get the output to a excel sheet
Folder and filename in one column and
the name of the files in another column
import statements
public class Excel {
private static String dest = "C:\\Users\\mahselva\\testexcel.xls";
private static HSSFWorkbook myWorkBook = new HSSFWorkbook();
private static HSSFSheet mySheet = myWorkBook.createSheet();
public static void excelLog(String filename, String message, int rowNum)
{
HSSFRow myRow = null;
HSSFCell myCell = null;
String excelData[][] = new String[1][2];
excelData[0][0] = filename;
excelData[0][1] = message;
myRow = mySheet.createRow(rowNum);
for (int cellNum = 0; cellNum < 2; cellNum++) {
myCell = myRow.createCell(cellNum);
myCell.setCellValue(excelData[0][cellNum]);
}
try {
FileOutputStream out = new FileOutputStream(dest);
myWorkBook.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
File currentDir = new File("C:\\OracleATS\\openScript"); // current
directory
displayDirectoryContents(currentDir);
}
public static void displayDirectoryContents(File dir) {
try {
int i = 0;
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println("Folder"
+path.getFileName().toString());
excelLog("Folder",path.getFileName().toString(),i);
i++;
displayDirectoryContents(file);
} else {
Path path = Paths.get(file.getCanonicalPath());
//System.out.println(path.getFileName().toString());
excelLog("File",path.getFileName().toString(),i);
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I want two columns in an excel sheet with column 1 containing File or
Folder and column 2 containing the name of the file/folder
eg
File books.xml
Folder Script
Thus i want to write the output to the excel sheet
i am using the function excel log to write to the output screen
I use this to write to an excel - however I make it .csv format, not xls. Therefore this might not be what you need, but it's still partially useful as it's writing in a file that can be opened by excel efortlessly.
public static void printAtFile(String filename, String header, String content[])
{
filename+=".csv";
System.out.println("Start creating file "+filename);
PrintWriter writer = null;
try {
writer = new PrintWriter(filename);
writer.println(header);
for(String u:content)
writer.println(u);
writer.close();
} catch (Exception ex) {
System.out.println("Error while writing at file "+filename);
}
}
I am using selenium webdriver in eclipse with Java for a project at work. I am in need of exporting a value to an excel file. I am able to write to an excel file but am unable to export the specific value to the excel file.
Here is the automation process for getting the value:
public void AbbeyNational (String AbbeyNationalURL, String AN_AccCookiesButton, String AN_MortgageTabButton, String AN_ExistingCustomerButton, String AN_FollowRateButton, String AN_SVRButton, String AN_RateFld)throws InterruptedException {
driver.get(AbbeyNationalURL);
driver.findElement(By.xpath(AN_AccCookiesButton)).click();
driver.findElement(By.linkText(AN_MortgageTabButton)).click();
driver.findElement(By.xpath(AN_ExistingCustomerButton)).click();
driver.findElement(By.xpath(AN_FollowRateButton)).click();
driver.findElement(By.xpath(AN_SVRButton)).click();
String a = driver.findElement(By.cssSelector(AN_RateFld)).getText();
String AN_Rate = a.substring(54,58);
System.out.println(AN_Rate);
}
The 'AN_Rate' variable holds the value after automation.
The value prints to the console but I need the value to be exported to the excel file with the use of automation. Can anyone help me with this?
Additionally, here is my code for writing to an excel file:
public void writeToExcel(String AN_Rate) throws IOException{
File file = new File(filePath+"\\"+fileName);
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet Sheet0 = IRWorkbook.createSheet();
Sheet0.createRow(0).createCell(0).setCellValue(AN_Rate);
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
you can use this code for large set of data :
public class ExcelWriter {
// LinkedHashMap to maintain the insertion order
public static Map<String, String> dataMap = new LinkedHashMap<>();
public static String filePath = "D:\\ECLIPSE-WORKSPACE\\playground\\src\\main\\resources";
public static String fileName = "demo-data";
public static void main(String[] args) throws IOException {
String AN_Rate = "Data-1";
String BN_Rate = "Data-2";
String CN_Rate = "Data-3";
dataMap.put("AN_Rate", AN_Rate);
dataMap.put("BN_Rate", BN_Rate);
dataMap.put("CN_Rate", CN_Rate);
writeToExcel(dataMap, filePath, fileName);
}
public static void writeToExcel(Map<String, String> dataMap, String filePath, String fileName) throws IOException {
File file = new File(filePath + "\\" + fileName + ".xlsx");
if (file.exists()) {
file.delete();
}
file.createNewFile();
XSSFWorkbook IRWorkbook = new XSSFWorkbook();
XSSFSheet sheet = IRWorkbook.createSheet();
List<String> headers = dataMap.keySet().stream().collect(Collectors.toList()); // all key values in a list
List<String> data = new ArrayList<>(dataMap.values()); // all data in a list
setHeadersAndFillData(sheet, headers, data); // filling excel sheet with headers and corresponding data
try {
FileOutputStream fos = new FileOutputStream(file);
IRWorkbook.write(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void setHeadersAndFillData(XSSFSheet sheet, List<String> headers, List<String> data) {
int headersSize = headers.size();
int dataSize = headers.size();
Row headerRow = sheet.createRow(0);
Row dataRow = sheet.createRow(1);
setCells(headers, headersSize, headerRow);
setCells(data, dataSize, dataRow);
}
private static void setCells(List<String> cellData, int headersSize, Row row) {
for (int rn = 0; rn < headersSize; rn++) {
row.createCell(rn).setCellValue(cellData.get(rn));
}
}
}
Just edit your method writeToExcel with :
Replace :File file = new File(filePath+"\\"+fileName);
with added file extention
File file = new File(filePath+"\\"+fileName + ".xlsx");
and than the value will be exported to excel file.
And if there is large set of data than you should store all values in a static map and than export all values to excel at once.
I want to pass username and password in a webpage from excel sheet. help me to get the out put.
error is display as red underline in getRow(), getColumn(), getCell() etc.
This is my java file:
public class NewTest_tstng_excel {
public WebDriver driver;
public static XSSFSheet excelSheet;
public void login() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
}
#BeforeClass
public void testSetup() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
//wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider="empLogin")
public void VerifyInvalidLogin(String userName, String password) {
driver.get("URL goes here");
driver.findElement(By.id("UserName")).sendKeys(userName);
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
driver.findElement(By.id("Password")).sendKeys(password);
driver.findElement(By.id("btnLogin")).submit();
}
#DataProvider(name="empLogin")
public Object[][] loginData() {
Object[][] arrayObject = getExcelData("E:\\disha.shah\\myWork\\sele_proj\\FAM_Excel data\\src\\DataFile\\Book1.xlsx","Sheet1");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fs);
//Workbook wb = Workbook.getWorkbook(fs);
//Sheet sh = wb.getSheet(sheetName);
excelSheet = workBook.getSheet("Sheet1");
int totalNoOfCols = excelSheet.getColumns();
int totalNoOfRows = excelSheet.getRows();
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i= 1 ; i < totalNoOfRows; i++) {
for (int j=0; j < totalNoOfCols; j++) {
arrayExcelData[i-1][j] = excelSheet.getCell(j, i).getContents();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
in excel: there is 2 column containing username and password.
See if getRow is null.
You can do createRow().
If in the excel you don't use the row you need, you will have to create a new row, otherwise you use getRow if the row is already in use!
I would like to insert values into existing work book. Here the class that encapsulates this logic:
public class FormulaExtractor {
private String pathToExcelFile;
private XSSFWorkbook workbook;
private Map<Double, Formula> idFormular = new HashMap<>();
public FormulaExtractor(String pathToExcelFile) {
this.pathToExcelFile = pathToExcelFile;
try (FileInputStream fileInputStream = new FileInputStream(new File(pathToExcelFile))) {
this.workbook = new XSSFWorkbook(fileInputStream);
} catch (FileNotFoundException e) {
System.out.println("Cannot locate a xls file. Exception: " + e.toString());
} catch (IOException e) {
System.out.println("IO exception " + e.toString());
}
}
public void insertHumanReadableFormulas() throws IOException {
XSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
Cell cell = currentRow.createCell(CellReference.convertColStringToIndex("K"));
cell.setCellValue("Some dummy variable to test. ");
}
FileOutputStream fileOut = new FileOutputStream(new File(this.pathToExcelFile));
workbook.write(fileOut);
fileOut.close();
}
}
How do I use it:
public class App {
public static void main(String[] args) throws IOException {
final String pathToExcel = "some/path/some_excel.xlsx";
FormulaExtractor formulaExtractor = new FormulaExtractor(pathToExcel);
formulaExtractor.insertHumanReadableFormulas();
}
}
I don't get any exception or error. When I open my excel file, I simply cannot find values in a column "K". What am I doing wrong?
I am able to read the excel file data from the below code, but I am unable to get the logic behind how to get Excel data in order to store in POJO class after reading the excel file.
In short: I am confused how to send these read Excel data to my model class to be stored in my database table?
The following code prints correctly the excel rows in my Eclipse console:
..............
..............
public String execute()
{
try
{
String filePath=servletRequest.getSession().getServletContext().getRealPath("/");
File fileToCreate= new File(filePath,this.excelDataFileName);
FileUtils.copyFile(this.excelData, fileToCreate);
UploadExcel obj=new UploadExcel();
obj.readExcel(excelData.getAbsolutePath());
}
catch(Exception e){
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
/*
*Method to read the each sheet ,row & column of the excel sheet of the uploaded xls file
*/
public void readExcel(String filePath)
{
try
{
FileInputStream file=new FileInputStream(new File(filePath));
//Getting the instance for XLS file
HSSFWorkbook workbook=new HSSFWorkbook(file);
//Get First sheet from the workbook
HSSFSheet sheet=workbook.getSheetAt(0);
ArrayList myList = new ArrayList();
//Iterate start from the first sheet of the uploaded excel file
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext())
{
Row row=rowIterator.next();
if(row.getRowNum()==0)
{
continue;//skip to read the first row of file
}
//For each row, iterate through each columns
Iterator<Cell> cellIterator=row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell=cellIterator.next();
if(cell.getColumnIndex()==0)
{
continue;
}
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
// myList.add(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue()+ "\t\t");
// myList.add(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue()+ "\t\t");
// myList.add(cell.getStringCellValue());
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out=
new FileOutputStream(new File(filePath));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In console output:
TEXTit 6695 PROSPECT RD Nova Scotia B3z 3t1
row2sdfsda 61695 P sfsdfdsf 23B3z 3t1
What I thought is: I have to get the row one by one and I will add this row data to my POJO class object and send it to dao, and finally use saveOrupdate(tableobj) of hibernate method to save the data into my db table.
But I was unable to think how I can add these pieces of data to my Pojo class.
Hope someone can help me here.
You can inject/pass reference to your DAO into UploadExcel class. Then when in readExcel() method you can create new ENTITY and fill it with values.
Entity entity = new Entity();
while(cellIterator.hasNext())
{
Cell cell=cellIterator.next();
if(cell.getColumnIndex()==0)
{
continue;
}
switch(cell.getCellType())
{
case Cell.CELL_TYPE_BOOLEAN:
entity.setBooleanValue(cell.getBooleanValue);
break;
...
}
}
Finally you insert/createOrUpdate your entity by your DAO.
dao.insertOrUpdate(entity);
* EDIT *
Code to explain comment
Entity is just an example of custom entity which models data you read from excel.
If for example your excel contains data about Customer then you can create
customer entity.
public class Customer {
private String name;
private String surname;
private Integer age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
// + getters and setters for other fields
}
Then you send this entity filled with excel data to your DAO (which manages customer table), and insert given entity into DB.
* EDIT2 *
Remove "dao.saveOrUpdateCompany(company);" from following code:
public String execute()
{
try
{
String filePath=servletRequest.getSession().getServletContext().getRealPath("/");
File fileToCreate= new File(filePath,this.excelDataFileName);
FileUtils.copyFile(this.excelData, fileToCreate);
UploadExcel obj=new UploadExcel();
obj.readExcel(excelData.getAbsolutePath());
}
catch(Exception e){
e.printStackTrace();
addActionError(e.getMessage());
return INPUT;
}
return SUCCESS;
}
You want one new entity PER ROW, now you just create one entity in the beginning of class
Read comments following code
public void readExcel(String filePath)
{
try
{
List sheetData = new ArrayList();
FileInputStream file=new FileInputStream(new File(filePath));
//Getting the instance for XLS file
HSSFWorkbook workbook=new HSSFWorkbook(file);
//Get First sheet from the workbook
HSSFSheet sheet=workbook.getSheetAt(0);
//Iterate start from the first sheet of the uploaded excel file
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = (Row) rowIterator.next();
// CHANGE
Company company = new Company();
company.setName(getCellValue(row.getCell((short)1)));
// HERE YOU CAN SAVE COMPANY
dao.saveOrUpdateCompany(company);
// OR ADD COMPANY TO LIST
// List<Company> companies = new ArrayList<Company>();
// Declare just one list for entire class not per row
// In this case you call custom made DAO method which batch save
// all company entities in list but you call this custom method
// at the end of excel processing (your original dao code position).
// Try it without list first
list.add(company);
}
System.out.println("Seet data size-"+sheetData.size());
file.close();
FileOutputStream out=
new FileOutputStream(new File(filePath));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
* EDIT3 *
I think this should finally work
try{
session=HibernateUtil.getSessionFactory().openSession();
transaction=session.beginTransaction();
for(int i=0;i<companies.size();i++)
{
// THIS IS BAD
//Company com=new Company();
//You need this
Company com = companies.get(i);
session.saveOrUpdate(com);
}
transaction.commit();
status++;
}
Iterator iterator = workSheet.rowIterator();
while (iterator.hasNext()) {
Row row = (Row) iterator.next();
// check each cell for null and by using getCellValue() method. and inject the value in to user defined pojo.
}
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}