关于用java导出PDF EXCEL

belong_jars 2011-08-15 09:29:32
如题,这周老大要我自学用java导出pdf、excel文件,但是我上网查了下资料,根本就不知道要从哪里下手,我们的的技术是基于SSH框架的,我想问下,我这个要怎么做,有什么案例的可以看的。谢谢!!!
...全文
468 17 打赏 收藏 转发到动态 举报
写回复
用AI写文章
17 条回复
切换为时间正序
请发表友善的回复…
发表回复
Maakey 2012-12-24
  • 打赏
  • 举报
回复
引用 9 楼 belong_jars 的回复:
引用 8 楼 ioe_gaoyong 的回复:导出PDF的用iText这个组件,楼主可以搜索下 对头 是用这个 这个iText也可以导出excel吧? 现在我遇到了一个问题,这是我写的一个测试用itext导出pdf的案例,照网上搜的例子做的: public class ItextProduce { public static void main(String[] a……
楼主这个问题怎么解决的啊?给解释一下啊
hfan365 2011-08-16
  • 打赏
  • 举报
回复
高手不少,真的可用耶
belong_jars 2011-08-16
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 ioe_gaoyong 的回复:]

给楼主贴一个demo,然后iText所需要的jar包你可以留一个email我给你发过去,照着例子就可以学习了
Java code
import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

/**
* iText5的……
[/Quote]
谢谢啦!就发在我的QQ邮箱上吧,466819370@qq.com

风尘中国 2011-08-16
  • 打赏
  • 举报
回复
给楼主贴一个demo,然后iText所需要的jar包你可以留一个email我给你发过去,照着例子就可以学习了
import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

/**
* iText5的入门学习文档,这个demo已经提供了自己想要的最为常见的实现
*
* 这个文档主要学习利用itext实现创建PDF文档
* 我需要学习利用itext实现读取PDF文档的内容
* @author http://www.coderanch.com/how-to/java/ItextExample
*
*/

public class Demo {

public static void main (String[] args) {

// creation of the document with a certain size and certain margins
// may want to use PageSize.LETTER instead
Document document = new Document(PageSize.A4, 50, 50, 50, 50);
try {
// creation of the different writers
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("etc/demo.pdf"));
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

HeaderFooter event = new HeaderFooter();
writer.setPageEvent(event);

// various fonts
BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

int y_line1 = 650;
int y_line2 = y_line1 - 50;
int y_line3 = y_line2 - 50;

document.open();

PdfContentByte cb = writer.getDirectContent();
cb.setLineWidth(0f);
cb.moveTo(250, y_line3 - 100);
cb.lineTo(250, y_line1 + 100);
cb.moveTo(50, y_line1);
cb.lineTo(400, y_line1);
cb.moveTo(50, y_line2);
cb.lineTo(400, y_line2);
cb.moveTo(50, y_line3);
cb.lineTo(400, y_line3);
cb.stroke();
cb.beginText();
cb.setFontAndSize(bf_helv, 12);
String text = "Sample text for alignment";
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, text + " Center", 250, y_line1, 0);
cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, text + " Right", 250, y_line2, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, text + " Left", 250, y_line3, 0);
cb.endText();

document.newPage();

// add text in two paragraphs from top to bottom
Paragraph par = new Paragraph("bold paragraph");
par.getFont().setStyle(Font.BOLD);
document.add(par);
par = new Paragraph("italic paragraph");
par.getFont().setStyle(Font.ITALIC);
document.add(par);
par = new Paragraph("underlined and strike-through paragraph");
par.getFont().setStyle(Font.UNDERLINE | Font.STRIKETHRU);
document.add(par);

// demonstrate some table features
PdfPTable table = new PdfPTable(3);
table.setSpacingBefore(20);
table.getDefaultCell().setPadding(5);

PdfPCell cell = new PdfPCell(new Phrase("header"));
cell.setPadding(5);
cell.setColspan(3);
table.addCell(cell);
table.setHeaderRows(1);
cell = new PdfPCell(new Phrase("example cell with rowspan 2 and red border"));
cell.setPadding(5);
cell.setRowspan(2);
cell.setBorderColor(new BaseColor(new Color(255, 0, 0)));
table.addCell(cell);
table.addCell("中文");
table.addCell("2.1");
table.addCell("1.2");
table.addCell("2.2");
cell = new PdfPCell(new Phrase("align center"));
cell.setPadding(5);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
cell = new PdfPCell(new Phrase("rotated cell"));
cell.setPadding(5);
cell.setRowspan(2);
cell.setColspan(2);
// PdfPCell content can be rotated
cell.setRotation(90);
table.addCell(cell);
cell = new PdfPCell(new Phrase("align right"));
cell.setPadding(5);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(cell);
document.add(table);

// add text at an absolute position
cb.beginText();
cb.setFontAndSize(bf_times, 14);
cb.setTextMatrix(100, 300);
cb.showText("Text at position 100, 300.");
cb.endText();

// rotated text at an absolute position
PdfTemplate template = cb.createTemplate(300, 300);
template.beginText();
template.setFontAndSize(bf_times, 14);
template.showText("Rotated text at position 400, 200.");
template.endText();

float rotate = 90;
float x = 400;
float y = 200;
float angle = (float) (-rotate * (Math.PI / 180));
float xScale = (float) Math.cos(angle);
float yScale = (float) Math.cos(angle);
float xRot = (float) -Math.sin(angle);
float yRot = (float) Math.sin(angle);

cb.addTemplate(template, xScale, xRot, yRot, yScale, x, y);

document.close();

} catch (Exception ex) {
System.err.println(ex.getMessage());
}
}

