Issue while reading Excel document (Java code) - java

I have some Java code which reads the Excel data. On running the Java code, it's showing the following error. Help me resolve the same. Also, I need to know other method of reading .xlsx file.
(A small edit) how I can print rows with their respective columns. For example:
Age
19
20
21
Salary
35k
20k
40k
.
.
.
Exception in thread "main"
org.apache.poi.poifs.filesystem.OfficeXmlFileException: The supplied
data appears to be in the Office 2007+ XML. You are calling the part
of POI that deals with OLE2 Office Documents. You need to call a
different part of POI to process this data (eg XSSF instead of HSSF)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:131)
at
org.apache.poi.poifs.storage.HeaderBlock.(HeaderBlock.java:104)
at
org.apache.poi.poifs.filesystem.POIFSFileSystem.(POIFSFileSystem.java:138)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:322)
at
org.apache.poi.hssf.usermodel.HSSFWorkbook.(HSSFWorkbook.java:303)
at ExcelRead.main(ExcelRead.java:18)
The Java code is as follows:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelRead {
public static void main(String[] args) {
try {
FileInputStream file = new FileInputStream(new File("C:/Users/vinayakp/Desktop/Book.xlsx"));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException ae) {
ae.printStackTrace();
}
}
}

If you want to read a .xls file you must use HSSF (it supports only .xls format) but for .xlsx files you must use XSSF or another higher version API.

After deleting previous imports class then try to add
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;
private static void read(String path){
Workbook workbook = null;
FileInputStream fis = null;
try {
File source = new File(path);
if(source.exists()){
fis = new FileInputStream(source);
workbook = WorkbookFactory.create(source);
}else{
JOptionPane.showMessageDialog(null, "File path is not exist.", "Error", JOptionPane.ERROR_MESSAGE);
}
Sheet sheet = null;
int lastRowNum = 0;
int numSheets = workbook.getNumberOfSheets();
for(int i = 0; i < numSheets; i++) {
sheet = workbook.getSheetAt(i);
if(sheet.getPhysicalNumberOfRows() > 0) {
lastRowNum = sheet.getLastRowNum();
int lastCellNum = 0;
for(Row row : sheet) {
Employee emp = new Employee();
int numOfCell = row.getPhysicalNumberOfCells();
System.out.println("numOfCell:: "+numOfCell);
String stringValues [] = new String[numOfCell];
for(Cell cell : row) {
// cell = row.getCell(cellIndex);
int cellIndex = cell.getColumnIndex();
logger.info("cellIndex:: "+ cellIndex);
switch (cell.getCellType()) {
case Cell.CELL_TYPE_FORMULA:
// printValue = "FORMULA value=" + cell.getCellFormula();
stringValues[cellIndex] = cell.getCellFormula();
break;
case Cell.CELL_TYPE_NUMERIC:
//printValue = "NUMERIC value=" + cell.getNumericCellValue();
System.out.println("Value is numeric:: "+ cell.getNumericCellValue());
stringValues[cellIndex] = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK:
// printValue = "STRING value=" + cell.getStringCellValue();
stringValues[cellIndex] = cell.getStringCellValue();
break;
default:
}
}
}
}
}
}
} catch (InvalidFormatException e) {
logger.error(e.getMessage());
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(e.getMessage());
} catch (IOException e) {
logger.error(e.getMessage());
e.printStackTrace();
}
catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
finally {
if (fis != null) {
try {
fis.close();
fis = null;
} catch (IOException ioEx) {
logger.error(ioEx.getMessage());
}
}
}
}

you are using the wrong class for reading the file HSSFWorkbook is for old excel format. use XSSFWorkbook instead
Edited:
copied from http://www.coderanch.com/t/463779/java/java/read-xlsx-sheet-Client-Side.
did u do the same thing?
try {
System.out.println("destDir==> "+destDir);
XSSFWorkbook workBook = new XSSFWorkbook(destDir);
XSSFSheet sheet = workBook.getSheetAt(0);
totalRows = sheet.getPhysicalNumberOfRows();
System.out.println("total no of rows >>>>"+totalRows);
} catch (IOException e) {
e.printStackTrace();
}
Edit 2:
Learn about apache POI from this link

