java.lang.IllegalArgumentException in getting data from an excel file - java

I am fetching data from a excel sheet containing more than 3000 lines. But I am getting an exception like java.lang.IllegalArgumentException: The supplied POIFSFileSystem contained neither a 'Workbook' entry, nor a 'WORKBOOK' entry. Is it really an excel file?
Below is mine code-
public ActionForward exportExtraExcel(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("inside exportExtraExcel----------> ");
// String fileName=request.getParameter("filePath");
// System.out.println("fileName----qqqqqqqqqqqqqq---->"+fileName);
String fileName = "C:\\Users\\apanigrahi\\Desktop\\tt.xls";
Statement st = null;
ResultSet rs = null;
EmployeeDTO employeeDTO = new EmployeeDTO();
List cellDataList = new ArrayList();
try {
FileInputStream fileInputStream = new FileInputStream(fileName);
POIFSFileSystem fsFileSystem = new POIFSFileSystem(fileInputStream);
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);
HSSFSheet hssfSheet = workBook.getSheetAt(0);
int rows = hssfSheet.getLastRowNum() + 1;
int col = -1;
for (int i = 0; i < rows; i++) {
HSSFRow hssfRow = hssfSheet.getRow(i);
if (i == 0)
col = hssfRow.getLastCellNum();
List cellTempList = new ArrayList();
for (int j = 0; j < col; j++) {
HSSFCell hssfCell = hssfRow.getCell((short) j);
cellTempList.add(hssfCell);
}
cellDataList.add(cellTempList);
}
} catch (Exception e)
{
e.printStackTrace();
}
List<Integer> empIdArr = new ArrayList<Integer>();
List<Integer> userIdArr = new ArrayList<Integer>();
List<String> empFnameArr = new ArrayList<String>();
List<String> empLnameArr = new ArrayList<String>();
List<String> employeeIdArr = new ArrayList<String>();
List<String> date1 = new ArrayList<String>();
ArrayList<ArrayList> biometric_Data = getBiometricData(cellDataList);
ArrayList<String> date_biometric_Data = biometric_Data.get(0);
ArrayList<String> emp_code_biometric_Data = biometric_Data.get(1);
ArrayList<String> working_hours_biometric_Data = biometric_Data.get(2);
ArrayList<String> date_biometric_Data1 = new ArrayList<String>();
ArrayList<String> emp_code_biometric_Data1 =new ArrayList<String>();
ArrayList<String> working_hours_biometric_Data1 = new ArrayList<String>();
List<EmployeeDTO> extra_empLeaveSummaryReport = new ArrayList<EmployeeDTO>();
try {
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
for (int j = 0; j < emp_code_biometric_Data.size(); j++)
{
String qry = "select emp_id,user_id,emp_first_name,emp_last_name,employee_id from \"Employee\" where employee_id='"
+ emp_code_biometric_Data.get(j)
+ "' and is_deleted is null and emp_current_country ='1' order by employee_id";
rs = st.executeQuery(qry);
if(rs!=null){
while (rs.next()) {
int empId = rs.getInt(1);
empIdArr.add(empId);
userIdArr.add(rs.getInt(2));
empFnameArr.add(rs.getString(3));
empLnameArr.add(rs.getString(4));
employeeIdArr.add(rs.getString(5));
date_biometric_Data1.add(date_biometric_Data.get(j));
emp_code_biometric_Data1.add(emp_code_biometric_Data.get(j));
working_hours_biometric_Data1.add(working_hours_biometric_Data.get(j));
}
}
connMgr.freeConnection("access", conn);
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("Exception in exportExcelLeaveSummary");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
for (int i = 0; i < employeeIdArr.size(); i++)
{
double hours_worked = Double.parseDouble(working_hours_biometric_Data.get(i));
if (hours_worked < 9.00 && hours_worked > 0.0)
{
String day_status = "Halfday";
try {
System.out.println("Inside if loop Halfday");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where leave_approval_status='Approved' and '"+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
if (hours_worked == 0.0) {
String day_status = "LOP";
try {
System.out.println("Inside if loop LOP");
UserManager userManager = new UserManagerImpl();
employeeDTO = userManager.getEmployeeLeaveDetails(userIdArr.get(i));
employeeDTO.setDate(date_biometric_Data1.get(i));
employeeDTO.setEmployeeId(employeeIdArr.get(i));
employeeDTO.setFirstName(empFnameArr.get(i));
employeeDTO.setLastName(empLnameArr.get(i));
employeeDTO.setWorking_hours(working_hours_biometric_Data1.get(i));
int totalLeaves = employeeDTO.getTotalLeaves();
employeeDTO.setTotalLeaves(totalLeaves);
int plToCredit = employeeDTO.getPlToCredit();
employeeDTO.setPlToCredit(plToCredit);
int slclToCredit = employeeDTO.getSlclToCredit();
employeeDTO.setSlclToCredit(slclToCredit);
int slclTotalBal = totalLeaves - plToCredit;
employeeDTO.setSlclTotalBal(slclTotalBal);
connMgr = InitServlet.connMgr;
conn = connMgr.getConnection("access");
st = conn.createStatement();
String qry = "";
qry = "Select * from \"Est_Employee_Leave_Application\" Where '"
+ ConvertDate.stringtoSQLDate(date_biometric_Data
.get(i))
+ "' between leave_application_from_date and leave_application_to_date And emp_id ='"
+ empIdArr.get(i) + "'";
rs = st.executeQuery(qry);
if (!(rs.equals(null))) {
employeeDTO.setDay_status(day_status);
extra_empLeaveSummaryReport.add(employeeDTO);
request.setAttribute("leaveSummary",
extra_empLeaveSummaryReport);
}
} catch (Exception e) {
e.printStackTrace();
System.out
.println("Exception in leaveDetailsReport method");
} finally {
rs.close();
st.close();
connMgr.freeConnection("access", conn);
}
}
}
List<String> columnName = new ArrayList<String>();
columnName.add("Date");
columnName.add("Emp_Id");
columnName.add("Emp_First_Name");
columnName.add("Emp_Last_Name");
columnName.add("SL/CL_TotalBal");
columnName.add("PL_ToCredit");
columnName.add("Total_Leaves");
columnName.add("SL/CL_ToCredit");
columnName.add("Working_Hours");
columnName.add("Day_status");
request.setAttribute("columnNames", columnName);
return mapping.findForward("EXTRA_DETAILED_REPORT");
}
#SuppressWarnings("rawtypes")
public ArrayList<ArrayList> getBiometricData(List cellDataList)
{
EmployeeDTO employeeDTO = new EmployeeDTO();
ArrayList<String> date_Biometric = new ArrayList<String>();
ArrayList<String> emp_code_Biometric = new ArrayList<String>();
ArrayList<String> working_hours_Biometric = new ArrayList<String>();
ArrayList<ArrayList> biometric_All = new ArrayList<ArrayList>();
for (int i = 2; i < cellDataList.size(); i++)
{
List cellTempList = (List) cellDataList.get(i);
for (int j = 0; j < cellTempList.size(); j++)
{
if (j == 0)
{
HSSFCell hssfCell = (HSSFCell) cellTempList.get(0);
Date d1 = hssfCell.getDateCellValue();
SimpleDateFormat sdfAct = new SimpleDateFormat("dd-MMM-YYYY");
String d2 = new SimpleDateFormat("EEEE").format(d1);
String week_day1 = "Sunday";
String week_day2 = "Saturday";
if (week_day1.equals(d2) || week_day2.equals(d2)) {
j = 15;
}
else {
employeeDTO.setDate(sdfAct.format(d1).toString());
}
}
if (j == 1) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(1);
// blank = hssfCell.toString();
// if(blank == "")
// System.out.println("N/A");
// //else
// //System.out.println(blank);
}
if (j == 2) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(2);
String emp_code1 = hssfCell.toString();
String temp = emp_code1;
String non_emp1="10003";
String non_emp2="1001";
String non_emp3="1002";
String non_emp4="1111";
String non_emp5="237";
String non_emp6="002";
String non_emp7="023";
String non_emp8="511";
if(temp.length()>3){
temp = ""+ Integer.parseInt(temp);
}
if(temp.equals(non_emp1)||temp.equals(non_emp2)||temp.equals(non_emp3)||temp.equals(non_emp4)||temp.equals(non_emp5)||temp.equals(non_emp6)||temp.equals(non_emp7)||temp.equals(non_emp8))
{
j=15;
}
else{
String emp_code = "EST" +temp;
employeeDTO.setEmp_code(emp_code);
System.out.println(emp_code);
}
}
if (j == 3) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(3);
String emp_name = hssfCell.toString();
employeeDTO.setName(emp_name);
}
if (j == 4) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(4);
// System.out.println(card_num);
}
if (j == 5) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(5);
String shift_start = hssfCell.toString();
}
if (j == 6) {
String emp_in = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(6);
try {
emp_in = hssfCell.toString();
} catch (Exception e) {
emp_in = "";
}
if (emp_in == "" || emp_in.isEmpty() || emp_in == null) {
} else {
}
}
if (j == 7) {
String emp_out = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(7);
try {
emp_out = hssfCell.toString();
} catch (Exception e) {
}
if (emp_out == "" || emp_out.isEmpty() || emp_out == null) {
} else {
}
}
if (j == 8) {
String shift_end = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(8);
}
if (j == 9) {
String status = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(9);
status = hssfCell.toString();
String holiday_status="Hol";
if(status.equals(holiday_status))
{
j=15;
}
}
if (j == 10) {
String emp_late = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(10);
try {
emp_late = hssfCell.toString();
} catch (Exception e) {
emp_late = "";
}
if (emp_late == "" || emp_late.isEmpty()
|| emp_late == null) {
} else {
}
}
if (j == 11) {
String emp_early = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(11);
try {
emp_early = hssfCell.toString();
} catch (Exception e) {
emp_early = "";
}
if (emp_early == "" || emp_early.isEmpty()
|| emp_early == null) {
} else {
}
}
if (j == 12) {
String hours_worked = "";
HSSFCell hssfCell = (HSSFCell) cellTempList.get(12);
try {
hours_worked = hssfCell.toString();
employeeDTO.setHours_worked(hours_worked);
} catch (Exception e) {
hours_worked = "";
}
if (hours_worked == "" || hours_worked.isEmpty()|| hours_worked == null)
{
hours_worked = "0.00";
employeeDTO.setHours_worked(hours_worked);
}
date_Biometric.add(employeeDTO.getDate());
emp_code_Biometric.add(employeeDTO.getEmp_code());
working_hours_Biometric.add(employeeDTO.getHours_worked());
}
if (j == 13) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(13);
}
if (j == 14) {
HSSFCell hssfCell = (HSSFCell) cellTempList.get(14);
}
}
}
biometric_All.add(date_Biometric);
biometric_All.add(emp_code_Biometric);
biometric_All.add(working_hours_Biometric);
return biometric_All;
}
..................
In the above code I am geting the above mentioned exception in line
HSSFWorkbook workBook = new HSSFWorkbook(fsFileSystem);

