ArrayList and itextpdf , table - java

I have table with 30 rows and array list full of strings.Table has 2 columns, in first is like company name , in second i need to write Strings from list, each row of that second column should have 10 elements, How do I do that ?
PDF Output should be something like this :
Company name |||| DESTINATION
AirFrance |||| Tokio,London,Istanbul,New Nork,Paris,Vienna,OSLO,Belgrade,Budapest,Amsterdam.
Each company should read 10 destination from list.
It's probably something easy that I just can't see I tried to count list elements and somehow partition it but it didn't work.
By the way i use itextpdf library and i read those data from excel.
Here is code :
public class ReadExcel {
private String inputfile;
private List<Avio> avioni;
public ReadExcel() {
this.avioni = new ArrayList<Avio>();
}
public List<Avio> getAvioni() {
return avioni;
}
public void setAvioni(List<Avio> avioni) {
this.avioni = avioni;
}
public String getInputfile() {
return inputfile;
}
public void setInputfile(String inputfile) {
this.inputfile = inputfile;
}
public void citaj(String naziv) {
Avio a = new Avio();
try {
Workbook w = Workbook.getWorkbook(new File(naziv));
Sheet sheet = w.getSheet(0);
// System.out.println(sheet.getRows());
for (int i = 1; i < sheet.getRows(); i++) {
Avio tmpAvio = new Avio();
tmpAvio.setDrzava(sheet.getCell(0, i).getContents());
System.out.println();
tmpAvio.setNazivKomp(sheet.getCell(1, i).getContents());
tmpAvio.setVlasnik(sheet.getCell(2, i).getContents());
tmpAvio.setBrAviona(Integer.parseInt(sheet.getCell(3, i)
.getContents()));
tmpAvio.setGod(Integer.parseInt(sheet.getCell(4, i)
.getContents()));
tmpAvio.setDatum(sheet.getCell(6,i).getContents());
tmpAvio.setModelAviona(sheet.getCell(7,i).getContents());
tmpAvio.setKapetan(sheet.getCell(8,i).getContents());
tmpAvio.setJMBG(sheet.getCell(9,i).getContents());
tmpAvio.setIskustvo(sheet.getCell(10,i).getContents());
tmpAvio.setBrPutnika(sheet.getCell(11,i).getContents());
tmpAvio.setLet(sheet.getCell(12,i).getContents());
avioni.add(tmpAvio);
}
Sheet sheet1 = w.getSheet(1);
List<String> destinacije = new ArrayList<String>();
for (int i = 0; i < sheet1.getRows(); i++) {
for (int j = 0; j < sheet1.getColumns(); j++) {
destinacije.add(sheet1.getCell(j, i).getContents());
System.out.println(sheet1.getCell(j,i).getContents()+i+","+j);
}
avioni.get(i).setDestinacije(destinacije);
System.out.println(avioni.get(i));
}
}
catch (BiffException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void kreirajPDF(String naziv) {
Document d = new Document();
try {
PdfWriter.getInstance(d, new FileOutputStream(new File(naziv)));
d.open();
File fontFile = new File("swansea.ttf");
BaseFont unicode = BaseFont.createFont(fontFile.getAbsolutePath(),
BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font titleFont = new Font(unicode, 16, Font.BOLD);
titleFont.setColor(BaseColor.WHITE);
Font textFont = new Font(unicode, 11, Font.NORMAL);
Font headerFont = new Font(unicode, 14, Font.BOLD);
Paragraph p1 = new Paragraph("Evropske Avio Kompanije", titleFont);
p1.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
Image img = Image.getInstance("lufthansa2.jpg");
img.setAlignment(Image.MIDDLE |Image.TEXTWRAP);
p1.add(img);
d.add(p1);
//d.add(new Paragraph("DESTINACIJE"));
Paragraph p2 = new Paragraph("Destinacije", titleFont);
p2.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
d.add(p2);
d.add(new Paragraph(" "));
Paragraph p3 = new Paragraph("Piloti", titleFont);
p3.setAlignment(com.itextpdf.text.Element.ALIGN_CENTER);
d.add(p3);
kreiranjeTabele(d, textFont, headerFont, "Pilot");
d.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void kreiranjeTabele(Document d, Font textFont, Font headerFont,
String smjer) throws DocumentException {
PdfPTable table = new PdfPTable(5);
PdfPCell c1 = new PdfPCell(new Phrase("Drzava", headerFont));
table.addCell(c1);
PdfPCell c2 = new PdfPCell(new Phrase("Kompanija", headerFont));
table.addCell(c2);
PdfPCell c3 = new PdfPCell(new Phrase("Vlasnik", headerFont));
table.addCell(c3);
PdfPCell c4 = new PdfPCell(new Phrase("Broj Aviona", headerFont));
table.addCell(c4);
PdfPCell c5 = new PdfPCell(new Phrase("Godina", headerFont));
table.addCell(c5);
for (Avio s : avioni) {
table.setWidthPercentage(110);
// Paragraph p1 = new Paragraph(s.toString(),
// textFont);Integer.toString(i)
table.addCell(new Phrase(s.getDrzava(), textFont));
table.addCell(new Phrase(s.getNazivKomp(), textFont));
table.addCell(new Phrase(s.getVlasnik(), textFont));
table.addCell(new Phrase(Integer.toString(s.getBrAviona()),
textFont));
table.addCell(new Phrase(Integer.toString(s.getGod()), textFont));
}
PdfPTable table1 = new PdfPTable(5);
PdfPCell c11 = new PdfPCell(new Phrase("Kompanija", headerFont));
table1.addCell(c11);
PdfPCell c22 = new PdfPCell(new Phrase("Avion", headerFont));
table1.addCell(c22);
PdfPCell c33 = new PdfPCell(new Phrase("Datum", headerFont));
table1.addCell(c33);
PdfPCell c44 = new PdfPCell(new Phrase("Destinacija", headerFont));
table1.addCell(c44);
PdfPCell c55 = new PdfPCell(new Phrase("Trajanje leta", headerFont));
table1.addCell(c55);
for (Avio s1 : avioni) {
table1.setWidthPercentage(110);
table1.addCell(new Phrase(s1.getNazivKomp(), textFont));
table1.addCell(new Phrase(s1.getModelAviona(), textFont));
table1.addCell(new Phrase(s1.getDatum(), textFont));
// table1.addCell(new Phrase(s1.getDestinacije(), textFont));
table1.addCell(new Phrase(s1.getLet(), textFont));
}
PdfPTable table2 = new PdfPTable(5);
PdfPCell c111 = new PdfPCell(new Phrase("Pilot", headerFont));
table2.addCell(c111);
PdfPCell c222 = new PdfPCell(new Phrase("Drzava", headerFont));
table2.addCell(c222);
PdfPCell c333 = new PdfPCell(new Phrase("JMBG", headerFont));
table2.addCell(c333);
PdfPCell c444 = new PdfPCell(new Phrase("Iskustvo", headerFont));
table2.addCell(c444);
PdfPCell c555 = new PdfPCell(new Phrase("Avion", headerFont));
table2.addCell(c555);
for (Avio s2 : avioni) {
table2.setWidthPercentage(110);
table2.addCell(new Phrase(s2.getKapetan(), textFont));
table2.addCell(new Phrase(s2.getDrzava(), textFont));
table2.addCell(new Phrase(s2.getJMBG(), textFont));
table2.addCell(new Phrase(s2.getIskustvo(), textFont));
table2.addCell(new Phrase(s2.getModelAviona(), textFont));
}
d.add(table);
d.newPage();
d.add(table1);
d.newPage();
d.add(table2);
}
Hope someone can help. Thanks in advance.

Related

how to insert paragraphs with different positions - itext

The drawing of the table is done correctly but it gets wrong as the data is repeated.
the barcode has to be like this to avoid errors from employees checking wrong codes.
The ideal would be A picture speaks a thousand words.
My function:
Document documentoPDF = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(documentoPDF, new FileOutputStream("c:\\exporta_Celso\\contagem_" + jComboBox1.getSelectedItem().toString() + ".pdf"));
documentoPDF.open();
documentoPDF.setPageSize(PageSize.A4);
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100);
table.setTotalWidth(documentoPDF.getPageSize().getWidth());
for (int i = 0; i < itens.size(); i++) {
System.out.println(((List) itens.get(i)).get(0).toString());
System.out.println(((List) itens.get(i)).get(1).toString());
String item = ((List) itens.get(i)).get(1).toString();
BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
String barCodeBruto = ((List) itens.get(i)).get(0).toString();
String barCode = null;
if (barCodeBruto.length() != 13) {
barCode = ("0000000000000" + barCodeBruto).substring(barCodeBruto.length());
} else {
barCode = barCodeBruto;
}
codeEAN.setCode(barCode);
PdfContentByte cb = writer.getDirectContent();
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);
PdfPCell cellBar = new PdfPCell(imageEAN);
PdfPCell cellDesc = new PdfPCell(new Paragraph(item));
PdfPCell cellQtd = new PdfPCell(new Paragraph("QTD."));
cellBar.setPadding(3);
cellBar.setUseDescender(true);
cellBar.setUseAscender(true);
cellDesc.setPadding(3);
cellDesc.setUseDescender(true);
cellDesc.setUseAscender(true);
cellQtd.setPadding(3);
cellQtd.setUseDescender(true);
cellQtd.setUseAscender(true);
float height = table.calculateHeights();
float width = documentoPDF.getPageSize().getWidth();
if (i % 2 == 0) {
float[] widths = new float[]{145f, width - 36 - 10f, 80f};
table.setWidths(widths);
table.addCell(cellBar);
table.addCell(cellDesc);
table.addCell(cellQtd);
}else{
float[] widths = new float[]{80f, width - 36 - 10f, 145f};
table.setWidths(widths);
table.addCell(cellQtd);
table.addCell(cellDesc);
table.addCell(cellBar);
}
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(table);
columnText.go();
}
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
documentoPDF.close();
}
I solved it by creating a parent table outside the looping.
PdfPTable tableFinal = new PdfPTable(1);
tableFinal.setWidthPercentage(100);
tableFinal.setTotalWidth(documentoPDF.getPageSize().getWidth());
tableFinal.addCell(table);
PdfContentByte canvas = writer.getDirectContent();
ColumnText columnText = new ColumnText(canvas);
columnText.setSimpleColumn(36, 756 - height, width - 36, 36);
columnText.addElement(tableFinal);
columnText.go();

Cell data getting cropped for particular table layout. iText 2.1.7

For particular table layout with particular cell having larger data then it is not getting properly exported to PDF, the data in that particular cell getting cropped.
private static void tableLayout1() {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream(
".\\TableLayout_1.pdf"));
doc.open();
// Table
PdfPTable table = new PdfPTable(3);
table.setWidthPercentage(100f);
table.setSplitLate(false);
//row 1
PdfPCell cell00 = new PdfPCell(new Paragraph("Cell00"));
cell00.setBackgroundColor(new Color(200, 0, 0));
cell00.setRowspan(3);
PdfPCell cell01 = new PdfPCell(new Paragraph("Cell01"));
cell01.setBackgroundColor(new Color(0, 200, 0));
cell01.setColspan(2);
//row 2
PdfPCell cell11 = new PdfPCell(new Paragraph("Cell11"));
cell11.setBackgroundColor(new Color(100, 100, 0));
PdfPCell cell12 = new PdfPCell( getLongCellData() );
cell12.setBackgroundColor(new Color(0, 200, 200));
cell12.setRowspan(2);
//row 3
PdfPCell cell21 = new PdfPCell(new Paragraph("Cell21"));
cell21.setBackgroundColor(new Color(200, 0, 200));
table.addCell(cell00);
table.addCell(cell01);
table.addCell(cell11);
table.addCell(cell12);
table.addCell(cell21);
doc.add(table);
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
doc.close();
}
private static Paragraph getLongCellData() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100; i++) {
sb.append("Cell12_" + i);
sb.append("\n");
}
return new Paragraph(sb.toString());
}
Here the data from cell12 (which has row span of 2 and has larger data) is getting cropped at the page end and it is not being continued on next page.
Tried dividing this table into two different tables as below, but still the issue is there.
private static void tableLayout2() {
Document doc = new Document();
try {
PdfWriter.getInstance(doc, new FileOutputStream(
".\\TableLayout_2.pdf"));
doc.open();
// Table
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100f);
table.setSplitLate(false);
table.setWidths(new int[]{1, 2});
//Inner table for column 1
PdfPTable column1Table = new PdfPTable(1);
PdfPCell cell00 = new PdfPCell(new Paragraph("Cell00"));
cell00.setBackgroundColor(new Color(200, 0, 0));
//cell00.setRowspan(3);
column1Table.addCell(cell00);
//Inner table for column 2
PdfPTable column2Table = new PdfPTable(2);
PdfPCell cell01 = new PdfPCell(new Paragraph("Cell01"));
cell01.setBackgroundColor(new Color(0, 200, 0));
cell01.setColspan(2);
PdfPCell cell11 = new PdfPCell(new Paragraph("Cell11"));
cell11.setBackgroundColor(new Color(100, 100, 0));
PdfPCell cell12 = new PdfPCell( getLongCellData() );
cell12.setBackgroundColor(new Color(0, 200, 200));
cell12.setRowspan(2);
PdfPCell cell21 = new PdfPCell(new Paragraph("Cell21"));
cell21.setBackgroundColor(new Color(200, 0, 200));
column2Table.addCell(cell01);
column2Table.addCell(cell11);
column2Table.addCell(cell12);
column2Table.addCell(cell21);
table.addCell(column1Table);
table.addCell(column2Table);
doc.add(table);
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
}
doc.close();
}
This issue is partially resolved on iText5, but, due to some issues upgrading library is not quite possible for us, so is there any solution for this ?
With iText5 the data is not getting cropped but cells' heights are not so appropriate. For TableLayout_2_withIText5.pdf cell21 should have rendered on page3 instead of page4. For TableLayout_1_withIText5.pdf cell21 is getting extended in the margin area of Page1.

