7
如何將excel
文件轉換/保存到pdf
?我正在使用java play framework
生成一些excel
文件,現在需求更改爲pdf
。我不想重新編碼一切。Java Apache POI Excel另存爲PDF
有沒有辦法轉換爲pdf
?
我生成的excel
文件來自模板;我讀了excel模板文件,寫入更改,並保存爲新的excel文件。這樣,模板不變。它包含邊框,圖像和其他格式。
如何將excel
文件轉換/保存到pdf
?我正在使用java play framework
生成一些excel
文件,現在需求更改爲pdf
。我不想重新編碼一切。Java Apache POI Excel另存爲PDF
有沒有辦法轉換爲pdf
?
我生成的excel
文件來自模板;我讀了excel模板文件,寫入更改,並保存爲新的excel文件。這樣,模板不變。它包含邊框,圖像和其他格式。
您需要以下Java庫和關聯的JAR文件才能使程序正常工作。 POI V3.8 iText的v5.3.4
嘗試這個例子爲XLS轉換爲PDF
接受Excel電子表格數據作爲輸入並轉換成完整的Java代碼,以提供一種表PDF數據如下:
import java.io.FileInputStream;
import java.io.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.usermodel.*;
import java.util.Iterator;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
public class excel2pdf {
public static void main(String[] args) throws Exception{
FileInputStream input_document = new FileInputStream(new File("C:\\excel_to_pdf.xls"));
// Read workbook into HSSFWorkbook
HSSFWorkbook my_xls_workbook = new HSSFWorkbook(input_document);
// Read worksheet into HSSFSheet
HSSFSheet my_worksheet = my_xls_workbook.getSheetAt(0);
// To iterate over the rows
Iterator<Row> rowIterator = my_worksheet.iterator();
//We will create output PDF document objects at this point
Document iText_xls_2_pdf = new Document();
PdfWriter.getInstance(iText_xls_2_pdf, new FileOutputStream("Excel2PDF_Output.pdf"));
iText_xls_2_pdf.open();
//we have two columns in the Excel sheet, so we create a PDF table with two columns
//Note: There are ways to make this dynamic in nature, if you want to.
PdfPTable my_table = new PdfPTable(2);
//We will use the object below to dynamically add new data to the table
PdfPCell table_cell;
//Loop through rows.
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next(); //Fetch CELL
switch(cell.getCellType()) { //Identify CELL type
//you need to add more code here based on
//your requirement/transformations
case Cell.CELL_TYPE_STRING:
//Push the data from Excel to PDF Cell
table_cell=new PdfPCell(new Phrase(cell.getStringCellValue()));
//feel free to move the code below to suit to your needs
my_table.addCell(table_cell);
break;
}
//next line
}
}
//Finally add the table to PDF document
iText_xls_2_pdf.add(my_table);
iText_xls_2_pdf.close();
//we created our pdf file..
input_document.close(); //close xls
}
}
我希望這會幫助你