Related

POI Excel cell highlighting "Repaired Records: Format From /xl/style.xml part(styles)

I have been working on a highlighting cells in excel sheet after end of execution when i opened the processed file(.xlsx file) using Ms-excel-2007 i am facing two pop up's .here the specified code and images :
HSSFWorkbook xlsWB = new HSSFWorkbook(file1InputStream);
XSSFWorkbook xlsxWB = new XSSFWorkbook(file2InputStream);
CellStyle xlsxStyle = getCellStyle(xlsxWB);
int numbeoOfSheetsFile1 = xlsWB.getNumberOfSheets();
int numbeoOfSheetsFile2 = xlsxWB.getNumberOfSheets();
for (int sheetIndex = 0; sheetIndex < numbeoOfSheetsFile1 && sheetIndex < numbeoOfSheetsFile2; sheetIndex++) {
HSSFSheet sheetFile1 = xlsWB.getSheetAt(sheetIndex);
XSSFSheet sheetFile2 = xlsxWB.getSheetAt(sheetIndex);
int noOfRowsSheetFile1 = sheetFile1.getLastRowNum();
int noOfRowsSheetFile2 = sheetFile2.getLastRowNum();
if (noOfRowsSheetFile1 < noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile1; vRow <= noOfRowsSheetFile2 - 1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
if (noOfRowsSheetFile1 > noOfRowsSheetFile2) {
for (int vRow = noOfRowsSheetFile2 + 1; vRow <= noOfRowsSheetFile1; vRow++) {
sheetFile2.createRow(vRow).setRowStyle(xlsxStyle);
//sheetFile2.getRow(vRow).setRowStyle(xlsxStyle);
}
}
for (int vRow = 0; vRow <= noOfRowsSheetFile1; vRow++) {
HSSFRow rwFile1 = sheetFile1.getRow(vRow);
XSSFRow rwFile2 = sheetFile2.getRow(vRow);
int noOfColSheetFile1 = sheetFile1.getRow(vRow).getLastCellNum();
int noOfColSheetFile2 = 0;
try {
noOfColSheetFile2 = sheetFile2.getRow(vRow).getLastCellNum();
} catch (NullPointerException e) {
rwFile2 = sheetFile2.createRow(vRow);
noOfColSheetFile2 = 0;
}
// Coloring of mismatch columns
if (noOfColSheetFile1 < noOfColSheetFile2) {
for (int vCol = noOfColSheetFile1 + 1; vCol <= noOfColSheetFile2; vCol++) {
rwFile2.createCell(vCol);
//rwFile2.getCell(vCol).setCellStyle(xlsxStyle);
}
}
if (noOfColSheetFile1 > noOfColSheetFile2) {
for (int vCo2 = noOfColSheetFile2 + 1; vCo2 <= noOfColSheetFile1; vCo2++) {
rwFile2.createCell(vCo2);
//rwFile2.getCell(vCo2).setCellStyle(xlsxStyle);
}
}
for (int vCol = 0; vCol < noOfColSheetFile1; vCol++) {
//System.out.println("vCol>>" + vCol + "--vRow>>" + vRow);
HSSFCell cellFile1 = rwFile1.getCell(vCol);
XSSFCell cellFile2 = rwFile2.getCell(vCol);
String cellFile1Value = null;
if (null != cellFile1) {
cellFile1Value = cellFile1.toString();
}
String cellFile2Value = null;
if (null != cellFile2) {
cellFile2Value = cellFile2.toString();
}
if ((null == cellFile1Value && null != cellFile2Value) || (null != cellFile1Value && null == cellFile2Value) || (null != cellFile1Value && cellFile1Value.compareTo(cellFile2Value) != 0)) {
if ((null != cellFile1Value && !cellFile1Value.isEmpty()) || (null != cellFile2Value && ! cellFile2Value.isEmpty())) {
CellValues cellValues = new CellValues();
cellValues.setValue1(cellFile1Value);
cellValues.setValue2(cellFile2Value);
cellValues.setCellRow(vRow);
cellValues.setCellColumn(vCol);
scenarioResultDetails.addDifference(cellValues);
XSSFCell cellDiff = rwFile2.getCell(vCol);
if (null == cellDiff) {
cellDiff = rwFile2.createCell(vCol);
}
cellDiff.setCellStyle(xlsxStyle);
}
}
}
}
}
String fileDiff = file2.replace(".xls", "_diff.xls");
FileOutputStream fileOut = new FileOutputStream(fileDiff);
xlsxWB.write(fileOut);
if (null != fileOut) {
try {
fileOut.close();
} catch (Exception e) {
}
}
if (scenarioResultDetails.getDifferencesList().size() > 0) {
scenarioResultDetails.setResult(false);
scenarioResultDetails.setResultText("Not Matched");
scenarioResultDetails.setDiffExcel(fileDiff);
} else {
scenarioResultDetails.setResult(true);
scenarioResultDetails.setResultText("Matched");
}
return scenarioResultDetails;
}
public static void openFile(String fileName){
ReportGenerator.getDriver().get("file://"+fileName);
}
private static CellStyle getCellStyle(XSSFWorkbook xssfWorkbook){
CellStyle style = xssfWorkbook.createCellStyle();
Font font = xssfWorkbook.createFont();
font.setColor(IndexedColors.BLACK.getIndex());
style.setFont(font);
style.setFillForegroundColor(HSSFColor.YELLOW.index);
style.setFillBackgroundColor(HSSFColor.YELLOW.index);
style.setFillPattern(CellStyle.ALIGN_RIGHT);
return style;
}
}
This behavior is still (or again) present. I'm using version 2.4.1 of the NuGet NPOI package which apparently has a FontHeight property bugfix, but it also introduced this.
The problem is that the font size the font returned by xssfWorkbook.createFont(); is way small. You have to set it explicitly like so:
IFont font = excel.CreateFont();
font.FontHeightInPoints = 11;
Also I got similar errors when overwriting a file that was previously repaired. Make sure you write to a clean/new file every time you change your code so no previous corruptions get in the way.
Full example:
/// <summary>
/// Return style for header cells.
/// </summary>
/// <returns></returns>
private static ICellStyle GetHeaderStyle(this XSSFWorkbook excel)
{
IFont font = excel.CreateFont();
font.IsBold = true;
//Added this explicitly, initial font size is tiny
font.FontHeightInPoints = 11;
ICellStyle style = excel.CreateCellStyle();
style.FillForegroundColor = IndexedColors.Grey25Percent.Index;
style.FillPattern = FillPattern.SolidForeground;
style.FillBackgroundColor = IndexedColors.Grey25Percent.Index;
style.BorderBottom = style.BorderLeft = style.BorderRight = style.BorderTop = BorderStyle.Thin;
style.BottomBorderColor = style.LeftBorderColor = style.RightBorderColor = style.TopBorderColor = IndexedColors.Black.Index;
style.SetFont(font);
return style;
}