ApachePOI generate excel (Autosize Row) with image using Java

I am trying to create excel file with image in it, using apache poi. What happening is data which i filled in other cells are not appearing.
ApachePOIImageDemo.java
public class ApachePOIImageDemo {
public static void main(String[] args) {
System.out.println("------------ Start Main()-------------!");
try {
List<Car> carList = new ArrayList<Car>();
Car car1 = new Car("white","GJ01OP1324","/home/vivek/1.jpg","White Maruthi 800");
Car car2 = new Car("Black","GJ01OP1244","/home/vivek/1.jpg","Black Mercedes");
Car car3 = new Car("Red","GJ01OP244","/home/vivek/1.jpg","Red Toyota Innova");
Car car4 = new Car("Blue","MH01OP1224","/home/vivek/1.jpg","Blue Renault Datson");
carList.add(car1);
carList.add(car2);
carList.add(car3);
carList.add(car4);
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("My Sample Excel");
CreationHelper creationHelper = workbook.getCreationHelper();
int index = 0;
for (Car carInstance : carList){
int columnNumber = 0;
Row row = sheet.createRow(index);
Cell cell0 = row.createCell(columnNumber++);
cell0.setCellValue(index);
Cell cell1 = row.createCell(columnNumber++);
cell1.setCellValue(carInstance.getCarColor());
Cell cell2 = row.createCell(columnNumber++);
cell2.setCellValue(carInstance.getCarPlateNumber());
InputStream inputStream = new FileInputStream(carInstance.getCarImage());
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = creationHelper.createClientAnchor();
anchor.setCol1(3);
anchor.setRow1(index);
anchor.setCol2(4);
anchor.setRow2(index+1);
Picture picture = drawing.createPicture(anchor, pictureIdx);
columnNumber++;
Cell cell4 = row.createCell(columnNumber++);
cell4.setCellValue(carInstance.getDescription());
index++;
}
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("myFile.xlsx");
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("------------ End Main() -------------!");
}
}
My Result :
Click here
I want to set auto height and width of the columns.
My images are of different sizes in practical. So I need to set auto height-width in my file.
Thank you in advance.
You can autosize your column, like this :
sheet.autoSizeColumn(numberOfYourCOlumnWithImage);

How to arrange cells in iText A4 document

I am developing an application to generate barcode. I need a number of bar codes to be generated at a time and add to a document of A4 size, using iText Table structure. Also all the barcodes to be positioned in a 13 X 5 matrix style, that fits A4 sheet, and to be printed. But for me, the bar codes are not properly aligned and positioned. Kindly help me.
This is the code:
int barwidthleft=(int) 14.112;
int barwidthtop=(int) 53.28;
int barwidthright=(int) 16.56;
int barwidthbottom=(int) 53.28;
float borderwidth=(float) 0.5;
int vgap=0;
int columns=0;
int i=0,j=0;
Rectangle pageSize = new Rectangle(new Rectangle(PageSize.A4));
Document document = new Document(pageSize);
document.setMargins(barwidthleft, barwidthright, barwidthtop, barwidthbottom);
try
{
PdfWriter writer =PdfWriter.getInstance(document,new FileOutputStream(new File("./barcode.pdf")));
document.open();
int count1=0,count2=0,count3=0,count4=0;
int maxcount=qty;
int itemcount=0,barcount=0;
columns=9;
Barcode128 code128 = new Barcode128();
code128.setGenerateChecksum(true);
String code="";
while(count2<maxcount)
{
PdfPTable table = new PdfPTable(columns); // 1 columns.
table.setWidthPercentage(100);
table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
table.setTotalWidth(new float[]{ (float)107.28, (float)5.61,(float)107.28, (float)5.61,(float)107.28, (float)5.61,(float)107.28, (float)5.61, (float)107.28});
table.setLockedWidth(true);
for(i=0;i<columns &&count2<maxcount;i=i+2)
{
code=Integer.toString(nextcode);
code128.setCode(code);
code128.setBarHeight(30);
code128.setX(1f);
Image img=code128.createImageWithBarcode(writer.getDirectContent(), null, null);
PdfPCell cell2 = new PdfPCell();
cell2.setFixedHeight((float) 59.04);
cell2.addElement(new Paragraph("Choice ",new Font(Font.FontFamily.COURIER, 6)));
cell2.addElement(new Paragraph("Rs. "+itemlist[itemcount][4]+"/-",new Font(Font.FontFamily.COURIER, 6)));
cell2.addElement(new Paragraph(" ",new Font(Font.FontFamily.COURIER, 2)));
cell2.addElement(img);
cell2.setBorder(PdfPCell.NO_BORDER);
cell2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cell2);
if(i!=8)
{
PdfPCell cellblank1 = new PdfPCell();
cellblank1.setBorder(PdfPCell.NO_BORDER);
cellblank1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cellblank1);
}
count2++;
itemcount++;
System.out.println("Two:"+count2);
nextcode++;
}
if(count2>=maxcount)
{
while(i<columns)
{
PdfPCell finalblank1 = new PdfPCell();
finalblank1.setBorder(PdfPCell.NO_BORDER);
finalblank1.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(finalblank1);
PdfPCell finalblank2 = new PdfPCell();
finalblank2.setBorder(PdfPCell.NO_BORDER);
finalblank2.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(finalblank1);
i=i+2;
}
}
document.add(table);
}
document.close();
//print
String[]args={};
PrintPdf.main(args);
}
catch(Exception e)
{
System.out.println(e);
}

