how to generate the excel file in java using seam - java

I am using seam 2.2.0 i want to generate the excel dynamically and download that excel file
can anybody have the code please
This is my code
public void getWriteExcelFile() {
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFCellStyle cellStyle = setHeaderStyle(hwb);
HSSFRow rowhead1 = sheet.createRow((short) 0);
HSSFCell cell = rowhead1.createCell((short) 4);
cell.setCellStyle(cellStyle);
cell.setCellValue(new HSSFRichTextString(
"Vizag Seaport Private Limited"));
HSSFRow rowdata1 = sheet.createRow(3);
rowdata1.createCell(2).setCellValue(
"Computation Of Storage Charges");
HSSFRow rowhead = sheet.createRow((short) 5);
HSSFRow row = sheet.createRow((short) 5);
HSSFRow rowhead2 = sheet.createRow((short) 6);
HSSFRow row2 = sheet.createRow(6);
HSSFRow rowhead3 = sheet.createRow((short) 7);
HSSFRow row3 = sheet.createRow((short) 7);
HSSFRow rowhead4 = sheet.createRow((short) 8);
HSSFRow row4 = sheet.createRow((short) 8);
HSSFCell cell1 = rowhead.createCell((short) 2);
cell1.setCellStyle(cellStyle);
cell1.setCellValue(new HSSFRichTextString("Party Name:"));
row.createCell((short) 3).setCellValue(
itStorageInvoice.getItImportCustomDetail()
.getIcPartyByBLParty().getPartyName());
HSSFCell cell2 = rowhead.createCell((short) 7);
cell2.setCellStyle(cellStyle);
cell2.setCellValue(new HSSFRichTextString("Free Period:"));
row.createCell((short) 8).setCellValue(
itStorageInvoice.getFreeDays());
System.out.println("-------------------------freedays-"
+ itStorageInvoice.getFreeDays());
HSSFCell cell3 = rowhead2.createCell((short) 2);
cell3.setCellStyle(cellStyle);
cell3.setCellValue(new HSSFRichTextString("Cargo Stacker:"));
row2.createCell((short) 3).setCellValue(
itStorageInvoice.getItBlLdg().getItBlLdgDetails().get(0)
.getIcCommodity().getCommodityCode());
System.out.println("--------------cargostacker---------"
+ itStorageInvoice.getItBlLdg().getItBlLdgDetails().get(0)
.getIcCommodity().getCommodityCode());
HSSFCell cell4 = rowhead2.createCell((short) 7);
cell4.setCellStyle(cellStyle);
cell4.setCellValue(new HSSFRichTextString("Date Of Sailing:"));
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
row2.createCell(8).setCellValue(
sdf.format(itStorageInvoice.getItVoyage().getLastRope()));
System.out.println("--------date--------"
+ itStorageInvoice.getItVoyage().getLastRope());
HSSFCell cell5 = rowhead3.createCell((short) 2);
cell5.setCellStyle(cellStyle);
cell5.setCellValue(new HSSFRichTextString("Vessel:"));
row3.createCell((short) 3).setCellValue(
itStorageInvoice.getItVoyage().getImVessel()
.getVesselName());
HSSFCell cell6 = rowhead3.createCell((short) 7);
cell6.setCellStyle(cellStyle);
cell6.setCellValue(new HSSFRichTextString("BL # :"));
row3.createCell((short) 8).setCellValue(
itStorageInvoice.getItImportCustomDetail().getBlNumber());
HSSFCell cell7 = rowhead4.createCell((short) 2);
cell7.setCellStyle(cellStyle);
cell7.setCellValue(new HSSFRichTextString("Tonnage"));
row4.createCell((short) 3).setCellValue(
itStorageInvoice.getItBlLdg().getItBlLdgDetails().get(0)
.getWeight().doubleValue()
+ " " + "TONNE");
/*
* HSSFCell cell8= rowhead4.createCell((short) 7);
* cell8.setCellStyle(cellStyle); cell8.setCellValue(new
* HSSFRichTextString("Free Time Upto")); row4.createCell((short)
* 8).setCellValue(itStorageInvoice.getItBlLdg().getFreePeriod());
*/
HSSFRow rowhead5 = sheet.createRow((short) 10);
CellStyle style = hwb.createCellStyle();
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT
.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
HSSFCell cell8 = rowhead5.createCell(2);
cell8.setCellStyle(style);
cell8.setCellValue("DATE");
HSSFCell cell9 = rowhead5.createCell(3);
cell9.setCellStyle(style);
cell9.setCellValue("Bal.Appx.Qty");
HSSFCell cell10 = rowhead5.createCell(4);
cell10.setCellStyle(style);
cell10.setCellValue("RATE");
HSSFCell cell11 = rowhead5.createCell(5);
cell11.setCellStyle(style);
cell11.setCellValue("AMOUNT");
FileOutputStream fileOut = new FileOutputStream(new File(this
.getExcelFileName()));
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
ex.printStackTrace();
}
}
i am calling from front end like this
but it is not downloaded if it download it shows the size as 0bytes
please provide any help

