将excel中的内容写入到PDF中(java)

这篇博客介绍了一种结合JXL和ITEXT库的方法,将Excel文件中的内容转换并写入PDF文档。虽然目前的实现未处理Excel中的合并单元格,作者计划在未来完善这一部分,并分享了代码以供参考,期待读者的反馈和建议。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天没事,写了一个小功能;将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("结束了");
}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值