PDF/Excel sheet writing through JAVA
Hi,
Today I
am going to explain the writing of PDF and Excel sheet through java.
To write
the data from java to PDF file you may require the following
supporting jars,
jText-2.1.5.jar
gnujaxp.jar
jcommon-1.0.17.jar
I use
the netbean IDE for the development where I added the above jars on
the project library
for
download above jar's click hereHere I create the JFileChooser to select the destination where we want to save a file
Create a function which will ask you to select the file type for saving or exporting data to
pdf or excel sheet
public JFileChooser file_select
public void Select_fileType()
{
try
{
file_select =new JFileChooser();
file_select.setFileSelectionMode(JFileChooser.FILES_ONLY);
file_select.setFileFilter(new FileTypeFilter(".pdf", "PDF Document"));
file_select.setFileFilter(new FileTypeFilter(".xls", "Excel Document"));
file_select.setAcceptAllFileFilterUsed(true);
int result= file_select.showSaveDialog(this);
if(result==0)
{
if(file_select.getFileFilter().getDescription().contains("pdf"))
{
if(objReport!=null)
{
Save_PDF();
}
else
{
JOptionPane.showMessageDialog(this, "Can't Save to PDF\n Please generate reports", "Error at generating PDF", JOptionPane.INFORMATION_MESSAGE);
}
}
else if(file_select.getFileFilter().getDescription().contains("xls"))
{
if(objReport!=null)
{
Save_Excel();
}
else
{
JOptionPane.showMessageDialog(this, "Can't Save to XLS\n Please generate reports", "Error at generating XLS", JOptionPane.INFORMATION_MESSAGE);
}
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
//The above function will show the following output
Here I create the two different function and call it on respective event
First function will save the hole data on the pdf i.e create the pdf file.
Second function will save the hole data on the excel i.e create the excel file.
First I demonstrate the writing of a PDF file
public void Save_PDF()
{
Save_Pdf_Document(file_select.getSelectedFile(), file_select);
}
The Save_PDF function call the other function i.e save_Pdf_Document which has the two
parameters first parameter is the name of pdf file which we written on the JFileChooser
and the second parameter is for the JFileChooser object
public void Save_Pdf_Document(File f, JFileChooser jfname)
{
try {
// tbl_result is the JTable which will containe the data
int tableCount = tbl_result.getRowCount();
Document document = new Document();
//Document is the single page document on the pdf file
PdfWriter writer= PdfWriter.getInstance(document, new FileOutputStream(jfname.getCurrentDirectory() + "/" + f.getName() + ".pdf"));
document.open();
document.setFooter(new com.lowagie.text.HeaderFooter(new Phrase(" \t\t\t\t\tpage no:- "), new Phrase(" ")));
// adding images
// it will add the image on the pdf as a logo for the PDF on first page
com.lowagie.text.Image imgLogo=com.lowagie.text.Image.getInstance("logo.jpg");
//imgLogo.setAbsolutePosition(0, 5);
imgLogo.scaleToFit(150, 100);
document.add(imgLogo);
Paragraph paragraph = new Paragraph();
String citys="\n\nReports\n\n";
paragraph.add(citys);
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
//PdfPTable is the inbuild function which will create the table
on the pdf
PdfPTable tab = new PdfPTable(tbl_result.getColumnCount());
tab.setTotalWidth(new float[]{ 80,80,80});
tab.setLockedWidth(true);
//PdfPCell is the column
PdfPCell c1 = new PdfPCell(new Phrase("Booking ID"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
c1.setBackgroundColor(Color.CYAN);
tab.addCell(c1);
PdfPCell c2 = new PdfPCell(new Phrase("Supplier"));
c2.setHorizontalAlignment(Element.ALIGN_CENTER);
c2.setBackgroundColor(Color.CYAN);
tab.addCell(c2);
PdfPCell c3 = new PdfPCell(new Phrase("Amount"));
c3.setHorizontalAlignment(Element.ALIGN_CENTER);
c3.setBackgroundColor(Color.CYAN);
tab.addCell(c3);
for (int i = 0; i < tableCount; i++)
{
String strBookingID;
String strSupplier;
String strAmount;
//for Booking Id
if (GetData(tbl_result, i, 0) == null) {
strBookingID = "-";
} else {
strBookingID = GetData(tbl_result, i, 0).toString();
}
tab.addCell(strBookingID);
//for supplier
if (GetData(tbl_result, i, 1) == null) {
strSupplier = "-";
} else {
strSupplier = GetData(tbl_result, i, 1).toString();
}
tab.addCell(strSupplier);
//for Amount
if (GetData(tbl_result, i, 2) == null) {
strAmount = "-";
} else {
strAmount = GetData(tbl_result, i, 2).toString();
}
tab.addCell(strAmount);
}
document.add(tab);
int pno=writer.getPageNumber();
document.addHeader("Page No ", ""+pno);
document.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
// This function will get the data of respective cell from JTable public Object GetData(JTable table, int row_index, int col_index) {
return table.getModel().getValueAt(row_index, col_index);
}
The next step is creating an Excel sheet
Following function will create the Excel file this function having two parameters
same as the above Save_Pdf_Document function , first parameter is the file name and other
one is the file path
public void Save_Excel_Document(File f, JFileChooser jfname) {
try {
WritableWorkbook workbook1 = Workbook.createWorkbook(f);
WritableSheet sheet1 = workbook1.createSheet("First Sheet", 0);
//tbl_result is the JTable object
TableModel model = tbl_result.getModel();
String Col_name[] = {"Booking Id", "Supplier", "Amount", "Supplier Rate", "Service Date", "Agent Name", "Agency Name"};
for (int i = 0; i < model.getColumnCount(); i++) {
Label column = new Label(i, 0, model.getColumnName(i).replace(model.getColumnName(i), Col_name[i]));
// String column = model.getColumnName(i).toString();
sheet1.addCell(column);
}
int j = 0;
for (int i = 0; i < model.getRowCount(); i++) {
for (j = 0; j < model.getColumnCount(); j++) {
if (model.getValueAt(i, j) != null) {
Label row = new Label(j, i + 1, model.getValueAt(i, j).toString());
sheet1.addCell(row);
} else {
Label row = new Label(j, i + 1, "-");
sheet1.addCell(row);
}
}
}
workbook1.write();
workbook1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you...
Nice
ReplyDelete