Setting the color and formatting of cell when using Apache Poi does not work

I have been thinking of days for the solution. Anyway, I am doing a program where the apache will copy the whole sheet to another sheet in a workbook. Currently, my code can copy the contents but not the colour and format of the sheet. Please assist as I really unsure on how to proceed. Thanks.
int rowReadIndent = 0;
int columnReadIndent = 0;
int rowWriteIndent = 0;
int columnWriteIndent = 0;
ArrayList<ArrayList<ArrayList<Object>>> lists = new ArrayList<ArrayList<ArrayList<Object>>>();
ArrayList<ArrayList<ArrayList<Short>>> cellColorLists = new ArrayList<ArrayList<ArrayList<Short>>>();
//ArrayList<ArrayList<ArrayList<XSSFCellStyle>>> cellStyleLists = new ArrayList<ArrayList<ArrayList<XSSFCellStyle>>>();
ArrayList<String> sheetNameList = new ArrayList<String>();
for(int i = 0; i < fileArrayList.size(); i++) {
OPCPackage pkg = OPCPackage.open(new FileInputStream(desktop + "/test/" + fileArrayList.get(i)));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
Sheet sheet1 = wb.getSheetAt(0);
lists.add(new ArrayList<>());
//cellStyleLists.add(new ArrayList<ArrayList<XSSFCellStyle>>());
cellColorLists.add(new ArrayList<>());
sheetNameList.add(sheet1.getSheetName());
for(int j = 0; j < 50; j++) {
Row row1 = sheet1.getRow(j + rowReadIndent);
lists.get(i).add(new ArrayList<>());
//cellStyleLists.get(i).add(new ArrayList<XSSFCellStyle>());
cellColorLists.get(i).add(new ArrayList<>());
if(row1 != null) {
for(int k = 0; k < 50; k++) {
Cell cell1 = row1.getCell(k + columnReadIndent, Row.RETURN_BLANK_AS_NULL);
if(cell1 != null){
Object o = null;
int type = cell1.getCellType();
if(type == Cell.CELL_TYPE_FORMULA) {
type = cell1.getCachedFormulaResultType();
}
switch (type) {
case Cell.CELL_TYPE_STRING:
o = cell1.getRichStringCellValue().getString();
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell1)) {
o = cell1.getDateCellValue();
} else {
o = cell1.getNumericCellValue();
}
break;
case Cell.CELL_TYPE_BOOLEAN:
o = cell1.getBooleanCellValue();
break;
}
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle.cloneStyleFrom(cell1.getCellStyle());
//cellStyleLists.get(i).get(j).add(cellStyle);
XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
cellStyle = (XSSFCellStyle) cell1.getCellStyle();
cellColorLists.get(i).get(j).add(cellStyle.getFillBackgroundColor());
lists.get(i).get(j).add(o);
}
else {
lists.get(i).get(j).add(null);
}
}
}
}
pkg.close();
}
OPCPackage pkg1 = OPCPackage.open(new FileInputStream(desktop + "/test/Output Graph.xlsx"));
XSSFWorkbook wb1 = new XSSFWorkbook(pkg1);
FileOutputStream stream = new FileOutputStream(desktop + "/Output Graph4.xlsx" /*+ name + ".xlsx"*/);
for(int i = 0; i < lists.size(); i++) {
Sheet sheet1 = wb1.createSheet();
wb1.setSheetName(wb1.getSheetIndex(sheet1), sheetNameList.get(i));
for(int j = 0; j < lists.get(i).size(); j++) {
Row row1 = sheet1.createRow(j + rowWriteIndent);
for(int k = 0; k < lists.get(i).get(j).size(); k++) {
Cell cell1 = row1.createCell(k + columnWriteIndent);
//cell1.setCellStyle(cellStyleLists.get(i).get(j).get(k));
//XSSFCellStyle cellStyle = new XSSFCellStyle(new StylesTable());
//cellStyle = (XSSFCellStyle) cell1.getCellStyle();
//cellStyle.setFillBackgroundColor(cellColorLists.get(i).get(j).get(k));
if(lists.get(i).get(j).get(k) != null) {
switch (lists.get(i).get(j).get(k).getClass().getSimpleName()) {
case "String":
cell1.setCellValue((String)lists.get(i).get(j).get(k));
break;
case "Date":
cell1.setCellValue((Date)lists.get(i).get(j).get(k));
break;
case "Double":
cell1.setCellValue((Double)lists.get(i).get(j).get(k));
break;
case "Boolean":
cell1.setCellValue((Boolean)lists.get(i).get(j).get(k));
break;
}
}
}
}
}
/* Sheet sheet1;
Row row1;
Row row2;
Cell cell1;
for(int j = 0; j < lists.size(); j++) {
wb1.cloneSheet(0);
sheet1 = wb1.getSheetAt(j+1);
row1 = sheet1.createRow(1);
row2 = sheet1.createRow(0);
for(int i = 0; i < lists.get(j).size(); i++) {
cell1 = row1.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
//cell1.setCellValue(lists.get(j).get(i));
System.out.println("Stored: "+lists.get(j).get(i));
}
for(int i = 0; i < lists1.get(j).size(); i++) {
cell1 = row2.createCell(i);
cell1.setCellType(Cell.CELL_TYPE_NUMERIC);
cell1.setCellValue(lists1.get(j).get(i));
System.out.println("Stored: "+lists1.get(j).get(i));
}
}*/
wb1.write(stream);
stream.close();
pkg1.close();
Desktop.getDesktop().open(new File(desktop + "/Output Graph4.xlsx"));
} catch (FileNotFoundException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(status.class.getName()).log(Level.SEVERE, null, ex);
}
}