When you write it to the FileOutputStream, you are just writing it to a file; nothing is sent to the user. You need to write out the contents of the file to the HttpResponse. Check this out: http://www.coolinterview.com/interview/26167/

Seam has built in excel support, have you looked at that? The excel generation is done from your xhtml and is laid out almost exactly like a datatable.
http://docs.jboss.org/seam/2.2.0.CR1/reference/en-US/html/excel.html

Related

How to reduce code when create an cell in apache poi?

I am creating a sheet with apache poi, it have a lot of column and row name so I create a lot of code, I have a lot of code duplicate, How can I can create a function and reuse it for another?
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
try (OutputStream os = new FileOutputStream("report.xls")) {
Row row;
Cell cell;
row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("Shop:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Export Date:");
cell = row.createCell(7);
cell.setCellValue("14.06.2019");
// -----
row = sheet.createRow(2);
cell = row.createCell(0);
cell.setCellValue("Code Supervisor:");
cell = row.createCell(1);
cell.setCellValue(4);
cell = row.createCell(6);
cell.setCellValue("Audit Date:");
cell = row.createCell(7);
cell.setCellValue("dd.MM.yyyy");
//----
row = sheet.createRow(4);
cell = row.createCell(6);
cell.setCellValue("Shop Note:");
cell = row.createCell(7);
cell.setCellValue("Note something");
wb.write(os);
}catch(Exception e) {
System.out.println(e.getMessage());
}

Writing to excel using Apache poi(Error)

I'm writing data into excel file using Apache Poi In Java Eclipse,Problem is when i add column aligned with each row,it override the previous column...here is the code before i add anything.
public static void main(String[] args) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("cellstyle");
XSSFRow row=spreadsheet.createRow(1);
XSSFCell cell;
row = spreadsheet.createRow((short) 4);
row.setHeight((short) 800);
cell = (XSSFCell) row.createCell((short) 5);
cell.setCellValue("Total Alerts raised");
spreadsheet.addMergedRegion(new CellRangeAddress(4,4,5,6));
row = spreadsheet.createRow(5);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Critical");
row = spreadsheet.createRow(6);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Warning");
row = spreadsheet.createRow(7);
cell = (XSSFCell) row.createCell(5);
cell.setCellValue("Total");
FileOutputStream out = new FileOutputStream(
new File("C:\\Users\\tshivhaser\\Desktop\\cellstyle.xlsx"));
workbook.write(out);
out.close();
System.out.println("cellstyle.xlsx written successfully");
}
I then add this piece of code...Critical,Warning and Total column becomes empty
row = spreadsheet.createRow(5);
cell = row.createCell(6);
cell.setCellValue(0);
row = spreadsheet.createRow(6);
cell = row.createCell(6);
cell.setCellValue(0);
row = spreadsheet.createRow(7);
cell = row.createCell(6);
cell.setCellValue(10);
Please help on how i can have all cells filled...

How to auto adjust the column in excel in apache POI

