java.lang.NullPointerException at org.apache.poi.xssf.usermodel - java

In the actual pipeline (locally it works) I am getting an error:
[Utils] [ERROR] [Error] java.lang.NullPointerException
at org.apache.poi.xssf.usermodel.XSSFWorkbook.getSheet(XSSFWorkbook.java:1112)
at utilities.ExcelData
See this screenshot for the full error message.
Below is the code that I've used.
#DataProvider
public Object[][] GetDataFromExcelSheet() throws Exception {
System.out.println("Enter GetDataFromExcelSheet");
// Get all the data of excel method
// Main Objective: Create data array which will contain excel data
ExcelDataProvider excelDataProviderObj = new ExcelDataProvider();
// 1. Find excel sheet name
excelDataProviderObj.GetSheetName(PropertiesfileDataProvider.GetPropertyValue("nameofthesheet"));
// 2. Find total rows of excel
int rows = excelDataProviderObj.FindTotalRows();
System.out.println("number of rows found as: " +rows);
Object[][] data = new Object[rows][6];
for (int i = 0; i < rows; i++)
{
data[i][0] = excelDataProviderObj.GetCellData(i, 0);
data[i][1] = excelDataProviderObj.GetCellData(i, 1);
data[i][2] = excelDataProviderObj.GetCellData(i, 2);
data[i][3] = excelDataProviderObj.GetCellData(i, 3);
data[i][4] = excelDataProviderObj.GetCellData(i, 4);
data[i][5] = excelDataProviderObj.GetCellData(i, 5);
}
System.out.println("Exit GetDataFromExcelSheet");
return data;
}
public class ExcelDataProvider
{
XSSFSheet sheetName;
public void GetSheetName(String SheetName) throws Exception
{
System.out.println("Enter GetSheetName");
File file=new File(".\\TestData\\TestData.xlsx");
FileInputStream fs=new FileInputStream(file);
XSSFWorkbook wb=new XSSFWorkbook(fs);
//CommonFunctions commonFunctionsObj=new CommonFunctions(driver);
if(PropertiesfileDataProvider.GetPropertyValue("URL").contains("urltag"))
{
sheetName= wb.getSheet(SheetName);
}
else
sheetName= wb.getSheet(SheetName);
System.out.println("Exit GetSheetName");
}
public int FindTotalRows()
{
int totalRows=sheetName.getLastRowNum()+1;
//System.out.println(totalRows);
//System.out.println(sheetName);
return totalRows;
}
public String GetCellData(int row,int column)
{
String data=sheetName.getRow(row).getCell(column).getStringCellValue();
//String data=sheetName.getRow(row).getCell(column).getColumnIndex();
//String data=sheetName.getRow(row).getCell(column).toString();
System.out.println(data);
return data;
}
}

Related

Reduce number of arguments when calling from DataProviders in testng using java