how to create dynamic rows of records for creating xls file using list

Here after fetching records from database I have added data in some list and I have set some session variables for them so that I can access in another method by using get(key) method of session which I am successful to do so .Now what I want is I want to create dynamic records by setting this list value in row but I am unable to do so.It creates file but there is no record displayed .Below is my code:
package com.ca.actions;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import com.ca.database.Database;
import com.ca.pojo.Event;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
public class DataForGeneralReportsAction extends ActionSupport implements
Preparable, SessionAware {
private List<String> eventsGeneral = new ArrayList<String>();
private List<String> companiesGeneral = new ArrayList<String>();
private SessionMap<String, Object> sessionMapGeneral;
List<String> eventIdList = new ArrayList<String>();
List<String> eventNameList = new ArrayList<String>();
List<String> eventVenueList = new ArrayList<String>();
List<String> eventTimeList = new ArrayList<String>();
List<String> companyNameList = new ArrayList<String>();
List<String> totalAmountList = new ArrayList<String>();
List<String> receivedAmountList = new ArrayList<String>();
List<String> balanceAmountList = new ArrayList<String>();
List<String> eventTdsList = new ArrayList<String>();
List<String> paymentDateList = new ArrayList<String>();
List<String> chequeDdList = new ArrayList<String>();
private String eventGeneral = null;
private String companyGeneral = null;
List<Event> dataForGeneralReports;
public List<String> getEventIdList() {
return eventIdList;
}
public void setEventIdList(List<String> eventIdList) {
this.eventIdList = eventIdList;
}
public List<String> getEventNameList() {
return eventNameList;
}
public void setEventNameList(List<String> eventNameList) {
this.eventNameList = eventNameList;
}
public List<String> getEventVenueList() {
return eventVenueList;
}
public void setEventVenueList(List<String> eventVenueList) {
this.eventVenueList = eventVenueList;
}
public List<String> getEventTimeList() {
return eventTimeList;
}
public void setEventTimeList(List<String> eventTimeList) {
this.eventTimeList = eventTimeList;
}
public List<String> getCompanyNameList() {
return companyNameList;
}
public void setCompanyNameList(List<String> companyNameList) {
this.companyNameList = companyNameList;
}
public List<String> getTotalAmountList() {
return totalAmountList;
}
public void setTotalAmountList(List<String> totalAmountList) {
this.totalAmountList = totalAmountList;
}
public List<String> getReceivedAmountList() {
return receivedAmountList;
}
public void setReceivedAmountList(List<String> receivedAmountList) {
this.receivedAmountList = receivedAmountList;
}
public List<String> getBalanceAmountList() {
return balanceAmountList;
}
public void setBalanceAmountList(List<String> balanceAmountList) {
this.balanceAmountList = balanceAmountList;
}
public List<String> getEventTdsList() {
return eventTdsList;
}
public void setEventTdsList(List<String> eventTdsList) {
this.eventTdsList = eventTdsList;
}
public List<String> getPaymentDateList() {
return paymentDateList;
}
public void setPaymentDateList(List<String> paymentDateList) {
this.paymentDateList = paymentDateList;
}
public List<String> getChequeDdList() {
return chequeDdList;
}
public void setChequeDdList(List<String> chequeDdList) {
this.chequeDdList = chequeDdList;
}
public SessionMap<String, Object> getSessionMapGeneral() {
return sessionMapGeneral;
}
public void setSessionMapGeneral(
SessionMap<String, Object> sessionMapGeneral) {
this.sessionMapGeneral = sessionMapGeneral;
}
public String getEventGeneral() {
return eventGeneral;
}
public void setEventGeneral(String eventGeneral) {
this.eventGeneral = eventGeneral;
}
public String getCompanyGeneral() {
return companyGeneral;
}
public void setCompanyGeneral(String companyGeneral) {
this.companyGeneral = companyGeneral;
}
public List<Event> getDataForGeneralReports() {
return dataForGeneralReports;
}
public void setDataForGeneralReports(List<Event> dataForGeneralReports) {
this.dataForGeneralReports = dataForGeneralReports;
}
public List<String> getEventsGeneral() {
return eventsGeneral;
}
public void setEventsGeneral(List<String> eventsGeneral) {
this.eventsGeneral = eventsGeneral;
}
public List<String> getCompaniesGeneral() {
return companiesGeneral;
}
public void setCompaniesGeneral(List<String> companiesGeneral) {
this.companiesGeneral = companiesGeneral;
}
public DataForGeneralReportsAction() {
// TODO Auto-generated constructor stub
}
#Override
public void prepare() throws Exception {
// TODO Auto-generated method stub
Connection con = null;
try {
con = new Database().Get_Connection();
// load companies
PreparedStatement ps = con
.prepareStatement("SELECT DISTINCT company_name FROM event");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
companiesGeneral.add(rs.getString("company_name"));
}
// load events
ps = con.prepareStatement("SELECT DISTINCT event_name FROM event");
rs = ps.executeQuery();
while (rs.next()) {
eventsGeneral.add(rs.getString("event_name"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
}
}
#Override
public String execute() throws Exception {
Connection con = null;
try {
con = new Database().Get_Connection();
// load the table. The first time the table is loaded completely
String sql = "SELECT EVENT_ID, EVENT_NAME, COMPANY_NAME,EVENT_VENUE,TOTAL_AMOUNT,RECEIVED_AMOUNT,EVENT_TDS,BALANCE_AMOUNT,CHEQUE_DD_NO,"
+ "date_format(PAYMENT_DATE,'%d/%m/%Y') as dateAsPayment,EVENT_TIME "
+ "FROM event";
String where = "";
// if instead this action has been called from the JSP page,
// the result is filtered on event and company:
if (eventGeneral != null && companyGeneral != null) {
where = " WHERE event_name = ? AND company_name = ?";
}
// load companies
PreparedStatement ps = con.prepareStatement(sql + where);
if (where.length() > 0) {
ps.setString(1, eventGeneral);
ps.setString(2, companyGeneral);
}
dataForGeneralReports = new ArrayList<Event>();
ResultSet rs = ps.executeQuery();
int i, j = 0;
while (rs.next()) {
dataForGeneralReports.add(new Event(rs.getString("EVENT_ID"),
rs.getString("EVENT_NAME"), rs
.getString("COMPANY_NAME"), rs
.getString("EVENT_VENUE"), rs
.getString("EVENT_TIME"), rs
.getString("TOTAL_AMOUNT"), rs
.getString("RECEIVED_AMOUNT"), rs
.getString("CHEQUE_DD_NO"), rs
.getString("dateAsPayment"), rs
.getString("BALANCE_AMOUNT"), rs
.getString("EVENT_TDS")));
eventIdList.add(rs.getString("EVENT_ID"));
eventNameList.add(rs.getString("EVENT_NAME"));
companyNameList.add(rs.getString("COMPANY_NAME"));
eventVenueList.add(rs.getString("EVENT_VENUE"));
eventTimeList.add(rs.getString("EVENT_TIME"));
totalAmountList.add(rs.getString("TOTAL_AMOUNT"));
receivedAmountList.add(rs.getString("RECEIVED_AMOUNT"));
chequeDdList.add(rs.getString("CHEQUE_DD_NO"));
paymentDateList.add(rs.getString("dateAsPayment"));
eventTdsList.add(rs.getString("EVENT_TDS"));
balanceAmountList.add(rs.getString("BALANCE_AMOUNT"));
}
sessionMapGeneral.put("eventIdPdf", eventIdList);
sessionMapGeneral.put("eventNamePdf", eventNameList);
sessionMapGeneral.put("companyNamePdf", companyNameList);
sessionMapGeneral.put("eventVenuePdf", eventVenueList);
sessionMapGeneral.put("eventTimePdf", eventTimeList);
sessionMapGeneral.put("totalAmountPdf", totalAmountList);
sessionMapGeneral.put("receivedAmountPdf", receivedAmountList);
sessionMapGeneral.put("chequeDdPdf", chequeDdList);
sessionMapGeneral.put("paymentDatePdf", paymentDateList);
sessionMapGeneral.put("eventTdsPdf", eventTdsList);
sessionMapGeneral.put("balanceAmountPdf", balanceAmountList);
} catch (Exception e) {
e.printStackTrace();
} finally {
con.close();
}
return SUCCESS;
}
public String generatePdfGeneral() throws Exception {
System.out.println(sessionMapGeneral.get("eventIdPdf"));
Document document = new Document(PageSize.A4_LANDSCAPE, 50, 50, 50, 50);
float[] columnWidths = { 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("D:\\GeneralReports.pdf"));
PdfPTable table = new PdfPTable(11);
table.setSpacingBefore(25);
table.setWidthPercentage(100);
table.setSpacingAfter(25);
table.setWidths(columnWidths);
PdfPCell c1 = new PdfPCell(new Phrase("Event ID "));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Event Name "));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Event Time"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Event Venue"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Company Name"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Total Amount"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Received Amount"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Cheque/DD Number"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Payment Date"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Event TDS"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
c1 = new PdfPCell(new Phrase("Balance Amount"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);
PdfPCell cell = new PdfPCell();
List<String> list = (List<String>) sessionMapGeneral.get("eventIdPdf");
for (String item : list) {
cell.addElement(new Paragraph(item));
}
PdfPCell cell1 = new PdfPCell();
List<String> list1 = (List<String>) sessionMapGeneral
.get("eventNamePdf");
for (String item : list1) {
cell1.addElement(new Paragraph(item));
}
table.addCell(cell1);
PdfPCell cell2 = new PdfPCell();
List<String> list2 = (List<String>) sessionMapGeneral
.get("eventTimePdf");
for (String item : list2) {
cell2.addElement(new Paragraph(item));
}
table.addCell(cell2);
PdfPCell cell3 = new PdfPCell();
List<String> list3 = (List<String>) sessionMapGeneral
.get("eventVenuePdf");
for (String item : list1) {
cell3.addElement(new Paragraph(item));
}
table.addCell(cell3);
PdfPCell cell4 = new PdfPCell();
List<String> list4 = (List<String>) sessionMapGeneral.get("eventIdPdf");
for (String item : list4) {
cell4.addElement(new Paragraph(item));
}
table.addCell(cell4);
PdfPCell cell5 = new PdfPCell();
List<String> list5 = (List<String>) sessionMapGeneral
.get("companyNamePdf");
for (String item : list5) {
cell5.addElement(new Paragraph(item));
}
table.addCell(cell5);
PdfPCell cell6 = new PdfPCell();
List<String> list6 = (List<String>) sessionMapGeneral
.get("totalAmountPdf");
for (String item : list6) {
cell6.addElement(new Paragraph(item));
}
table.addCell(cell6);
PdfPCell cell7 = new PdfPCell();
List<String> list7 = (List<String>) sessionMapGeneral
.get("receivedAmountPdf");
for (String item : list7) {
cell7.addElement(new Paragraph(item));
}
table.addCell(cell7);
PdfPCell cell8 = new PdfPCell();
List<String> list8 = (List<String>) sessionMapGeneral
.get("chequeDdPdf");
for (String item : list8) {
cell8.addElement(new Paragraph(item));
}
table.addCell(cell8);
PdfPCell cell9 = new PdfPCell();
List<String> list9 = (List<String>) sessionMapGeneral
.get("paymentDatePdf");
for (String item : list9) {
cell9.addElement(new Paragraph(item));
}
table.addCell(cell9);
PdfPCell cell10 = new PdfPCell();
List<String> list10 = (List<String>) sessionMapGeneral
.get("eventTdsPdf");
for (String item : list10) {
cell10.addElement(new Paragraph(item));
}
table.addCell(cell10);
PdfPCell cell11 = new PdfPCell();
List<String> list11 = (List<String>) sessionMapGeneral
.get("balanceAmountPdf");
for (String item : list11) {
cell11.addElement(new Paragraph(item));
}
table.addCell(cell11);
document.open();
document.add(table);
document.close();
return "success";
}
public String generateGeneralXls() throws Exception {
try {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("Event ID");
rowhead.createCell(1).setCellValue("Event Name");
rowhead.createCell(2).setCellValue("Event Time");
rowhead.createCell(3).setCellValue("Event Venue");
rowhead.createCell(4).setCellValue("Company Name");
rowhead.createCell(5).setCellValue("Total Amount");
rowhead.createCell(6).setCellValue("Received Amount");
rowhead.createCell(7).setCellValue("Payment Date");
rowhead.createCell(8).setCellValue("Cheque/DD No.");
rowhead.createCell(9).setCellValue("Event TDS");
rowhead.createCell(10).setCellValue("Balance Amount");
FileOutputStream fileOut;
fileOut = new FileOutputStream("D:\\Samplmgjkm.xls");
// HSSFRow row1 = sheet.createRow((short) 1);
System.out.println(sessionMapGeneral.size());
for (int i = 1; i <= sessionMapGeneral.size(); i++) {
HSSFRow row1 = sheet.createRow((short) i);
row1.createCell(i-1).setCellValue(
sessionMapGeneral.get("eventIdPdf").toString());
row1.createCell(i).setCellValue(
sessionMapGeneral.get("eventNamePdf").toString());
}
/*
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
* row1.createCell(1).setCellValue(
* sessionMapGeneral.get("eventNamePdf").toString());
*/
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
#Override
public void setSession(Map<String, Object> map) {
// TODO Auto-generated method stub
sessionMapGeneral = (SessionMap) map;
}
}
I have edited my code where I get result in string but all records are displayed in single cell. I want each record in new cell.I have attached image of how it looks.
No error is displayed. Please help me to solve my problem.
Try this:
FileOutputStream fileOut;
fileOut = new FileOutputStream("D:\\Samplmgjkm.xls");
int nextRow = 1;
while(rs.next()){
HSSFRow r = sheet.getRow(nextRow);
if (r == null) {
r = sheet.createRow(nextRow);
}
HSSFCell c = r.getCell(1, Row.CREATE_NULL_AS_BLANK);
c.setCellValue(rs.getString(1));
HSSFCell c2 = r.getCell(2, Row.CREATE_NULL_AS_BLANK);
c2.setCellValue(rs.getString(2));
nextRow++;
}
First poposal : use event object.You build a list of Event object you could use and put in SessionMap and if you want, build the other list using list of Events)
here and Exemple assuming you have getter in Event Object :
public String generateGeneralXls() throws Exception {
try {
String titles="Event ID,Event Name,Event Time,Event Venue,Company Name,Total Amount,Received Amount,Payment Date,Cheque/DD No,Event TDS,Balance Amount";
String[]arrTiltes=titles.split(",");
FileOutputStream fileOut = new FileOutputStream("poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
int row=0;
HSSFRow rowTitle = worksheet.createRow(row);
// set titles
for(int i=0;i<arrTiltes.length;i++){
HSSFCell cellTitle=rowTitle.createCell(i);
cellTitle.setCellValue(arrTiltes[i]);
}
//setting values
row++;
for(Event dataValue:dataForGeneralReports){
HSSFRow rowValue = worksheet.createRow(row);
HSSFCell cell0 = rowValue.createCell(0);
cell0.setCellValue(dataValue.getEventID());
HSSFCell cell1 = rowValue.createCell(1);
cell1.setCellValue(dataValue.getEventName());
HSSFCell cell2 = rowValue.createCell(2);
cell2.setCellValue(dataValue.getEventTime());
HSSFCell cell3 = rowValue.createCell(3);
cell3.setCellValue(dataValue.getEventVenue());
HSSFCell cell4 = rowValue.createCell(4);
cell4.setCellValue(dataValue.getCompanyName());
HSSFCell cell5 = rowValue.createCell(5);
cell5.setCellValue(dataValue.getTotalAmount());
HSSFCell cell6 = rowValue.createCell(6);
cell6.setCellValue(dataValue.getReceivedAmount());
HSSFCell cell7 = rowValue.createCell(7);
cell7.setCellValue(dataValue.getPaymentDate());
HSSFCell cell8 = rowValue.createCell(8);
cell8.setCellValue(dataValue.getChequeDDNo());
HSSFCell cell9 = rowValue.createCell(9);
cell9.setCellValue(dataValue.getEventTDS());
HSSFCell cell10 = rowValue.createCell(10);
cell10.setCellValue(dataValue.getBalanceAmount());
row++;
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
you can use the same idea for you PDF.
be carreful in your code for PDF, i suspect you don't have results expected.
you have forgotten adding cell on table ( first cell on your code)
you have 12 cells however you declare 11:
i sugest you o remove "block" for
PdfPCell cell4
second proposal : if you want really use your lists, then iterate over each list to get first value in each of them, second value of each of them etc..
Exemple assuming all list have the same size (coming from your resultset):
public String generateGeneralXlsOther() throws Exception {
try {
String titles="eventIdPdf,eventNamePdf,companyNamePdf,eventVenuePdf,eventTimePdf,totalAmountPdf,receivedAmountPdf,receivedAmountPdf,chequeDdPdf,paymentDatePdf,eventTdsPdf,balanceAmountPdf";
String[]arrTiltes=titles.split(",");
FileOutputStream fileOut = new FileOutputStream("poi-testOtehr.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("POI Worksheet");
HSSFRow rowTitle = worksheet.createRow(0);
// set titles
for(int i=0;i<arrTiltes.length;i++){
HSSFCell cellTitle=rowTitle.createCell(i);
cellTitle.setCellValue(arrTiltes[i]);
}
int size=((List<String>) sessionMapGeneral.get(arrTiltes[0])).size();
for(int row=0;row<size;row++){
HSSFRow rowValue = worksheet.createRow(row+1);
int cell=0;
for(int i=0;i<arrTiltes.length;i++){
List<String> theList=(List<String>) sessionMapGeneral.get(arrTiltes[i]);
HSSFCell cell0 = rowValue.createCell(cell);
cell0.setCellValue(theList.get(row));
cell++;
}
}
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
I have checked your code and done some editing as below, so please refer below code and you will get solution.
List<String> eventIdPdf = (List<String>) sessionMapGeneral.get("eventNamePdf");
List<String> eventNamePdf = (List<String>) sessionMapGeneral.get("eventNamePdf");
for (int i = 1; i <= sessionMapGeneral.size(); i++) {
HSSFRow row1 = sheet.createRow((short) i);
row1.createCell(i-1).setCellValue(eventIdPdf.get(i).toString());
row1.createCell(i).setCellValue(eventNamePdf.get(i).toString());
}
As you are taking list of strings in one variable like eventIdPdf, so as per your use in code you are writing entire list in one cell therefor you are getting entire list in one cell, now check above method so it will display one by one answer.
Hope this will work..
Your first problem is here:
row1.createCell(i-1).setCellValue(
sessionMapGeneral.get("eventIdPdf").toString());
because sessionMapGeneral.get("eventIdPdf").toString() returns the whole eventIdList, or more precisely, all values of eventIdList as a String, so the result of this expression looks like "[value1, value2, ... , valueN]"
and this (very long) result goes comletely to the row1.createCell(i-1). But actually, Cell(i-1) should get only the "value1". And here we go to
your second problem:
for (int i = 1; i <= sessionMapGeneral.size(); i++)
You iterate just through the sessionMapGeneral, but iterating through 2D-structures like tables or matrices requires two loops (nested loop). Notice, your sessionMapGeneral's elements are Key-Value pairs, where every Key is a String, e.g. "eventIdPdf", and every Value is a List, e.g. eventIdList. So, in the first loop you should access the values (Lists) of the sessionMapGeneral to get to your data stored there. Then, in the second loop, you can iterate through the Lists you got in the first loop, in order to get every single data item and set it into the required cell of the table.
The next small problem is, you can't access SessionMap's elements by index, but there is a way to "beat the system" :) - here it is
your solution: (please pay attention to comments)
//modify your key-Strings in order to be able to sort them later easily
sessionMapGeneral.put("01_eventIdPdf", eventIdList);
sessionMapGeneral.put("02_eventNamePdf", eventNameList);
sessionMapGeneral.put("03_companyNamePdf", companyNameList);
sessionMapGeneral.put("04_eventVenuePdf", eventVenueList);
sessionMapGeneral.put("05_eventTimePdf", eventTimeList);
sessionMapGeneral.put("06_totalAmountPdf", totalAmountList);
sessionMapGeneral.put("07_receivedAmountPdf", receivedAmountList);
sessionMapGeneral.put("08_chequeDdPdf", chequeDdList);
sessionMapGeneral.put("09_paymentDatePdf", paymentDateList);
sessionMapGeneral.put("10_eventTdsPdf", eventTdsList);
sessionMapGeneral.put("11_balanceAmountPdf", balanceAmountList);
...
fileOut = new FileOutputStream("D:\\Samplmgjkm.xls");
// get all the key-Strings from sessionMapGeneral and store them in an ArrayList in order to be able to access the elements by index
List<String> keys = new ArrayList<String>(sessionMapGeneral.keySet());
// and sort them, so that they suit to your "rowhead"
Collections.sort(keys);
// iterate through the keys and fill out the xls table column by column:
for (int key = 0; key < keys.size(); key++) {
//hold the current List from sessionMapGeneral for the current column in a variable
List<String> currentList = (List<String>) (sessionMapGeneral.get(keys.get(key)));
// iterate through the current ArrayList (column) and fill out the cells of this column row by row:
for (int row = 0; row < currentList.size(); row++) {
// hold the current row in a variable
HSSFRow currentRow = sheet.getRow(row+1);
// create a row only once to avoid deleting the data set earlier and set the value into the cell
if (currentRow == null) {
currentRow = sheet.createRow((short) row+1); // I don't understand why do you cast it to short. To save 16 bit per row?
currentRow.createCell(key).setCellValue(currentList.get(row));
} else {
currentRow.createCell(key).setCellValue(currentList.get(row));
}
}
// to make the width of columns looking well, add this line here:
sheet.autoSizeColumn(key);
}

Categories