/** Inner class to add a header and a footer. */
static class HeaderFooter extends PdfPageEventHelper {

public void onEndPage (PdfWriter writer, Document document) {
Rectangle rect = writer.getBoxSize("art");
switch(writer.getPageNumber() % 2) {
case 0:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, new Phrase("even header"),
rect.getRight(), rect.getTop(), 0);
break;
case 1:
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_LEFT, new Phrase("odd header"),
rect.getLeft(), rect.getTop(), 0);
break;
}
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_CENTER, new Phrase(String.format("page %d", writer.getPageNumber())),
(rect.getLeft() + rect.getRight()) / 2, rect.getBottom() - 18, 0);
}
}
}
风尘中国 2011-08-16
  • 打赏
  • 举报
回复
不清楚你的iText使用的版本是多少的,我用的是5.1版本的,你说的问题估计就是中文字体方面的支持,然后用的iTextAsian.jar这个包官方给的需要做一个处理才能用。
如果导出excel,用POI比较好
belong_jars 2011-08-16
  • 打赏
  • 举报
回复
[Quote=引用 9 楼 belong_jars 的回复:]

引用 8 楼 ioe_gaoyong 的回复:

导出PDF的用iText这个组件,楼主可以搜索下

对头 是用这个 这个iText也可以导出excel吧? 现在我遇到了一个问题,这是我写的一个测试用itext导出pdf的案例,照网上搜的例子做的:
public class ItextProduce {
public static void main(String[] args) t……
[/Quote]

上面说我这个The document is not open.然后我把document.close()给屏蔽了,就报Font 'STSongStd-Light' with 'UniGB-UCS2-H' is not recognized.
belong_jars 2011-08-16
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 ioe_gaoyong 的回复:]

