I have created a test where I am reading from excel and iterating through a worksheet to process an application in a web portal. This is working as expected.
However I am now trying to write results from the web page into another sheet on the same excel. The test case I am running passes in Eclipse but no data is written to the specified sheet. (I'm also looking to iterate on the results sheet to capture multiple application records, haven't got to that part yet).
Please see below my test script and the methods I have created in an ExcelConfig util sheet. Hoping someone can advise where I'm going wrong, thanks in advance.
Steve
Test Case
package com.htb.puma.uatTests;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import com.htb.puma.pages.SMcaseHeader;
import com.htb.puma.pages.SMhome;
import com.htb.puma.pages.SMloanDetails;
import com.htb.puma.pages.SMlogin;
import com.htb.puma.pages.SetUpConfig;
import com.htb.puma.util.ExcelConfig;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import java.io.File;
import java.io.IOException;
public class THAM_WRITE_Test {
WebDriver driver;
#Test
public void specMortHome() throws NoAlertPresentException, InterruptedException, IOException {
// calling drivers from the SetUpConfig page
driver = SetUpConfig.getChromeDriver();
// driver = SetUpConfig.getFirefoxDriver();
// driver = SetUpConfig.getIEDriver();
String path = new File("src/test/resources/TestData.xlsx").getAbsolutePath();
ExcelConfig excel = new ExcelConfig(path);
int row = 1;
while (excel.getData("PDFRollUp", row, 0) != "") {
String loanAmReq = excel.getNumericData("PDFRollUp", row, 6);
// LOGIN
SMlogin specMortLogin = new SMlogin(driver);
specMortLogin.openSMlogin();
specMortLogin.maximiseWindow();
specMortLogin.enterUsername("OpsAdminAuto");
specMortLogin.enterPassword("AutoOps123!");
specMortLogin.clickSignInBtn();
Thread.sleep(2000);
SMhome specMortHome = new SMhome(driver);
specMortHome.clickTopMC();
Thread.sleep(2000);
SMcaseHeader specMortCaseHeader = new SMcaseHeader(driver);
specMortCaseHeader.clickLoanDetailsTab();
SMloanDetails specMortLoanDetails = new SMloanDetails(driver);
Thread.sleep(2000);
specMortLoanDetails.enterLoanAmReq(Keys.CONTROL + "a"); // PDF
specMortLoanDetails.enterLoanAmReq(loanAmReq); // PDF
String erc = specMortLoanDetails.getERC();
String ltv = specMortLoanDetails.getLTV();
excel.createFile("src/test/resources/TestData.xlsx");
excel.writeStringData("Results", 1, 1, erc);
excel.writeStringData("Results", 1, 2, ltv);
specMortHome.clickUserActionsHomeLM();
specMortHome.clickLogoutHomeLM();
row++;
}
driver.quit();
}
}
Excel Config
package com.htb.puma.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class ExcelConfig {
public XSSFWorkbook wb;
XSSFSheet sheet1;
public ExcelConfig(String Excelpath) {
File src = new File(Excelpath);
try {
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
System.out.println("Excel file not loaded");
}
}
// reads the string in the excel file
public String getData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
data = sheet1.getRow(row).getCell(column).getStringCellValue();
} catch (NullPointerException e) {
data = "";
}
return data;
}
// reads the number in the excel file
public String getNumericData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
// data = sheet.getRow(row).getCell(column).getRawValue();
DataFormatter dataFormatter = new DataFormatter();
Cell cell = sheet1.getRow(row).getCell(column);
data = dataFormatter.formatCellValue(cell);
} catch (NullPointerException e) {
data = "";
}
return data;
}
//write string data into excel
public void writeStringData(String sheetName, int row, int column, String data) {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
}
//creates an excel file
public void createFile(String path) {
File src = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(src);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
write(java.io.OutputStream stream) is used to write data to the excel file
public void writeStringData(String sheetName, int row, int column, String data) {
try {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
FileOutputStream fout;
fout = new FileOutputStream(new File("<path>"));
//fout = new FileOutputStream("src/test/resources/TestData.xlsx" );
wb.write(fout);
// fout.flush();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Related
I have some records with header in my excel sheet.I want to read all the records and write to the docx file along with header using java.Thanks for the helps.
Able to write one excel to other excel file but failed to write in docx file.
I have try this way but the word file is generated as corrupted.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH =
"C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH ="C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException,
InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new
File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + "
Sheets : ");
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();
}
workbook.close();
}
}
I would suggest to use Apache Poi lib (https://poi.apache.org/)
Rewrite your code like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH = "C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE !!!");
}
}
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);
}
}
}
I am trying to read the following data from an Excel sheet
With the following code
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public String readUsernameFromExcel() {
File src = new File("C:/filepath.xls");
try {
Workbook wb = Workbook.getWorkbook(src);
Sheet sh1 = wb.getSheet(0);
Cell a2 = sh1.getCell(0, 2);
data1 = a2.getContents().trim();
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data1;
}
So when I try and get the cell 0,1 I can pick up the username 1000483 just fine. But when I try to read 0,2 and I get java.lang.ArrayIndexOutOfBoundsException: 2.
What I'm trying to do is read data from an excel sheet return it as a String and then pass it in to login my application. But it seems when I try 0,2 I'm going outside of what is expected. I've tried a few things such as a for loop
for (int rows = 0; rows < sh1.getRows(); rows++) {
Sheet sh1 = wb.getSheet(0);
Cell a2 = sh1.getCell(0, 2);
}
I understand the first number is the column and the second is the row. I also understand that the code isn't able to see past 0,1. I'm just at a loss as to how to get it to see the rest of the sheet after trying other solutions of the same problem.
sh1.getRows() returns 3. As loop starts from 0, sh1.getRows() needs to be decremented by 1 (as below). Below loop works fine and returns value properly.
import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class Excel {
public static void main(String[] args) {
File src = new File("c:/filepath.xls");
try {
String data1;
Workbook wb = Workbook.getWorkbook(src);
Sheet sh1 = wb.getSheet(0);
for (int rows = 1; rows < sh1.getRows(); rows++) {
for (int column = 0; column <= sh1.getColumns()-1; column++) {
Cell a2 = sh1.getCell(column, rows);
data1 = a2.getContents().trim();
System.out.println(data1);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
The above code works and fetches the date without error
I use the same data with you, and I could get 1000484 value through my code.
Here is my code :
package com.jason.xls;
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class XlsParser {
public static void main(String[] args) {
final String path = "/home/coder/filepath.xls";
System.out.println(readUserNameFromXls(path));
}
public static String readUserNameFromXls(final String path) {
File file = new File(path);
try {
Workbook wb = Workbook.getWorkbook(file);
Sheet sheet = wb.getSheet(0);
Cell a2 = sheet.getCell(0, 2);
return a2.getContents().trim();
} catch (Exception e) {
return null;
}
}
}
I download jxl.jar from jxl.jar download here
My code result is : Code Result Image
I am creating an excel sheet using Apache POI and then sending the same file using Java GWT.The file created is all right.Now in the mail there are two options- Save or open.When I save the file in machine it is working fine but when I try to open ,it opens in notepad.In the suggestion too it is not showing excel. Here is my code to create the excel sheet:
package com.ericsson.egi.sxs.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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;
import com.ericsson.egi.sxs.persistence.entity.AssetOrder;
public class CreateExcelFile {
int rownum = 0;
HSSFSheet firstSheet;
Collection<File> files;
HSSFWorkbook workbook;
CreateExcelFile() {
}
public File createWeeklyReport(List<AssetOrder> tempOrderList) throws Exception {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
List<String> headerRow = new ArrayList<String>();
headerRow.add("Name of Supplier/Vendor");
headerRow.add("Description of Contract");
headerRow.add("Initiator");
headerRow.add("Type Of Contract");
headerRow.add("Template Source");
headerRow.add("Savings");
headerRow.add("Payment Term");
headerRow.add("Code of Conduct Signed by Supplier");
headerRow.add("RoHS clause Included");
headerRow.add("Agreement No");
headerRow.add("Agreement Validity From ");
headerRow.add("Agreement Validity To");
headerRow.add("Sanctioned Parties List Screening");
headerRow.add("Sanctioned Parties List Screening Reasons in case no answer NO");
headerRow.add("Registered in CLM");
headerRow.add("Registered in CLM reasons if answer NO");
headerRow.add("Current State");
headerRow.add("Next State");
headerRow.add("TAT for L1");
headerRow.add("TAT for L2");
headerRow.add("TAT for L3");
headerRow.add("TAT for L4");
headerRow.add("Current State Comments");
List<List> recordToAdd = new ArrayList<List>();
recordToAdd.add(headerRow);
for (AssetOrder order : tempOrderList ) {
List<String> row = new ArrayList<String>();
row.add(order.getSourcingDetails().getVendorName());
row.add(order.getSourcingDetails().getContractDescription());
row.add(order.getSourcingDetails().getInitiatorName());
row.add(order.getSourcingDetails().getContractType());
row.add(order.getSourcingDetails().getTemplateSource());
row.add(order.getSourcingDetails().getSavings());
row.add(order.getSourcingDetails().getPaymentTerm());
if (order.getSourcingDetails().getIsCOCSigned()) {
row.add("YES");
} else {
row.add("NO");
}
if (order.getSourcingDetails().getIsROHSIncluded()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getAgreementNo());
row.add(order.getSourcingDetails().getValidityFrom().toString());
row.add(order.getSourcingDetails().getValidityTo().toString());
if (order.getSourcingDetails().getIsSPLScreening()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForSPL());
if (order.getSourcingDetails().getIsRegisteredInCLM()) {
row.add("YES");
} else {
row.add("NO");
}
row.add(order.getSourcingDetails().getReasonsForCLM());
row.add(order.getStatusMaster().getStatusName());
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(null);
row.add(order.getComments());
recordToAdd.add(row);
}
CreateExcelFile cls = new CreateExcelFile(recordToAdd);
File file = cls.createExcelFile(tempOrderList.get(0).getOrderRequesterSignum());
return file;
}
File createExcelFile(String requesterSignum) {
FileOutputStream fos = null;
File file = new File("/tmp/" + requesterSignum + "_StatusReport.xls");
try {
fos=new FileOutputStream(file);
HSSFCellStyle hsfstyle=workbook.createCellStyle();
hsfstyle.setBorderBottom((short) 1);
hsfstyle.setFillBackgroundColor((short)245);
workbook.write(fos);
} catch (Exception e) {
e.printStackTrace();
}
return file;
}
CreateExcelFile(List<List> l1) throws Exception {
try {
workbook = new HSSFWorkbook();
firstSheet = workbook.createSheet("FIRST SHEET");
for (int j = 0; j < l1.size(); j++) {
Row row = firstSheet.createRow(rownum);
List<String> l2= l1.get(j);
for(int k=0; k<l2.size(); k++)
{
Cell cell = row.createCell(k);
cell.setCellValue(l2.get(k));
}
rownum++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
}
Try with other Excel Extension as per your Excel version installed on your machine.
--EDIT--
May be the issue is related to Content Type. Please confirm what are you using for this?
response.setContentType("APPLICATION/OCTET-STREAM");
// try this one if above doesn't work
//response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=myExcel.xls");
I would like to dynamically generate multiple worksheets for a workbook/excel in Apache poi. I want to know how can I do it an efficient and thread safe/concurrent way.
So multiple worksheet dynamically with the option to name them.
Each worksheet will have their own set of columns etc ( or style).
Write return those back in a servlet etc.
Please help.
Thank you.
like this?
public static void createExcel(String excelFilePath, String sheetName)
throws IOException {
FileOutputStream fos = null;
try {
HSSFWorkbook workbook = null;
if (new File(excelFilePath).createNewFile()) {
workbook = new HSSFWorkbook();
} else {
POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream(
new File(excelFilePath)));
workbook = new HSSFWorkbook(pfs);
}
if (workbook.getSheet(sheetName) == null) {
fos = new FileOutputStream(excelFilePath);
workbook.createSheet(sheetName);
workbook.write(fos);
}
} catch (IOException e) {
throw e;
} finally {
if (fos != null) {
fos.close();
}
}
}
Please find the sample code.
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class ExcelUtility {
public static boolean writeDataSheetWise(final String excelFileName, final List<String> headers,
Map<String, List<Object[]>> sheetRowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
for(String sheetName: sheetRowDataList.keySet()) {
createSheet(workbook, sheetName, headers, sheetRowDataList.get(sheetName));
}
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
public static boolean writeData(final String excelFileName, final String sheetName, final List<String> headers,
List<Object[]> rowDataList) throws IOException, InvalidFormatException {
boolean isWritten = false;
HSSFWorkbook workbook = new HSSFWorkbook();
createSheet(workbook, sheetName, headers, rowDataList);
try {
System.out.println("\nWritting data to excel file <" + excelFileName + ">");
FileOutputStream outputStream = new FileOutputStream(new File(excelFileName));
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
isWritten = true;
System.out.println("\nData is successfully written to excel file <"+excelFileName+">.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return isWritten;
}
#SuppressWarnings("deprecation")
private static void createSheet(final HSSFWorkbook workbook, final String sheetName, final List<String> headers,
final List<Object[]> rowDataList) {
HSSFSheet sheet = workbook.createSheet(sheetName);
int rowCount = 0;
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont headersFont = workbook.createFont();
headersFont.setFontName(HSSFFont.FONT_ARIAL);
headersFont.setFontHeightInPoints((short) 16);
headersFont.setColor(HSSFColor.GREEN.index);
headersFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
style.setFont(headersFont);
// Creating header row
Row headerRow = sheet.createRow(rowCount++);
for (int i = 0; i < headers.size(); i++) {
Cell cell = headerRow.createCell(i);
cell.setCellStyle(style);
cell.setCellValue(headers.get(i));
sheet.autoSizeColumn(i);
}
for (Object rowDataObject[] : rowDataList) {
Row row = sheet.createRow(rowCount++);
int cellnum = 0;
for (Object rowData : rowDataObject) {
Cell cell = row.createCell(cellnum++);
if (rowData instanceof Date)
cell.setCellValue((Date) rowData);
else if (rowData instanceof Boolean)
cell.setCellValue((Boolean) rowData);
else if (rowData instanceof String)
cell.setCellValue((String) rowData);
else if (rowData instanceof Integer)
cell.setCellValue((Integer) rowData);
else if (rowData instanceof Long)
cell.setCellValue((Long) rowData);
else if (rowData instanceof Double)
cell.setCellValue((Double) rowData);
}
}
}
}