这几天没事,写了一个小功能;将excel中的内容写入到PDF中;是用JXL和ITEXT一起写的;JXL读取excel,然后把读到的内容写到pdf中;但是没有对excel中合并的单元格进行处理。以后有时间再研究一下补上吧!把写的代码发上来,希望能帮上有用的人;如果有更好的方法或建议,请留言一起学习;
package zText;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.Paragraph;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
public class ItextTest {
//生成PDF
public void WItext(){
Workbook book;
Document document = new Document();
try {
book = Workbook.getWorkbook(new File("d:/test.xls")); //用JXL读取excel
Sheet sheet = book.getSheet(0);//读取excel第1页
Cell cell = null;
int Columns = sheet.getColumns();//读取excel的列数
int Rows = sheet.getRows();//读取excel的行数
System.out.println(Columns);
System.out.println(Rows);
PdfWriter.getInstance(document, new FileOutputStream("d:/Chap0707.pdf"));//用ITEXT写一个名为Chap0707的PDF
document.open();//打开Chap0707
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); //显示中文
Font FontChinese = new Font(bfChinese, 12, Font.NORMAL); //显示中文
Table aTable = new Table(Columns,Rows);//在PDF中加入表格
aTable.setWidth(90); //设置表格宽度
aTable.setCellspacing(5);//设置表格行高
aTable.setAutoFillEmptyCells(true);//表格的单元格中无内容时显示空格子
for(int i=0;i<Rows;i++){ //读第i行数
for(int j=0;j<Columns;j++){ //读第i列的第j列
String result = sheet.getCell(j, i).getContents();//得到excel中每个单元格的内容;
System.out.println(result);
aTable.addCell( new Paragraph(result,FontChinese));//将excel中每个单元格的内容填写到PDF的表格中;
}
}
document.add(aTable);
document.close();
} catch (BiffException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
System.out.println("进来了");
ItextTest tItextTest = new ItextTest();
tItextTest.WItext();
System.out.println("结束了");
}
}