导出PDF的用iText这个组件,楼主可以搜索下
[/Quote]
对头 是用这个 这个iText也可以导出excel吧? 现在我遇到了一个问题,这是我写的一个测试用itext导出pdf的案例,照网上搜的例子做的:
public class ItextProduce {
public static void main(String[] args) throws Exception {
// 创建一个document对象
Document document = null;
try {
document = new Document();
// 生成名为.pdf的文档
PdfWriter.getInstance(document, new FileOutputStream(
"e://ieres.pdf"));
BaseFont font=BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",false);
Font fontChinese=new Font(font,12,Font.NORMAL,Color.GREEN);


// 添加文档信息
document.addTitle("fsdfasfadfa");
document.addAuthor("aa");
document.addSubject("weewfefdsgfsdfsd");
document.addCreationDate();
document.addCreator("my first program us iText");
// 打开文档,将要写入内容
document.open();
// 插入一个段落
Paragraph p=new Paragraph("啊啊啊",fontChinese);
document.add(p);

} catch (DocumentException e) {
System.err.print(e.getMessage());
} catch (IOException e) {
System.err.print(e.getMessage());
}
document.close();

}
}

然后导入的包有iTextAsian.jar ,iText-2.1.5.jar,bcprov-jdk16-145.jar,然后我调试的时候是控制台报错,
Font 'STSongStd-Light' with 'UniGB-UCS2-H' is not recognized.Exception in thread "main" java.lang.RuntimeException: The document is not open.
at com.lowagie.text.pdf.PdfWriter.getDirectContent(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.newPage(Unknown Source)
at com.lowagie.text.pdf.PdfDocument.close(Unknown Source)
at com.lowagie.text.Document.close(Unknown Source)
at org.com.test.entity.ItextProduce.main(ItextProduce.java:51)
该怎么解决?
belong_jars 2011-08-16
  • 打赏
  • 举报
回复
[Quote=引用 12 楼 ioe_gaoyong 的回复:]

给楼主贴一个demo,然后iText所需要的jar包你可以留一个email我给你发过去,照着例子就可以学习了
Java code
import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

/**
* iText5的……
[/Quote]

真是高手 可以了 分全给你了 呵呵
shagan 2011-08-16
  • 打赏
  • 举报
回复
看你的样子,
应该导出的样子应该不是很复杂,
除实在没办法,自己用itext或POI呀jxl等开源jar写PDF与excel外,
一般情况下建议用jaspereporter,用ireport写template,
不复杂的话,很容易学。
建议用之。
小龙在线 2011-08-15
  • 打赏
  • 举报
回复
操作pdf,office,大多采用开源的中间件
softroad 2011-08-15
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 dragonsky_w 的回复:]

HTML code

<%@ page language="java" contentType="text/html;charset=UTF-8" import="java.util.*,java.io.*,java.sql.*,org.apache.poi.hssf.usermodel.*" pageEncoding="UTF-8"%>
<%
String path = request.ge……
[/Quote]

正解这是poi的,貌似是03版本的excel
支持07的

Workbook book = null;

try {
book = new HSSFWorkbook(in);
}
catch(OutOfMemoryError e) {
String msg = "The file " + excel.getName()
+ " data is error, please delete invalid data!";
if(log.isDebugEnabled()) {
log.debug(msg);
}

throw new Exception(msg);
}
catch(OfficeXmlFileException e) {
in = new FileInputStream(excel);
book = new XSSFWorkbook(in);
//throw new Exception(e.getMessage());
}

if(book == null || book.getNumberOfSheets() == 0) {
return null;
}

你是将什么导出为pdf?
sysnl 2011-08-15
  • 打赏
  • 举报
回复
收藏了,好东西,正好用上,谢谢楼主
dragonsky_w 2011-08-15
  • 打赏
  • 举报
回复

<%@ page language="java" contentType="text/html;charset=UTF-8" import="java.util.*,java.io.*,java.sql.*,org.apache.poi.hssf.usermodel.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>数据库导出成Excel文件测试</title>

</head>
<body>
<br><br><br><br>
<center>
<%
String driverName = "com.mysql.jdbc.Driver"; // 驱动名称
String userName = "root"; // 用户名
String password = "318404"; // 密码
String dbName = "test"; // 数据库名字
String tableName = "userinfo"; // 表名
String url="jdbc:mysql://localhost/"+dbName+"?user="+userName+"&password="+password;
Class.forName(driverName).newInstance();
Connection connection = DriverManager.getConnection(url);
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("SELECT userName,passWord,age,email,address FROM userinfo ");

%>
<%
HSSFWorkbook workbook = new HSSFWorkbook(); //创建新的Excel工作薄
HSSFSheet sheet = workbook.createSheet("userInfo"); //在Excel工作薄中建工作表,名为缺省
HSSFRow row = sheet.createRow((short)0); //在索引0的位置建行(最顶端的行)
//
HSSFCell cell = row.createCell((short)0); //在索引0的位置建单元格
// cell.setEncoding(HSSFCell.ENCODING_UTF_16); //定义单元格为字符串类型
cell.setCellValue("编号"); //在单元格输入一些内容

cell = row.createCell((short)1);
cell.setCellValue("姓名"); //在单元格输入一些内容

cell = row.createCell((short)2);
cell.setCellValue("密码");

cell = row.createCell((short)3);
cell.setCellValue("年龄");

cell = row.createCell((short)4);
cell.setCellValue("邮箱");

cell = row.createCell((short)5);
cell.setCellValue("地址");

int i = 1;
while(rs.next()){
row = sheet.createRow((short)i); //在索引1的位置创建行(最顶端的行)
cell = row.createCell((short)0); //在索引0的位置创建单元格(左上端)
cell.setCellValue(i); //在单元格输入一些内容

cell = row.createCell((short)1);
cell.setCellValue(rs.getString(1)); //在单元格输入一些内容

cell = row.createCell((short)2);
cell.setCellValue(rs.getString(2));

cell = row.createCell((short)3);
cell.setCellValue(rs.getString(3));

cell = row.createCell((short)4);
cell.setCellValue(rs.getString(4));

cell = row.createCell((short)5);
cell.setCellValue(rs.getString(5));

i++;
}
String filename = application.getRealPath("/") + "test.xls"; //filename是工作薄的存放位置,存放在当前应用程序的根目录下
FileOutputStream fOut = new FileOutputStream(filename); //新建输出文件流
workbook.write(fOut); //把相应的Excel工作薄存盘
fOut.flush();
fOut.close(); //操作结束,关闭文件
out.println("excel文件已经生成,存放在 <font color=red>" + filename + "</font>");

%>
<fieldset style="height:auto;width: 80%;">
<legend>数据库导出成Excel文件测试</legend>
<table align="center" border="1" width="80%">
<tr align="center">
<td colspan="6">纯JSP页面的分页测试数据</td>
</tr>
<tr align="center">
<td>编号</td>
<td>姓名</td>
<td>密码</td>
<td>年龄</td>
<td>邮箱</td>
<td>地址</td>
</tr>
<%
ResultSet result = statement.executeQuery("SELECT userName,passWord,age,email,address FROM userinfo ORDER BY id DESC");
int j = 1;
while (result.next()) {
// int bil = j + (PageNo-1)*PageSize;
%>
<tr align="center">
<td><%=j %></td>
<td><%=result.getString(1)%></td>
<td><%=result.getString(2) %></td>
<td><%=result.getString(3) %></td>
<td><%=result.getString(4) %></td>
<td><%=result.getString(5) %></td>
</tr>
<%
j++;
}

rs.close();
result.close();
statement.close();
connection.close();
%>
</fieldset>
</center>
</body>
</html>

belong_jars 2011-08-15
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 muzi45ya 的回复:]
execl的导出做过,但是pdf的没有接触过
[/Quote]
能不能给我个导出excel的例子?这个我也得做。
浅碎丨时光 2011-08-15
  • 打赏
  • 举报
回复
execl的导出做过,但是pdf的没有接触过
风尘中国 2011-08-15
  • 打赏
  • 举报
回复
导出PDF的用iText这个组件,楼主可以搜索下
蜗牛@路上 2011-08-15
  • 打赏
  • 举报
回复
我前两天刚做过在后台用jxl导出excel的项目,导出pdf的没做过

81,091

社区成员

发帖
与我相关
我的任务
社区描述
Java Web 开发
社区管理员
  • Web 开发社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