Related

On calling getcellData() getting no values from excel - Selenium WebDriver

Here is my excel utils class:
package utility;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.CellType;
public class ExcelUtils {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell cell;
private static XSSFRow row;
//This method is to set the File path and to open the Excel
file, Pass Excel Path and Sheetname as Arguments to this method
public static void setExcelFile(String Path, String SheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(Path);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(SheetName);
} catch (Exception e) {
throw (e);
}
}
//This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
String cellData = "";
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(CellType.STRING);
cellData = cell.getStringCellValue();
return cellData;
} catch (Exception e) {
return "undefined";
}
}
//This method is to write in the Excel cell, Row num and Col num are the parameters
public static void setCellData(String Result, int RowNum, int ColNum) throws Exception {
try {
row = ExcelWSheet.getRow(RowNum);
cell = row.getCell(ColNum, Row.MissingCellPolicy.RETURN_BLANK_AS_NULL);
if (cell == null) {
cell = row.createCell(ColNum);
cell.setCellValue(Result);
} else {
cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
FileOutputStream fileOut = new FileOutputStream(Constants.Path_TestData + Constants.File_TestData);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
throw (e);
}
}
}
Here is the script where I'm calling the getCellData to get the values from Excel:
String cellData = ExcelUtils.getCellData(1, 1);
System.out.println("CellData :" + cellData);
Here is the excel file format:
TestCaseName | Username | Password
TC_01 | TestData |
Output:
Exception in thread "main" java.lang.NullPointerException
at utility.ExcelUtils.getCellData(ExcelUtils.java:63)
at testScripts.Category_creation.main(Category_creation.java:47)
Here is the excel I'am using. Not able to fetch data from excel file. I'm using Page object framework, hence the excel utils file contains only the code and in fetching the data in testScript by passing row and column number.
POI 3.9
please add cell.setCellType(Cell.CELL_TYPE_STRING); after cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
i.e.
import org.apache.poi.ss.usermodel.Cell;
...
try{
cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
cell.setCellType(Cell.CELL_TYPE_STRING);
String CellData = cell.getStringCellValue();
return CellData;
}catch (Exception e){
return"";
}
or you can use this construct
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:
source http://www.java67.com/2014/09/how-to-read-write-xlsx-file-in-java-apache-poi-example.html
and please rename the variable private static XSSFCell Cell; to cell. (Variable naming conventions in Java?)
UPDATE 1
POI 3.17 you could also uncomment switch-case block, it works for POI 3.17
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.io.IOUtils;
import org.apache.poi.ss.usermodel.CellType;
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;
public class Excel {
private static XSSFSheet ExcelWSheet;
private static XSSFWorkbook ExcelWBook;
private static XSSFCell xCell;
private static XSSFRow xRow;
public static void main(String... args) {
try {
InputStream is = readInputStreamFromFile();
XSSFWorkbook myWorkBook = new XSSFWorkbook(is);
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
ExcelWSheet = mySheet;
System.out.println(getCellData(1, 0));
System.out.println(getCellData(1, 1));
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String getCellData(int RowNum, int ColNum) throws Exception{
try {
String cellData = "";
xCell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
xCell.setCellType(CellType.STRING);
cellData = xCell.getStringCellValue();
// switch (xCell.getCellTypeEnum()) {
// case STRING:
// //System.out.print(xCell.getStringCellValue() + "\t");
// cellData = xCell.getStringCellValue();
// break;
// case NUMERIC:
// cellData = String.valueOf(xCell.getNumericCellValue());
// //System.out.print(xCell.getNumericCellValue() + "\t");
// break;
// case BOOLEAN:
// cellData = String.valueOf(xCell.getBooleanCellValue());
// //System.out.print(xCell.getBooleanCellValue() + "\t");
// break;
//
// default:
// cellData = "undefined";
// }
return cellData;
} catch (Exception e){
return "undefined";
}
}
private static InputStream readInputStreamFromFile() throws Exception {
try {
File f = new File("C:\\path to your file\\TestData.xlsx");
InputStream is = new FileInputStream(f);
try {
return new ByteArrayInputStream(IOUtils.toByteArray(is));
} finally {
is.close();
}
} catch (IOException e) {
throw new Exception(e);
}
}
}

How to deal with the changing file names.using jxl?

I want to read xls file using JXl where xls file name is always changing, how to read that please help.
i tried below code
FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\*.xls");
FileInputStream filepath = new FileInputStream("C:\\Users\\sameer.joshi\\Downloads\\");
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\");
File[] all_XLS_Files = directory.listFiles(); //all files in that directory
for (File file : all_XLS_Files) { // iterate through all files in that directory
if(file.getName().endsWith(".xls")){ // select only xls files
//do something with your xls files here
//for example print out the file name
System.out.println(file.getName());
//or read one or all of them
FileInputStream fileInputStream = new FileInputStream(new File(file.getPath()));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(fileInputStream);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
fileInputStream.close();
FileOutputStream out =
new FileOutputStream(new File(file.getPath()));
workbook.write(out);
out.close();
}
}
}
}
Try to add all fileNames inside a list and read all data of Excel file.
List<String>ArrayList xlsFiles=new ArrayList<String>();
xlsFiles.add("your all files Names");
for (String str:xlsFiles) {
readExcellData(str);
}
public List<String> readExcellData(String fileNameToProcess) throws IOException {
List<String> dataList = new ArrayList<String>();
List<Integer> rowNo=new ArrayList<Integer>();
List<Integer> colNo=new ArrayList<Integer>();
int countRow=1;
int countCol=1;
try {
FileInputStream fis = new FileInputStream(file);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
rowNo.add(countRow);
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: {
dataList.add(cell.getStringCellValue());
System.out.println(cell.getStringCellValue());
}
break;
}
}
}
return dataList;
} catch (FileNotFoundException ee) {
ee.printStackTrace();
} catch (IOException ee) {
ee.printStackTrace();
}
return dataList;
}
I think the issue is not how to read a xls file, but how to deal with the changing file names. if that is the case try to use a FilenameFilter to get your .xls files. Example :
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
File directory = new File("C:\\Users\\sameer.joshi\\Downloads\\");
//get all files which ends with ".xls"
FilenameFilter textFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xls");
}
};
// all xls files are listed in this File[] array
File[] files = directory.listFiles(textFilter);
// iterate through your array and do something
for (File file : files) {
//read your .xls files here
System.out.println(file.getCanonicalPath());
}
}
}