I am creating an excel file with apache poi the excel is generated but i can not adjust the column with according to the cell values i am posting the code what i have done so far
This is how i have created the headers in excel
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
sheet.protectSheet("password");
sheet.autoSizeColumn(15);
HSSFFont hSSFFont = wb.createFont();
hSSFFont.setFontName(HSSFFont.FONT_ARIAL);
hSSFFont.setFontHeightInPoints((short) 8);
CellStyle style = wb.createCellStyle();
/* cell style for locking */
CellStyle lockedCellStyle = wb.createCellStyle();
lockedCellStyle.setLocked(true);
HSSFRow row = null;
HSSFCell cell = null;
row = sheet.createRow(0);
int headercolumnNo = 0;
//1st Column Header for Indicator
cell = row.createCell(headercolumnNo);
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(0)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
cell.setCellStyle(style);
headercolumnNo = 1;
cell = row.createCell(headercolumnNo); //2nd Column Header for Firstname
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(1)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
cell.setCellStyle(style);
headercolumnNo = headercolumnNo + 1;
cell = row.createCell(headercolumnNo); //2nd Column Header for Firstname
cell.setCellValue(new HSSFRichTextString(listOfActiveCarrierUserHeader.get(2)));
style.setWrapText(true);
style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
style.setFont(hSSFFont);
cell.setCellStyle(style);
headercolumnNo = headercolumnNo + 1;
and this is how i have populated the values in that excel file
for(CarrierActiveUser carrierActiveUser : listOfCarrierUser){
int columnNo = 0;
row = sheet.createRow(j + 1);
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getFistName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getFistName()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
columnNo = columnNo + 1;
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getLastName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getLastName()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
columnNo = columnNo + 1;
cell = row.createCell(columnNo);
if(null != carrierActiveUser.getLastName()){
cell.setCellValue(new HSSFRichTextString(carrierActiveUser.getEmailId()));
lockedCellStyle.setFont(hSSFFont);
cell.setCellStyle(lockedCellStyle);
}else{
cell.setCellValue(new HSSFRichTextString(" "));
cell.setCellStyle(lockedCellStyle);
}
Please someone help me to adjust the columns , i am new to apache poi
You can use HSSFSheet.autoSizeColumn(columnNumber) method to align the columns perfectly.
This method adjusts the column width to fit the contents, read the doc.
After setting all cell values for all columns you can use this method, in your current code call this method after for loop.
Sample code
sheet.autoSizeColumn(1);
sheet.autoSizeColumn(2);
Note - You have to do this separately for all columns which you want to be aligned and the call to sheet.autoSizeColumn(columnNumber) should be made after populating the data into the excel. Calling before populating data will not have any effect.

Merge Consecutive cells in a Column having same values in excel

I have some data to be written into an excel Sheet.
i have done that part.
Now i want the consecutive cells of first column having same values to get merged.
I dont have any idea about how to merge cells by coding.
i use apache-poi
Below is my code.
HSSFWorkbook wb = new HSSFWorkbook();
String fromAddress,toAddress;
HSSFSheet sheet = wb.createSheet("Report 1");
SimpleDateFormat dateFormatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
short dateFormat = wb.createDataFormat().getFormat("dd-MM-yyyy HH:mm:ss");
SimpleDateFormat dateFormatter1 = new SimpleDateFormat("dd/MM/yyyy-HH:mm:ss");
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Proposal No."));
cell = row.createCell(1);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Equipment Name"));
cell = row.createCell(2);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Quantity Ordered"));
cell = row.createCell(3);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Invoice"));
cell = row.createCell(4);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Total Invoice Value"));
cell = row.createCell(5);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Quantity Dispatched"));
cell = row.createCell(6);
cell.setCellStyle(headerCellStyle);
cell.setCellValue(new HSSFRichTextString("Balance Quantity"));
DispatchReports dispatchSummery=new DispatchReports();
if (dispatchSummery != null) {
dispatchList = dispatchSummery.dispatchSummery();
}
DispatchReports dispatchSummeryExtend=new DispatchReports();
if (dispatchSummeryExtend != null) {
dispatchListExtended = dispatchSummeryExtend.dispatchSummeryExtended();
}
int tempCount = 1;
//Data filling starts here
for (int key = 0; key < dispatchList.size(); key++) {
try {
CmaDispatchEquipmentDetails ws = new CmaDispatchEquipmentDetails();
int cellnum = 0;
HSSFRow row1 = sheet.createRow(tempCount++);
ws = (CmaDispatchEquipmentDetails) dispatchList.get(key);
HSSFCell cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getCmaId().getCmaNo()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getEquipmentname()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getQtyordered()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getInvoice()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getTotalinvoicevalue()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getQtydispatched()));
cell1 = row1.createCell(cellnum++);
cell1.setCellValue(new HSSFRichTextString("" + ws.getBalancedispatched()));
} catch (Exception e) {
e.printStackTrace();
tempCount--;
continue;
}
}
Please help me merge the consecutive cells of 'proposal No.' column that have same values.