Cell and Column on XLSX Apache Java

I really have some problems with my code. Really appreciate it if any of you would help me. Below is my code and 2 screenshots of what it looks like and how it should looks like when the code is being executed.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
for (int c = 0; c < _col_cnt; c++) {
// Construct the header row
String _h = HeadersLabel[c];
System.out.println("_h: " + _h);
if (_h != null) {
XSSFCell hd = row.createCell(c);
hd.setCellValue(_h);
}
int r = 3;
for (Iterator iter = Cells.iterator();iter.hasNext();) {
Object[] _o = (Object[]) iter.next();
currentRow = s.createRow(r);
for(int colNum = 0; colNum < _col_cnt; colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING")
|| CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[colNum];
if (_l != null) {
currentCell.setCellValue(_l);
System.out.println("Data: " + _l);
}
}
else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
//XSSFCell cell = rowData.createCell(c);
cell.setCellValue(_aDate);
}
}
r++;
}
}
FileOutputStream fos = new FileOutputStream(excelFileName);
//w.write(response.getOutputStream());
w.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
context.responseComplete();
}
The XLSX excel did not manage to capture some data. The first two column is empty when there is suppose to be data appearing. Only the third column has the data.
What it looks like now: https://www.dropbox.com/s/2vfxsootyln6qq5/Capture3.JPG What it suppose to be like: https://www.dropbox.com/s/d0yctgk4pywh140/Capture2.JPG
I am not sure about the data source... However I have tried to solve your problem As far as possible. Please change it wherever you need.
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename="+ ReportID + ".xlsx");
String excelFileName = "C:\\Test.xlsx";
XSSFWorkbook w = new XSSFWorkbook();
System.out.println("w: " + w);
XSSFSheet s = w.createSheet(ReportID);
System.out.println("s: " + s);
// Report Title
s.createRow(0).createCell(0).setCellValue(Title);
System.out.println("Title: " + Title);
// Populate the worksheet
int _col_cnt = HeadersLabel.length;
XSSFRow row = s.createRow(_col_cnt);
System.out.println("HeadersLabel: " + _col_cnt);
//For Headers
int headerRowNum = 2; //for App, ShortName, LongName
XSSFRow currentRow = s.createRow(headerRowNum);
for(int headerCol =0; headerCol <_col_cnt; headerCol++){
currentRow.createCell(headerCol).setCellValue(HeadersLabel[headerCol]);
}
// for Date entry
for(int dataRow=3;dataRow < 20;dataRow++){
currentRow = s.createRow(dataRow);
for(int colNum=0;colNum<_col_cnt;colNum++){
XSSFCell currentCell =currentRow.createCell(colNum);
if (CellDataType[c].equals("STRING") || CellDataType[c].equals("VARCHAR")) {
String _l = (String) _o[c];
if (_l != null) {
currentCell.setCellValue(_l);
}
} else if (CellDataType[c].equals("DOUBLE")) {
Double _D = (Double) _o[c];
if (_D != null) {
currentCell.setCellValue(_D);
}
} else if (CellDataType[c].equals("INTEGER")) {
Integer _I = (Integer) _o[c];
if (_I != null) {
currentCell.setCellValue(_I);
}
} else if (CellDataType[c].equals("DATE")) {
Date _aDate = (Date) _o[c];
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
} else if (CellDataType[c].equals("TIMESTAMP")) {
Timestamp _aTimestamp = (Timestamp) _o[c];
Date _aDate = Timestamp2Date(_aTimestamp);
if (_aDate != null) {
currentCell.setCellValue(_aDate);
}
}
}
}
}
}