I am reading the data from Excel file, let us say I have 5 rows and 15 columns in Java testNG.
Review the below code
Class ReadExcel {
public String[][] getCellData(String path, String sheetName) throws InvalidFormatException, IOException {
FileInputStream stream = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(stream);
Sheet s = workbook.getSheet(sheetName);
int rowcount = s.getLastRowNum();
int cellcount = s.getRow(0).getLastCellNum();
String data[][] = new String[rowcount][cellcount];
FormulaEvaluator evaluator= workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter df = new DataFormatter();
for (int i = 1; i <= rowcount; i++) {
Row r = s.getRow(i);
for (int j = 0; j < cellcount; j++) {
Cell c = r.getCell(j);
try {
if(c!=null){
if (c.getCellType() == c.CELL_TYPE_STRING) {
data[i - 1][j] = c.getStringCellValue();
}else if (c.getCellType() == c.CELL_TYPE_FORMULA) {
data[i - 1][j] = df.formatCellValue(c, evaluator);
}
else if (c.getCellType() == c.CELL_TYPE_BOOLEAN) {
data[i - 1][j] = df.formatCellValue(c, evaluator);
}
else{
data[i - 1][j] = String.valueOf(c.getNumericCellValue());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
return data;
}
}
Another class for processing the data
public class Sample
{
ReadExcel read = new ReadExcel();
#DataProvider (parallel= true)
public String[][] getFilterValues() throws InvalidFormatException, IOException, InterruptedException{
return read.getCellData("fileLoc","fileName");
}
#Test(dataProvider = "getFilterValues")
public void verifyReports(String row, String name, String age, String lastname and so on...) throws Exception
{
System.out.println(FileName);
}
So, here I need to reduce the argument count in verifyReports method and should able to retrieve the entire records in the same method.
Note: Argument count may be changed in future.
So I tried with Map concept but I could not find out.
The main goal is to reduce the no. of arguments in verifyReports method. How to achieve this.
I achieved by using the below code. But it would be in 2D array in order to use it in testNG DataProviders
Below is the code, I tried using list of map.
public ArrayList<String> readHeader(String path, String sheetName) throws IOException
{
FileInputStream stream = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(stream);
Sheet s = workbook.getSheet(sheetName);
int rowcount = s.getLastRowNum();
int cellcount = s.getRow(0).getLastCellNum();
ArrayList<String> al = new ArrayList<String>();
Row r = s.getRow(0);
for(int i=0;i<cellcount;i++)
{
Cell c = r.getCell(i);
al.add(c.getStringCellValue());
}
return al;
}
public ArrayList<HashMap<String,String>> getCellData(String path, String sheetName) throws InvalidFormatException, IOException {
//ExcelConfig ec = new ExcelConfig();
FileInputStream stream = new FileInputStream(path);
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
XSSFWorkbook workbook = new XSSFWorkbook(stream);
Sheet s = workbook.getSheet(sheetName);
int rowcount = s.getLastRowNum();
int cellcount = s.getRow(0).getLastCellNum();
FormulaEvaluator evaluator= workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter df = new DataFormatter();
ArrayList<String> head = ec.readHeader(path, sheetName);
for (int i = 1; i <= rowcount; i++) {
HashMap<String,String> map = new HashMap<String,String>();
Row r = s.getRow(i);
for (int j = 0; j < cellcount; j++) {
Cell c = r.getCell(j);
try {
if(c!=null){
if (c.getCellType() == c.CELL_TYPE_STRING) {
map.put(head.get(j), c.getStringCellValue());
}else if (c.getCellType() == c.CELL_TYPE_FORMULA) {
map.put(head.get(j), df.formatCellValue(c, evaluator));
}
else if (c.getCellType() == c.CELL_TYPE_BOOLEAN) {
map.put(head.get(j), df.formatCellValue(c, evaluator));
}
else{
map.put(head.get(j), String.valueOf(c.getNumericCellValue()));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
list.add(map);
}
return list;
}
public void multiRec() throws InvalidFormatException, IOException
{
ArrayList<HashMap<String, String>> map = read.getCellData(fileLoc,"ComparisonStatus");
for(HashMap<String, String> ls : map)
{
System.out.println(ls.get("Row"));
System.out.println(ls.get("FileName"));
}
}
Here, Row and FileName are Excel file header. So now I reduced the no. of arguments. But how to convert it to 2D array will be the task now.
The best way would be to create a class containing all the arguments as fields of the class. Let the class name be CellData
class CellData {
private String row;
private String name;
// and all other relevant fields..
}
In the getCellData method, create and initialize an object of CellData with the relevant values of each row and instead of returning String[][] return CellData[]. Then make the below changes:
#DataProvider (parallel= true)
public Object[][] getFilterValues() throws InvalidFormatException, IOException, InterruptedException{
CellData[] cellData = read.getCellData("fileLoc","fileName");
Object[][] data = new Object[cellData.length][];
for(int i = 0; i < cellData.length; i++) {
data[i][0] = cellData[i];
}
return data;
}
#Test(dataProvider = "getFilterValues")
public void verifyReports(CellData data) throws Exception
{
// test code.
}
Since you are saying that new arguments could be introduced in the future, using a class would be very much beneficial as it could help the code be maintainable and readable. Any future updates would also require much less code changes as there is no need of updating the DataProvider method or the test method. The only change would be a new field in the CellData class and setting the values for the new fields in getCellData method.

write data into excel dynamically in selenium java

After executing a test case with multiple parameters I am passing the result (Pass/Fail) into an excel sheet. there are 6 rows the 1st result fail is entering into all the 6 rows (it should enter into only 1st row), the 2nd result pass is starting from 1st row and entering into all the 6 rows
Getting Data Code
public static Object[][] getData() throws IOException{
int rowCount = ExcelUtil.getRowCount();
int colCount = ExcelUtil.getColumnCount();
Object[][] data = new Object[rowCount-1][colCount];
for(int i=1; i<rowCount; i++)
{
for(int j=0; j<colCount; j++)
{
//Check cell is empty or not
if (data[i-1][j] == null) {
data[i-1][j] = "";
}
//change values to string
data[i-1][j] = ExcelUtil.setCellDataToString(i, j);
}
}
return data;
}
Test Case
public static void signIn(String email, String password, String result) throws IOException, InterruptedException {
LoginPage lp = PageFactory.initElements(driver, LoginPage.class);
driver.navigate().to(loginUrl);
lp.email().sendKeys(email);
lp.password().sendKeys(password);
lp.submitlogin().click();
//Verify
String expectedUrl = "http://automationpractice.com/index.php?controller=my-account";
String actualUrl = driver.getCurrentUrl();
String loginmessage;
if (expectedUrl.equalsIgnoreCase(actualUrl)) {
loginmessage = "pass";
lp.logout().click();
}else {
loginmessage ="fail";
}
ExcelUtil.writeIntoExcel(filePath, loginmessage);
}
Writing into excel
public static void writeIntoExcel(String FilePath, String dataToWrite) throws IOException {
int rowCount = ExcelUtil.getRowCount();
int colCount = ExcelUtil.getColumnCount();
try {
for (int i = 1; i <= rowCount; i++) {
shFile.getRow(i).createCell(colCount-1).setCellValue(dataToWrite);
fileOut = new FileOutputStream(filePath);
wbFile.write(fileOut);
}
fileOut.close();
} catch (Exception e) {
System.out.println("Data is not entered into excel");
}
}
You should not be iterating rows for each test run. Change method
public static void writeIntoExcel
to find row number based on email and password content and then create cells of result into that row.

JXL Changing Columns for JSOUP-based Application

Currently, this program will run down a column of URLs and output the selected data to the neighboring cell. I can set which column it starts on, but that is all I can do. Right now, I only have it working on one column. How can I instruct it to go to say, column 4 (Column E) and work top down once it is through with column 0 (A)? And then perhaps another, say column J after that?
I believe my problem lies within the "while (!(cell = sheet.getCell..." line, but I am unsure of what to change there without breaking the program.
My code is as follows:
public class App {
private static final int URL_COLUMN = 0; // Column A
private static final int PRICE_COLUMN = 1; //Column B
public static void main(final String[] args) throws Exception {
Workbook originalWorkbook = Workbook.getWorkbook(new File("C:/Users/Shadow/Desktop/original.xls"));
WritableWorkbook workbook = Workbook.createWorkbook(new File("C:/Users/Shadow/Desktop/updated.xls"), originalWorkbook);
originalWorkbook.close();
WritableSheet sheet = workbook.getSheet(0);
int currentRow = 1;
Cell cell;
while (!(cell = sheet.getCell(URL_COLUMN, currentRow)).getType().equals(CellType.EMPTY)) {
String url = cell.getContents();
System.out.println("Checking URL: " + url);
if (url.contains("scrapingsite1.com")) {
String Price = ScrapingSite1(url);
System.out.println("Scraping Site1's Price: " + Price);
Label cellWithPrice = new Label(PRICE_COLUMN, currentRow, Price);
sheet.addCell(cellWithPrice);
}
currentRow++;
}
workbook.write();
workbook.close();
}
private static String ScrapingSite1 (String url) throws IOException {
Document doc = null;
for (int i=1; i <= 6; i++) {
try {
doc = Jsoup.connect(url).userAgent("Mozilla/5.0").timeout(6000).validateTLSCertificates(false).get();
break;
} catch (IOException e) {
System.out.println("Jsoup issue occurred " + i + " time(s).");
}
}
if (doc == null){
return null;
}
else{
return doc.select("p.price").text();
}
}
}
To simplify the code I made an assumption that the price comes always to the next column (+1).
Also to process few columns instead of using single value int URL_COLUMN = 0 I replaced it with array of columns to process: int[] URL_COLUMNS = { 0, 4, 9 }; // Columns A, E, J.
You can then loop over every column {0, 4, 9} and save the data to the next column {1, 5, 10}.
private static final int[] URL_COLUMNS = { 0, 4, 9 }; // Columns A, E, J
public static void main(final String[] args) throws Exception {
Workbook originalWorkbook = Workbook.getWorkbook(new File("C:/Users/Shadow/Desktop/original.xls"));
WritableWorkbook workbook = Workbook.createWorkbook(new File("C:/Users/Shadow/Desktop/updated.xls"), originalWorkbook);
originalWorkbook.close();
WritableSheet sheet = workbook.getSheet(0);
Cell cell;
// loop over every column
for (int i = 0; i < URL_COLUMNS.length; i++) {
int currentRow = 1;
while (!(cell = sheet.getCell(URL_COLUMNS[i], currentRow)).getType().equals(CellType.EMPTY)) {
String url = cell.getContents();
System.out.println("Checking URL: " + url);
if (url.contains("scrapingsite1.com")) {
String Price = ScrapingSite1(url);
System.out.println("Scraping Site1's Price: " + Price);
// save price into the next column
Label cellWithPrice = new Label(URL_COLUMNS[i] + 1, currentRow, Price);
sheet.addCell(cellWithPrice);
}
currentRow++;
}
}
workbook.write();
workbook.close();
}

read multiple excel sheet selenium-webdriver, java, eclipse

I want to run selenium-webdriver-java-eclipse, using excel file contains multiple excel sheets with different name(sheet1,sheet2,sheet3,...), i need a for loop help me to do that and read from this sheets.
public class ExcelDataConfig {
XSSFWorkbook wb;
XSSFSheet sheet = null;
public ExcelDataConfig(String Excelpath) throws IOException {
// TODO Auto-generated method stub
try {
File file = new File(Excelpath);
// Create an object of FileInputStream class to read excel file
FileInputStream fis = new FileInputStream(file);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
}
}
public String GetData(int sheetNumber, int Row, int Column) {
Iterator<Row> rowIt=sheet.rowIterator();
DataFormatter formatter = new DataFormatter();
XSSFCell cell = sheet.getRow(Row).getCell(Column);
String data = formatter.formatCellValue(cell);
return data;
}
public int GetRowCount(String sheetNumber) {
int row = wb.getSheet(sheetNumber).getLastRowNum();
row = row + 1;
return row;
}
}
try something like this, it is working for me you need to add the sheet numbers and cell numbers at the places of k and j
enter code here
String filePath="C:\\Users\\USER\\Desktop\\Book1.xlsx";// file path
FileInputStream fis=new FileInputStream(filePath);
Workbook wb=WorkbookFactory.create(fis);
ArrayList<String> ls=new ArrayList<String>();
for(int k=0; k<=3;k++)//k =sheet no
{
Sheet sh=wb.getSheetAt(k);
System.out.println(sh);
// int count=0;
for(int i=0;i<=sh.getLastRowNum();i++)
{
System.out.println("row no:"+i);
for(int j=0; j<=4;j++)//j=column no
{
try {
String values=sh.getRow(i).getCell(j).getStringCellValue().trim();
System.out.println(values);
//condetions
/* if(values.contains("condtn1"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}
if(values.contains("condn2"))
{
System.out.println("Value of cell "+values+" ith row "+(i+1));
ls.add(values);
count++;
}*/
}catch(Exception e){
}
}
}
}
}
}
Please try writing similar to something like this:
for (int i = startRow; i < endRow + 1; i++) {
for (int j = startCol; j < endCol + 1; j++) {
testData[i - startRow][j - startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
Terms used in method are pretty self explanatory. Let us know if you get stuck or need more info.

How to add Headers to multiple sheets in a workbook using Apache POI

I have created a Batch Reporting using Apache POI. I need to know how to add Headers to both sheets. I used getHeader() but that adds same Headers for both sheets and I need to add different headers to both sheets. My code is following.
Excel Writer:
public class ExcelWriter {
Logger log = Logger.getLogger(ExcelWriter.class.getName());
private HSSFWorkbook excel;
public ExcelWriter() {
excel = new HSSFWorkbook();
}
public HSSFWorkbook getWorkbook() {
return excel;
}
public void writeExcelFile(String filename, String[] columns, Object[][] data, HSSFCellStyle[] styles,
HSSFCellStyle columnsStyle, String[] header, String[] footer) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
HSSFSheet sheet = excel.createSheet("Daily Screening");
HSSFSheet sheet1 = excel.createSheet("Parcel Return");
int numHeaderRows = header.length;
createHeader(sheet,header,columns.length, 0);
createColumnHeaderRow(sheet,columns,numHeaderRows,columnsStyle);
int rowCtr1 = numHeaderRows;
for( int i = 0; i < data.length; i++) {
if (i > data.length -2)
++rowCtr1;
else
rowCtr1 = rowCtr1 + 2;
createRow(sheet, data[i], rowCtr1, styles);
}
int totalRows = rowCtr1 + 1;
createHeader(sheet1,footer,columns.length, totalRows);
excel.write(out);
out.close();
}
private void createHeader(HSSFSheet sheet1, String[] header, int columns, int rowNum) {
for( int i = 0; i < header.length ; i++ ) {
HSSFRow row = sheet1.createRow(i + rowNum);
HSSFCell cell = row.createCell((short) 0);
String text = header[i];
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
HSSFCellStyle style = excel.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont arialBoldFont = excel.createFont();
arialBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
arialBoldFont.setFontName("Arial");
arialBoldFont.setFontHeightInPoints((short) 12);
style.setFont(arialBoldFont);
if (!isEmpty(header[i]) && rowNum < 1) {
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
}
cell.setCellStyle(style);
sheet1.addMergedRegion( new Region(i+rowNum,(short)0,i+rowNum,(short)(columns-1)) );
}
}
private HSSFRow createColumnHeaderRow(HSSFSheet sheet, Object[] values, int rowNum, HSSFCellStyle style) {
HSSFCellStyle[] styles = new HSSFCellStyle[values.length];
for( int i = 0; i < values.length; i++ ) {
styles[i] = style;
}
return createRow(sheet,values,rowNum,styles);
}
private HSSFRow createRow(HSSFSheet sheet1, Object[] values, int rowNum, HSSFCellStyle[] styles) {
HSSFRow row = sheet1.createRow(rowNum);
for( int i = 0; i < values.length; i++ ) {
HSSFCell cell = row.createCell((short) i);
cell.setCellStyle(styles[i]);
try{
Object o = values[i];
if( o instanceof String ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
else if (o instanceof Double) {
Double d = (Double) o;
cell.setCellValue(d.doubleValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if (o instanceof Integer) {
Integer in = (Integer)o;
cell.setCellValue(in.intValue());
}
else if (o instanceof Long) {
Long l = (Long)o;
cell.setCellValue(l.longValue());
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
}
else if( o != null ) {
String text = String.valueOf(o);
cell.setCellValue(text);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
}
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return row;
}
public boolean isEmpty(String str) {
if(str.equals(null) || str.equals(""))
return true;
else
return false;
}
}
Report Generator which includes Headers, footer, and columns:
public class SummaryReportGenerator extends ReportGenerator {
Logger log = Logger.getLogger(SummaryReportGenerator.class.getName());
public SummaryReportGenerator(String reportDir, String filename) {
super( reportDir + filename + ".xls", reportDir + filename + ".pdf");
}
public String[] getColumnNames() {
String[] columnNames = {"ISC\nCode", "Total\nParcels", "Total\nParcel Hit\n Count",
"Filter Hit\n%", "Unanalyzed\nCount", "Unanalyzed\n%",
"Name\nMatch\nCount", "Name\nMatch\n%", "Pended\nCount",
"Pended\n%", "E 1 Sanction\nCountries\nCount", "E 1 Sanction\nCountries\n%", "Greater\nthat\n$2500\nCount", "Greater\nthat\n$2500\n%",
"YTD\nTotal Hit\nCount", "YTD\nLong Term\nPending", "YTD\nLong Term\n%"};
return columnNames;
}
public HSSFCellStyle getColumnsStyle(HSSFWorkbook wrkbk) {
HSSFCellStyle style = wrkbk.createCellStyle();
style.setWrapText(true);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont timesBoldFont = wrkbk.createFont();
timesBoldFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
timesBoldFont.setFontName("Arial");
style.setFont(timesBoldFont);
return style;
}
public Object[][] getData(Map map) {
int rows = map.size();// + 1 + // 1 blank row 1; // 1 row for the grand total;
int cols = getColumnNames().length;
Object[][] data = new Object[rows][cols];
int row = 0;
for (int i=0; i < map.size(); i++ ){
try{
SummaryBean bean = (SummaryBean)map.get(new Integer(i));
data[row][0] = bean.getIscCode();
data[row][1] = new Long(bean.getTotalParcelCtr());
data[row][2] = new Integer(bean.getTotalFilterHitCtr());
data[row][3] = bean.getFilterHitPrctg();
data[row][4] = new Integer(bean.getPendedHitCtr());
data[row][5] = bean.getPendedHitPrctg();
data[row][6] = new Integer(bean.getTrueHitCtr());
data[row][7] = new Integer(bean.getRetiredHitCtr());
data[row][8] = new Integer(bean.getSanctCntryCtr());
data[row][9] = new Integer(bean.getC25Ctr());
data[row][10] = new Integer(bean.getCnmCtr());
data[row][11] = new Integer(bean.getCndCtr());
data[row][12] = new Integer(bean.getCnlCtr());
data[row][13] = new Integer(bean.getCneCtr());
data[row][14] = new Integer(bean.getVndCtr());
data[row][15] = new Integer(bean.getCilCtr());
data[row][16] = new Integer(bean.getHndCtr());
data[row][17] = new Integer(bean.getCnrCtr());
++row;
}
catch(Exception e) {
log.error(e.getMessage());
}
}
return data;
}
public String[] getHeader(String startDate, String endDate) {
Date today = new Date();
String reportDateFormat = Utils.formatDateTime(today, "MM/dd/yyyyHH.mm.ss");
String nowStr = Utils.now(reportDateFormat);
String[] header = {"","EXCS Daily Screening Summary Report ","",
"for transactions processed for the calendar date range",
"from " + startDate + " to " + endDate,
"Report created on " + nowStr.substring(0,10)+ " at "
+ nowStr.substring(10)};
return header;
}
public HSSFCellStyle[] getStyles(HSSFWorkbook wrkbk) {
int columnSize = getColumnNames().length;
HSSFCellStyle[] styles = new HSSFCellStyle[columnSize];
HSSFDataFormat format = wrkbk.createDataFormat();
for (int i=0; i < columnSize; i++){
styles[i] = wrkbk.createCellStyle();
if (i == 0){
styles[i].setAlignment(HSSFCellStyle.ALIGN_LEFT);
}else{
styles[i].setAlignment(HSSFCellStyle.ALIGN_RIGHT);
}
if (i == 1 || i == 2){
styles[i].setDataFormat(format.getFormat("#,###,##0"));
}
HSSFFont timesFont = wrkbk.createFont();
timesFont.setFontName("Arial");
styles[i].setFont(timesFont);
}
return styles;
}
public String[] getFooter() {
String[] header = {"","Parcel Return Reason Code Reference","",
"DPM = Sender and/or recipient matches denied party",
"HND = Humanitarian exception not declared",
"CNM = Content not mailable under export laws",
"VND = Value of content not declared",
"CNR = Customer non-response",
"C25 = Content Value greater than $2500",
"CIL = Invalid license",
"C30 = More than one parcel in a calendar month",
"CNL = Content description not legible",
"CNE = Address on mailpiece not in English",
"RFN = Requires full sender and addressee names",
"DGS = Dangerous goods",
"R29 = RE-used 2976 or 2976A",
"ANE = PS Form 2976 or 2976A not in English",
"ICF = Incorrect Customs Declaration Form used",
"DPR = Declaration of purpose required",
"ITN = Internal Transaction Number (ITN), Export Exception/Exclusion Legend (ELL), or Proof of Filing Citation (PFC) is required",
"OTH = Other","",};
return header;
}
}
Report Generator Abstract class
public void generateExcelReport(Map map, String startDate, String endDate) throws IOException {
ExcelWriter writer = new ExcelWriter();
writer.writeExcelFile( getXlsFilename(), getColumnNames(), getData(map),
getStyles(writer.getWorkbook()), getColumnsStyle(writer.getWorkbook()),
getHeader(startDate, endDate), getFooter());
Report Driver:
public class ReportDriver {
static Logger log = Logger.getLogger(ReportDriver.class.getName());
public static void main (String args[]){
if (args.length == 0) {
log.error("Usage - ReportDriver [Day|Week|Month|Year]");
System.exit(1);
}
String reportPeriod = args[0];
log.info("Begin Prior " + reportPeriod + " Report");
String dir = "c:\\excsbatch\\report\\";
Dates dates = new Dates();
dates.setDates(reportPeriod);
String startDate = dates.getStartDate();
String endDate = dates.getEndDate();
DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
Calendar cal = Calendar.getInstance();
String timeStamp = dateFormat.format(cal.getTime());
String fileName = "prior" + reportPeriod + "Report" + timeStamp;
SummaryDAO dao = new SummaryDAO();
Map map = dao.extractData(startDate, endDate);
SummaryReportGenerator report = new SummaryReportGenerator(dir, fileName);
try {
report.generateExcelReport(map, startDate, endDate);
}
catch(Exception e) {
log.error(e.getMessage());
System.exit(2);
}
log.info("End Prior " + reportPeriod + " Report");
}
}

Categories

Resources