Can someone point me in the right direction for writing to an excel file in java??
I am not understanding the links I found online.
Could you just send me a link or anything which I could follow through??
Thank you,
J
Another alternative to Apache POI is the JExcelAPI, which (IMO) has an easier to use API. Some examples:
WritableWorkbook workbook = Workbook.createWorkbook(new File("output.xls"));
WritableSheet sheet = workbook.createSheet("First Sheet", 0);
Label label = new Label(0, 2, "A label record");
sheet.addCell(label);
Number number = new Number(3, 4, 3.1459);
sheet.addCell(number);
Not to be banal, but Apache POI can do it. You can find some code examples here:
http://poi.apache.org/spreadsheet/examples.html
Posting useful examples for API's.
Step by step example for using JExcelAPI:
http://www.vogella.de/articles/JavaExcel/article.html
http://www.java-tips.org/other-api-tips/jexcel/how-to-create-an-excel-file.html
Step by step example for using POI (little old one but useful):
http://www.javaworld.com/javaworld/jw-03-2004/jw-0322-poi.html
Here i'm going to give sample example,how to write excel;use this in pom.xml
<dependency>
<groupId>net.sf.jxls</groupId>
<artifactId>jxls-core</artifactId>
<version>0.9</version>
</dependency>
Model class:
public class Products {
private String productCode1;
private String productCode2;
private String productCode3;
constructors,setters and getters
}
main class:
public class WriteExcel {
public void writeExcel() {
Collection staff = new HashSet();
staff.add(new Products("101R15ss0100", "PALss Kids 1.5 A360 ", "321"));
staff.add(new Products("101R1ss50100", "PAL sKids 1.5 A360 ", "236"));
Map beans = new HashMap();
beans.put("products", staff);
XLSTransformer transformer = new XLSTransformer();
try {
transformer.transformXLS(templateFileName, beans, destFileName);
System.out.println("Completed!!");
} catch (ParsePropertyException e) {
System.out.println("In ParsePropertyException");
e.printStackTrace();
} catch (IOException e) {
System.out.println("In IOException");
e.printStackTrace();
}
}
public static void main(String[] args) {
WriteExcel writeexcel = new WriteExcel();
writeexcel.writeExcel();
}
}
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell Cell;
private static XSSFRow Row;
File fileName = new File("C:\\Users\\satekuma\\Pro\\Fund.xlsx");
public void setExcelFile(File Path, String SheetName) throws Exception {
try {
FileInputStream ExcelFile = new FileInputStream(Path);
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
public static void setCellData(String Result, int RowNum, int ColNum, File Path) throws Exception {
try {
Row = ExcelWSheet.createRow(RowNum - 1);
Cell = Row.createCell(ColNum - 1);
Cell.setCellValue(Result);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the basic code to write data in excel file (.xls).
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
public class Export2Excel {
public static void main(String[] args) {
try {
//create .xls and create a worksheet.
FileOutputStream fos = new FileOutputStream("D:\\data2excel.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("My Worksheet");
//Create ROW-1
HSSFRow row1 = worksheet.createRow((short) 0);
//Create COL-A from ROW-1 and set data
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("Sno");
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.GOLD.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellA1.setCellStyle(cellStyle);
//Create COL-B from row-1 and set data
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Name");
cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(HSSFColor.LIGHT_CORNFLOWER_BLUE.index);
cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
cellB1.setCellStyle(cellStyle);
//Create COL-C from row-1 and set data
HSSFCell cellC1 = row1.createCell((short) 2);
cellC1.setCellValue(true);
//Create COL-D from row-1 and set data
HSSFCell cellD1 = row1.createCell((short) 3);
cellD1.setCellValue(new Date());
cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(HSSFDataFormat
.getBuiltinFormat("m/d/yy h:mm"));
cellD1.setCellStyle(cellStyle);
//Save the workbook in .xls file
workbook.write(fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
NOTE: You need to download jar library from the link: http://www.java2s.com/Code/JarDownload/poi/poi-3.9.jar.zip
I've used Apache's POI Library when I've had to write to excel files from Java. I found it rather straight forward once you get the hang of it. Java World has a good tutorial about starting out using POI that I found very helpful.
Related
I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file
using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}
Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}
Can some one please provide codes/logic to retrieve Excel (.xlsx) data. I need the data to be retrieved in such a way that I can get the value and pass it any where in code for testing web page. This is the code how I need to get:
driver.findElement(By.id("")).sendkeys(getExceldata(row, column));
I just need to define the row and column and it should get the data from Excel sheet by using any method like getExceldata(1,2)
public String cellValue(String filepath,String sheetname,int r,int c)
{
try{
FileInputStream fis = new FileInputStream(new File(filepath));
book = WorkbookFactory.create(fis);
sh = book.getSheet(sheetname);
System.out.println(sh.getSheetName());
row = sh.getRow(r);
cell = row.getCell(c);
return cell.getStringCellValue();
}catch(Exception e)
{
return null;
}
}
public int getRows(String filepath,String sheetname)
{
try{
FileInputStream fis= new FileInputStream(filepath);
book= new XSSFWorkbook(fis);
return book.getSheet(sheetname).getLastRowNum();
}
catch(Exception e)
{
return 0;
}
----------------------------New class below--------------------------------
WebDriver driver;
Excel excel= new Excel();
public static String filepath="D:\\Chinmaya Work\\Work Space\\simpleProject\\src\\Newcustomerdata.xlsx";
public static String sheetname="newcusotomer";
public void setUp() throws InterruptedException
{
driver=new FirefoxDriver();
driver.get("http://www.demo.guru99.com/V4/index.php");
Thread.sleep(5000);
}
public void loginToApplication()
{
Homepagegurru99 home=new Homepagegurru99(driver);
home.enterUsername("mngr45812");
home.enterPassword("chinu#221");
home.clickLoogin();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void gotoNewcustomepage()
{
Dashbardgurru99 dash=new Dashbardgurru99(driver);
dash.gotonewCustomerpage();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
}
public void createNewcustomer()
{
Newcustomeradd create=new Newcustomeradd(driver);
int rowCount=excel.getRows(filepath, sheetname);
System.out.println(rowCount);
create.eneterCustomername(excel.cellValue(filepath, sheetname, 2,0));
create.selectSex();
create.enterDob(excel.cellValue(filepath, sheetname, 3,0));
create.enterAddress(excel.cellValue(filepath, sheetname, 4,0));
create.enterCity(excel.cellValue(filepath, sheetname, 5,0));
create.enterState(excel.cellValue(filepath, sheetname, 6,0));
create.enterPin(excel.cellValue(filepath, sheetname, 7,0));
create.enterMobileno(excel.cellValue(filepath, sheetname, 8,0));
create.enterEmail(excel.cellValue(filepath, sheetname, 9,0));
create.enterPassword(excel.cellValue(filepath, sheetname, 10,0));
create.clickSubmit();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
}
public void logOut()
{
driver.findElement(By.linkText("Log out")).click();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS);
driver.switchTo().alert().accept();
driver.close();
}
Dependencies (poi-ooxml.jar)
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
To Persist into an Excel File
fis = new FileInputStream(new File(fileName));
XSSFWorkbook workbook = new XSSFWorkbook (fis);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row1 = sheet.createRow(0);
XSSFCell r1c1 = row1.createCell(0);
r1c1.setCellValue("Demo");
fis.close();
FileOutputStream fos = new FileOutputStream(new File(outputFile));
workbook.write(fos);
fos.close();
To Retrieve from an Excel File follow the link, Get Cell Value from Excel Sheet with Apache Poi .
HTH
I am working on creating an excel report from java code using apache POI library. I have encountered a problem while formatting excel cell. Please find below piece of code.
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("coverageData");
int rownum = 0,cellnum=0;
Row row1 = sheet.createRow(rownum++);
Cell cell10 = row1.createCell(cellnum++);
cell10.setCellValue("cell data");
XSSFCellStyle row1style = (XSSFCellStyle)cell10.getCellStyle();
XSSFColor grayColor = new XSSFColor(Color.DARK_GRAY);
row1style.setFillBackgroundColor(grayColor);
cell10.setCellStyle(row1style);
try
{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("P:\\automation\\Spreadsheet.xlsx"));
workbook.write(out);
out.close();
System.out.println("Spreadsheet.xlsx written successfully on disk.");
}
catch (Exception e)
{
e.printStackTrace();
}
The problem here is i am setting cell10 style in last line of code, but it is not getting affected in the excel sheet created by the program.
Thanks in advance.
Try it, bellow work fine for me:
import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestClass {
public static void main(String[] args){
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("coverageData");
int rownum = 0,cellnum=0;
Row row1 = sheet.createRow((short)rownum++);
//Set Color style start
CellStyle row1style = wb.createCellStyle();
row1style.setFillBackgroundColor(IndexedColors.LIGHT_GREEN.getIndex());
row1style.setFillPattern(CellStyle.BIG_SPOTS);
//Set Color style end
Cell cell10 = row1.createCell((short)cellnum++);
cell10.setCellStyle(row1style);
cell10.setCellValue("cell data");
try{
//Write the workbook in file system
FileOutputStream out = new FileOutputStream(new File("Spreadsheet.xlsx"));
wb.write(out);
out.close();
System.out.println("Spreadsheet.xlsx written successfully on disk.");
} catch (Exception e) { e.printStackTrace(); }
}
}
You need to set the color like this:
final XSSFCellStyle description = (XSSFCellStyle) workbook.createCellStyle();
description.setFillForegroundColor( yourColor );
description.setFillPattern( FillPatternType.SOLID_FOREGROUND );
This is, you need a fill pattern
I want to store username and password in Excel whatever I will type in any application using WebDriver. I am using TestNG framework and Apache POI to write data to Excel. But I am getting Null pointer exception. Please tell me how to work WebDriver with Excel.
public class Test {
private static WebDriver driver;
static String username="abc";
static String password="abf123";
public static void main(String args[]) {
try {
driver.get("any url");
driver.findElement(By.xpath("//*[#id='txtUserName']")).sendKeys(username);
driver.findElement(By.xpath("//*[#id='txtPwd']")).sendKeys(password);
FileOutputStream fos = new FileOutputStream("Userpass.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("POI WorkSheet");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cell1 = row1.createCell((short) 0);
cell1.setCellValue(username);
HSSFCell cell2 = row1.createCell((short) 1);
cell2.setCellValue(password);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
#Test
public void f() {
}
}
Replace the following lines in your code
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cell1 = row1.createCell((short) 0);
cell1.setCellValue(username);
HSSFCell cell2 = row1.createCell((short) 1);
cell2.setCellValue(password);
with
HSSFRow row1 = worksheet.createRow(0);
row1.createCell(0).setCellValue(new HSSFRichTextString("username"));
row1.createCell(1).setCellValue(new HSSFRichTextString("password"));
you will get the desired output.
I am new to Java POI and i am trying to overwrite an excel file using Java POI.Let me make it clear, i don't want to open a new .xls file every time time i build the code however the code i wrote does it that way.The purpose for this is to, i will build the chart on excel and read the values for the chart from the database and write it to the excel file by using Java POI.Here is my code:
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet firstSheet = workbook.createSheet("oldu");
HSSFSheet secondSheet = workbook.createSheet("oldu2");
HSSFRow rowA = firstSheet.createRow(6);
HSSFCell cellA = rowA.createCell(3);
cellA.setCellValue(new HSSFRichTextString("100"));
cellA.setCellValue(100);
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell(0);
cellB.setCellValue(new HSSFRichTextString("200"));
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File("CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Always use the same filename and when you run the program it will overwrite the file.
EDIT
If you want to modify an existing excel file then have a look HERE and scroll down to the section on "Reading or Modifying an existing file".
The problem is Apache POI doesn't support all features of Excel file format, including charts. So can not generate a chart with POI and when opening an existing Excel file with POI and modifying it, some of the current "objects" in the Excel file could be lost, as POI can't handle it and when writing, writes only the new information generated and existing one that can handle.
This is assumed by Apache as one of the flaws of POI.
We done similar processing of existing Excel file, filling new data onto it, but the existing Excel file contains only formatting styles and they are preserved using POI, but I think charts are very problematic. Trying ti filling data to update an existing chart is not possible with POI.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class UserInput {
public static Map getUserInput() throws InvalidFormatException, IOException {
String userName = System.getProperty("user.name");
String path = "";
int indexofColumn = 10;
Map inputFromExcel = new HashMap();
InputStream inp = new FileInputStream(path);
int ctr = 4;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
inputFromExcel.put("NBKID",cell.toString()) ;
row = sheet.getRow(ctr+1);
cell = row.getCell(indexofColumn);
inputFromExcel.put("Password", cell.toString());
row = sheet.getRow(ctr+2);
cell = row.getCell(indexofColumn);
inputFromExcel.put("NBKIDEmail",cell.toString());
row = sheet.getRow(ctr+3);
cell = row.getCell(indexofColumn);
inputFromExcel.put("sourceExcel" ,cell.toString());
} catch(Exception e) {
}
return inputFromExcel;
}
}
import java.util;
public class Main {
public static void main(String[] args) {
List<String> partyIdList = new ArrayList<String>();
List<String> phNoList = new ArrayList<String>();
String userName = System.getProperty("user.name");
String path = "";
try {
Map data = new HashMap(UserInput.getUserInput());
partyIdList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),0);
phNoList = ReadExcel.getContentFromExcelSheet(data.get("sourceExcel").toString(),1);
WriteExcel.writeFile1(partyIdList, path,0,1);
WriteExcel.writeFile1(phNoList,path,1,0);
} catch (Exception e) {
throw new RuntimeException("Error while read excel Sheet" + e);
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.List;
public class WriteExcel {
public static void writeFile1(List dataList , String path , int columnCount,int forwardIndex) throws InvalidFormatException, IOException {
try {
FileInputStream inputStream = new FileInputStream(new File(path));
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
int rowCount = 1;
for ( int i = 0+forwardIndex ; i < dataList.size(); i++) {
Row row = sheet.createRow(++rowCount);
// int columnCount = 0;
Cell cell = row.createCell(columnCount);
cell.setCellValue((String) dataList.get(i));
}
inputStream.close();
FileOutputStream outputStream = new FileOutputStream(path);
workbook.write(outputStream);
workbook.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ReadExcel {
public static List getContentFromExcelSheet(String path ,int indexofColumn) throws InvalidFormatException, IOException {
//System.out.println(path);
List<String> ItemList = new ArrayList();
InputStream inp = new FileInputStream(path);
int ctr = 0;
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0); // Mention Sheet no. which you want to read
Row row = null;
Cell cell = null;
boolean isNull = false;
do{
try{
row = sheet.getRow(ctr);
cell = row.getCell(indexofColumn); //Mention column no. which you want to read
ItemList.add(cell.toString());
// System.out.println(cell.toString());
ctr++;
} catch(Exception e) {
isNull = true;
}
}while(isNull!=true);
inp.close();
return ItemList;
}
}