Fetch an entire row with jdbc as a List

I need to fetch data from multiple tables and export into excel sheet for each table. I don't want to use the getXXX() method as there are large number of columns and I don’t know the data type of each column. I need to fetch an entire row and store in the result in List.
I fetched each column using getObject() and also the class type using MetaData.getColumnClassName().
For example
Object val = resultSet.getObject(i);
I try to cast this val to its actual type using getColumnClassName() but it gives me an error while casting.
Can anyone please help me.
public class Row {
public Map<Object, Class> row;
public static Map<String, Class> TYPE;
static {
TYPE = new HashMap<String, Class>();
TYPE.put("INTEGER", Integer.class);
TYPE.put("NUMERIC", BigDecimal.class);
TYPE.put("DOUBLE", Double.class);
TYPE.put("VARCHAR2", String.class);
}
public Row() {
row = new HashMap<Object, Class>();
}
public <t> void add(t data) {
row.put(data, data.getClass());
}
public void add(Object data, String sqlType) {
add((Row.TYPE.get(sqlType)) data);
}
public static void formTable(ResultSet rs, List<Row> table) throws SQLException {
if(rs == null)
return;
ResultSetMetaData rsmd = rs.getMetaData();
int colCt = rsmd.getColumnCount();
while(rs.next()) {
Row row = new Row();
for(int i = 0; i < colCt; i++) {
row.add(rs.getObject(i), rsmd.getColumnTypeName(i));
}
table.add(row);
}
}
public static void main(String[] args) {
}
}
Try this code:
Connection connection = DriverManager.getConnection("URL", "USERNAME", "PASSWORD");
PreparedStatement statement = connection.prepareStatement("select * from table");
ResultSet resultSet = statement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
int type = resultSetMetaData.getColumnType(i);
if (type == Types.VARCHAR || type == Types.CHAR) {
System.out.println(resultSet.getString(i));
} else {
System.out.println(resultSet.getLong(i));
}
}
System.out.println("-----------");
}
}
You should extend it with other datatypes.
Step 1: get the metadata
ResultSetMetaData rsmd;
rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
int[] columnsType = new int[numColumns + 1];
columnsType[0] = 0;
for (int i = 1; i <= numColumns; i++)
columnsType[i] = rsmd.getColumnType(i);
Step 2: fetch a row at a time from the result set and check the data type
String s;
Object o;
while (rs.next()) {
for (int i = 1; i <= numColumns; i++) {
if (columnsType[i] == java.sql.Types.NUMERIC || columnsType[i] == java.sql.Types.CHAR || columnsType[i] == java.sql.Types.VARCHAR) {
s = rs.getString(i);
} else if (columnsType[i] == java.sql.Types.NVARCHAR) {
s = rs.getNString(i);
} else if (columnsType[i] == java.sql.Types.BOOLEAN) {
// TODO
} else if (columnsType[i] == java.sql.Types.FLOAT || columnsType[i] == java.sql.Types.DOUBLE) {
// TODO
} else if (columnsType[i] == java.sql.Types.TINYINT || columnsType[i] == java.sql.Types.SMALLINT || columnsType[i] == java.sql.Types.INTEGER || columnsType[i] == java.sql.Types.BIGINT) {
// TODO
} else if (columnsType[i] == java.sql.Types.DATE || columnsType[i] == java.sql.Types.TIMESTAMP) {
// TODO
} else {
o = rs.getObject(i);
}
}
}
Step 3: fill the blanks and add the exception handling
Step 4: write to Excel (inside the loop)
public class EXECUTEQUERY implements Module {
private static final DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private String userId;
String result = "";
String resp = "";
static int count = 1;
private final Logger log = Logger.getLogger("EXECUTEQUERY");
private void dbg(String msg) {
log.info(userId + ":" + msg);
}
private void dbg(Exception ex) {
log.info(ex.getMessage());
ex.printStackTrace();
}
private void uDbg(String msg) {
log.info(userId + " :" + msg);
}
private void uDbg(Exception ex) {
uDbg(ex.getMessage());
ex.printStackTrace();
}
public String main(UserContext userContext, String reqXml) {
dbg("Query recieved is " + reqXml);
String resp;
userId = userContext.getUserId();
if (userContext.getAction().equals("EXECUTEQUERY")) {
if (reqXml == null || reqXml.equals("")) {
result = "!Please Enter the query";
} else {
result = getQueryResult(userContext, reqXml);
}
}
return result;
}
/***
*
* for adding search record in backend created by #shyamlal yadav
* #param userContext
* #param reqXml
*/
public void addQueryLog(UserContext userContext, String reqXml) {
dbg("inside addQueryLog methos request is " + reqXml);
userId = userContext.getUserId();
dbg( userId +"this user is selecting value from screen");
System.out.println("recieve request is " + reqXml);
PreparedStatement pStmt = null;
Connection eodConn = null;
dbg("addQueryLog recieved for log " + reqXml);
Date date = new Date();
java.sql.Date sqlDate = new java.sql.Date( date.getTime());
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
pStmt = eodConn.prepareStatement("insert into EOD_QRY_EXEC_LOG (QRY_EXEC_TIMESTAMP, QRY_TEXT,OPERATOR_ID)\n"
+ " values (?,?,?)");
pStmt.setTimestamp(1, new java.sql.Timestamp(System.currentTimeMillis()));
pStmt.setString(2, reqXml);
pStmt.setString(3, userId);
pStmt.executeQuery();
} catch (SQLException ex) {
dbg("Exception is " + ex);
return;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
return;
}
/*
This method returns query excecuted table data with separators.
#Shaymlal,
*/
public String getQueryResult(UserContext userContext, String reqXml) {
String field_value = "";
String lsitofquery = "";
String resultlist = "";
dbg("Inside getQueryResult method");
Connection eodConn = null;
Statement stmt = null;
eodConn = EODConnectionFactory.getInstance().getFCConnectionFromPool();
try {
stmt = eodConn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(reqXml);
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
dbg("Total no of column is:" + columnCount);
int rsCount = 1;
while (rs.next()) {
if (rsCount == 1) {
for (int i = 1; i <= columnCount; i++) {
resultlist += "~" + rsmd.getColumnName(i);
}
}
for (int i = 1; i <= columnCount; i++) {
field_value += "~" + rs.getString(i);
}
field_value = field_value + "~<>";
lsitofquery = resultlist + "~>" + field_value;
rsCount = rsCount + 1;
}
} catch (Exception ex) {
dbg("Exception is " + ex);
return "!Exception invalid query: " + ex;
}
EODConnectionFactory.returnFCConnectionToPool(eodConn);
// return rowCount > 0 ? lsitofquery+">" : "!Table is Empty" ;
addQueryLog(userContext,reqXml);
return lsitofquery + ">";
}
}

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