Write to excel using Apache POI

Earlier I was using SAX parser for export to excel. Now I am not able to get data using Apache POI, Any suggestion???
This String in XML contains all the data which I retrieved through farpoint grid tech and set in the form in action class.
private void parseXML(String inXML) {
/* // get a factory
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
// get a new instance of parser
SAXParser sp = spf.newSAXParser();
// parse the file
sp.parse(new InputSource(new StringReader(inXML)), this);
} catch (IOException ie) {
}*/
Now I am using this.
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue(inXML);
**/* Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
cell.setCellValue(inXML);
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}*/**
try {
FileOutputStream out = new FileOutputStream(new File("C:\\Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
This program (which is what you posted with added imports, without the comment block, with a literal string instead of the variable inXML and with the path removed from the output file):
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
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.ss.usermodel.Cell;
public class Main {
public Main() {
// TODO Auto-generated constructor stub
}
public static void main(String[] args) {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("Sample sheet");
short rowNum = 0;
short colNum = 0;
HSSFRow row = sheet.createRow(rowNum++);
Cell cell = row.createCell(colNum);
cell.setCellValue("<data>test data</data>");
try {
FileOutputStream out = new FileOutputStream(new File("Excel.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Produced exactly what you would expect: A spreadsheet with <data>test data</data> in cell A1.
Perhaps cell A1 in your spreadsheet is blank because inXML really is blank.

using HSSF to read an excel file

Emp ID Name Salary
1.0 john 2000000.0
2.0 dean 4200000.0
3.0 sam 2800000.0
4.0 cass 600000.0
I have created this code:
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
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.poifs.filesystem.POIFSFileSystem;
public class sample2
{
public static void main(String[] args) {
new sample2().sample2();
}
}
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(test);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Get iterator to all the rows in current sheet
Iterator<Row> rowIterator = sheet.iterator();
//Get iterator to all cells of current row
Iterator<Cell> cellIterator = row.cellIterator();
try {
FileInputStream file = new FileInputStream(new File("C:\\test.xls"));
//Get the workbook instance for XLS file
HSSFWorkbook workbook = new HSSFWorkbook(file);
//Get first sheet from the workbook
HSSFSheet sheet = workbook.getSheetAt(0);
//Iterate through each rows from first sheet
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch(cell.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
file.close();
FileOutputStream out =
new FileOutputStream(new File("C:\\test.xls"));
workbook.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
for reading the content from this excel file using POI library. My editor is Eclipse. But when i run the program I took this: Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method sample2() is undefined for the type sample2
at sample2.main(sample2.java:17)
Any help?
Thank u in advance!
public class sample2
{
public static void main(String[] args) {
new sample2().sample2(); // This is wrong too.
}
}
All your code after this is pointless. Your class has basically ended with the second }.
You might want to move all that within your main() method.
Also, this piece of code in the main() method new sample2().sample2(); is wrong.
It should be like this
sample2 s = new sample2();
Delete the last curly brace in your code :
{
public static void main(String[] args) {
new sample2().sample2();
}
}
And then creat a method named test2() like this:
public void sample2(){ //Put your code here }

Writing to a existing xls file using POI

The scenario is roughly this:
I have a java program with several methods getting called randomly.
The first method will create an xls file using apache POI and will put the headers for the columns.
All the other methods has to write a record into this file.
The final method will first mail the created xls and then delete the xls.
For above scenario is the below approach correct:
1) Create the file and put the header names in the first method:
Workbook wb = new HSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short)0);
row.createCell(1).setCellValue(createHelper.createRichTextString("First Column"));
row.createCell(2).setCellValue(createHelper.createRichTextString("Second Column"));
row.createCell(3).setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
2) In the remaining methods put the records:
I am not sure of the code here. I know that I can reach the end of the sheet using getRowCount method and then add the new row. But I could not find any example code.
Also, how to access the existing xls file ?
3) In the last method, the file will be mailed and then deleted.
Do I need to perform any other steps before deleting the file ?
This was what I was looking for:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
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 PoiWriteExcelFile {
public void methodOne() {
System.out.println("Into method one!");
Workbook wb = new HSSFWorkbook();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
CellStyle cs = wb.createCellStyle();
cs.setFont(f);
CreationHelper createHelper = wb.getCreationHelper();
Sheet sheet = wb.createSheet("First Sheet");
Row row = sheet.createRow((short) 0);
Cell c = null;
c = row.createCell(0);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("First Column"));
c = row.createCell(1);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Second Column"));
c = row.createCell(2);
c.setCellStyle(cs);
c.setCellValue(createHelper.createRichTextString("Third Column"));
// Write the output to a file
FileOutputStream fileOut;
try {
fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method one!");
}
public void methodTwo() {
System.out.println("Into method two!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("First Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("First Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("First Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method two!");
}
public void methodThree() {
System.out.println("Into method three!");
InputStream inp;
try {
inp = new FileInputStream("C:\\TestData\\POI\\poi-test.xls");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.createRow((short) (sheet.getLastRowNum() + 1));
Cell c = null;
CreationHelper createHelper = wb.getCreationHelper();
c = row.createCell(0);
c.setCellValue(createHelper.createRichTextString("Second Row First value"));
c = row.createCell(1);
c.setCellValue(createHelper.createRichTextString("Second Row Second value"));
c = row.createCell(2);
c.setCellValue(createHelper.createRichTextString("Second Row Third value"));
FileOutputStream fileOut = new FileOutputStream("C:\\TestData\\POI\\poi-test.xls");
wb.write(fileOut);
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Out of method three!");
}
public void methodFour() {
System.out.println("Into method four!");
File file = new File("C:\\TestData\\POI\\poi-test.xls");
// file.deleteOnExit();
System.out.println("Out of method four!");
}
public static void main(final String[] args) {
PoiWriteExcelFile myObj = new PoiWriteExcelFile();
myObj.methodOne();
myObj.methodTwo();
myObj.methodThree();
myObj.methodFour();
}
}

Categories

Resources