Spring Security and Apache POI Issues

I have a Java Spring web application with Spring Security where the user enters a date, the
database is queried based on that date and the result is sent back to the user's browser as an excel file via HSSFWorkbook writing to ServletOutputStream.
If the date selected is in the weeks of 12/28/2013-1/4/2014, 1/12/2014-1/18-2014, 1/19/2014-1/25/2014, or 1/26/2014-2/1/2014 the file that is sent to the user for download is converted to the contentType "text/html" even though it is explicitly set to "application/x-ms-excel".
The resulting Excel file is corrupted and contains only strange symbols. This only happens when Spring-Security is included and so far, only for the dates listed.
If anyone has had this problem could you please let me know how you fixed it?
This generates the workbook:
public static HSSFWorkbook getExcelRemittance(HashMap<String,List> items)
{
List<ItemView> remit = items.get("remit");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet;
sheet = workbook.createSheet("Final Remittance");
Row header = sheet.createRow(0);
Cell cell1 = header.createCell(0);
cell1.setCellValue("DISNEY INVOICE NUM");
Cell cell2 = header.createCell(1);
cell2.setCellValue("EBI AMOUNT");
Cell cell3 = header.createCell(2);
cell3.setCellValue("PAYING AMOUNT");
Cell cell4 = header.createCell(3);
cell4.setCellValue("RESIDUAL AMOUNT");
Cell cell5 = header.createCell(4);
cell5.setCellValue("BOOKING #");
Cell cell6 = header.createCell(5);
cell6.setCellValue("GUEST NAME");
Cell cell7 = header.createCell(6);
cell7.setCellValue("NOTES/Dispute Reason");
int count = 1;
double total = 0.0;
for(ItemView v : remit)
{
Row row = sheet.createRow(count++);
Cell c1 = row.createCell(0);
c1.setCellValue(v.getDisneyInvoiceNum());
Cell c2 = row.createCell(1);
c2.setCellValue(v.getEbiAmount());
Cell c3 = row.createCell(2);
c3.setCellValue(v.getEbiAmount());
Cell c4 = row.createCell(3);
c4.setCellValue("-");
Cell c5 = row.createCell(4);
c5.setCellValue("");
Cell c6 = row.createCell(5);
c6.setCellValue("");
Cell c7 = row.createCell(6);
c7.setCellValue("");
total+=v.getEbiAmount();
}
Row subTotalRemit = sheet.createRow(sheet.getLastRowNum()+1);
int subTotalRow1 = sheet.getLastRowNum()+1;
Cell t = subTotalRemit.createCell(0);
t.setCellValue("subtotal");
Cell tAmt = subTotalRemit.createCell(1);
tAmt.setCellFormula("SUM(B2:B"+sheet.getLastRowNum()+")");
List<ItemView> past = items.get("prev");
Row prevHead = sheet.createRow(count+6);
Cell remitTitle = prevHead.createCell(0);
remitTitle.setCellValue("Invoices from previous batches");
CellStyle cs = workbook.createCellStyle();
Font f = workbook.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
cs.setFont(f);
remitTitle.setCellStyle(cs);
Row prevCols = sheet.createRow(sheet.getLastRowNum()+1);
Cell ph1= prevCols.createCell(0);
ph1.setCellValue("Invoice Number");
Cell ph2= prevCols.createCell(1);
ph2.setCellValue("Invoice Amount");
Cell ph3= prevCols.createCell(2);
ph3.setCellValue("Paying Amount");
Cell ph4= prevCols.createCell(3);
ph4.setCellValue("Residual Amount");
Cell ph5= prevCols.createCell(4);
ph5.setCellValue("Booking #");
Cell ph6= prevCols.createCell(5);
ph6.setCellValue("Guest Name");
Cell ph7= prevCols.createCell(6);
ph7.setCellValue("Notes/Dispute Reason");
int sum1 = sheet.getLastRowNum()+1;
for(ItemView v : past)
{
Row row = sheet.createRow(sheet.getLastRowNum()+1);
Cell c1 = row.createCell(0);
c1.setCellValue(v.getDisneyInvoiceNum());
Cell c2 = row.createCell(1);
c2.setCellValue(v.getEbiAmount());
Cell c3 = row.createCell(2);
c3.setCellValue(v.getAmountPaid());
Cell c4 = row.createCell(3);
c4.setCellValue(v.getDiffEbiApAmt());
Cell c5 = row.createCell(4);
c5.setCellValue("");
Cell c6 = row.createCell(5);
c6.setCellValue("");
Cell c7 = row.createCell(6);
c7.setCellValue(v.getNotes());
}
Row subTotalPrev = sheet.createRow(sheet.getLastRowNum()+1);
Cell tP = subTotalPrev.createCell(1);
tP.setCellValue("subtotal");
Cell tAmtP = subTotalPrev.createCell(2);
tAmtP.setCellFormula("SUM(C"+sum1+":C"+sheet.getLastRowNum()+")");
Row gTotal = sheet.createRow(sheet.getLastRowNum()+1);
Cell gtP = gTotal.createCell(1);
gtP.setCellValue("Total");
Cell gtAmtP = gTotal.createCell(2);
gtAmtP.setCellFormula("B"+subTotalRow1+"+C"+(sheet.getLastRowNum()));
return workbook;
}
This is the code that sends the file to the user:
#RequestMapping(value="generateRemit")
public #ResponseBody String getRemitExcel(
#RequestParam("date") String date,
HttpServletResponse response)
{
ServletOutputStream out;
HSSFWorkbook book = Utils.getExcelRemittance(jdbcBillingDao.getWeeklyRemit(date));
try {
response.setContentType("application/x-ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+date+"Remittance Final.xls");
out = response.getOutputStream();
log.info("writing to output stream");
book.write(out);
out.flush();
log.info("finished writing to output stream");
// return book.toString();
} catch (IOException e) {
e.printStackTrace();
log.info("Error writing to file output stream");
return e.toString();
}
return "success";
}
Fixed it by returning an AbstractExcelView instead of a redirect:
#RequestMapping(value="generateRemit")
protected View remitExcel( #RequestParam("date") String date)
{
final String finalDate = date;
return new AbstractExcelView() {
#Override
protected void buildExcelDocument(Map<String, Object> model, HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception {
response.addHeader("Content-Disposition", "attachment; filename=\""+finalDate+"Disney Remittance Final\"");
HashMap<String,List> items = jdbcBillingDao.getWeeklyRemit(finalDate);
HSSFSheet sheet = workbook.createSheet("Final Remittance");
#SuppressWarnings("unchecked")
List<ItemView> remit = items.get("remit");
Row header = sheet.createRow(0);
Cell cell1 = header.createCell(0);
cell1.setCellValue("DISNEY INVOICE NUM");
Cell cell2 = header.createCell(1);
cell2.setCellValue("EBI AMOUNT");
Cell cell3 = header.createCell(2);
cell3.setCellValue("PAYING AMOUNT");
Cell cell4 = header.createCell(3);
cell4.setCellValue("RESIDUAL AMOUNT");
Cell cell5 = header.createCell(4);
cell5.setCellValue("BOOKING #");
Cell cell6 = header.createCell(5);
cell6.setCellValue("GUEST NAME");
Cell cell7 = header.createCell(6);
cell7.setCellValue("NOTES/Dispute Reason");
//more spreadsheet generation
}
};
}

Categories

Resources