描述:
最近在项目开发中,需要导出对账单报表信息为PDF、WORD和EXCEL,经过资料收集导出文件的实现方式很多,也有许多可使用的开源jar包。经选择,使用IText导出PDF和Word、POI导出excel比较实用,且功能强大,能满足需求。下面将代码和jar包分享出来,希望对大家有帮助:
package com.szkingdom.kfit.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfPageEventHelper;
import com.lowagie.text.pdf.PdfTemplate;
import com.lowagie.text.pdf.PdfWriter;
/**
* iText输出文档为PDF格式的工具类
* @author yanq
*
*/
public class ExportPdfUtil {
private static final String PRAMATER_PATH = "/report.properties"; //配置文件路径
private static final String PAGECLASS_PATH = "com.lowagie.text.PageSize"; //默认的类路径
private static final String FORMAT_STR = "yyyy-MM-dd HH:mm:ss";
private static ExportPdfUtil printUtil = null;
private static Properties prop = null;
private static SimpleDateFormat format = new SimpleDateFormat(FORMAT_STR);
private ExportPdfUtil() {
}
/**
* 提供外部访问接口
* @return
*/
public static ExportPdfUtil newInstance() {
if(prop == null) {
try {
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(PRAMATER_PATH);
//InputStream in = Thread.currentThread().getClass().getResourceAsStream(PRAMATER_PATH);
prop = new Properties();
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
if(printUtil == null) {
printUtil = new ExportPdfUtil();
}
return printUtil;
}
/**
* 导出PDF报表
* @param param 配置参数
* @param titleMap 报表标题属性
* @param result 报表数据
* @param out 输出流
* @throws Exception
*/
public void exportPdfReport(Map<String, Object> param, LinkedHashMap<String, String> titleMap,
List<Map<String, Object>> result, OutputStream out) throws Exception {
Document document = createDocument();
PdfWriter writer = PdfWriter.getInstance(document, out);
PDFMaker event = new PDFMaker();
writer.setPageEvent(event);
document.open();
if("TRUE".equals(prop.getProperty("IS_SHOWTITLE"))) {
PdfPTable titleTable = new PdfPTable(1);
titleTable.setWidthPercentage(16 * titleMap.size());
titleTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
Font titleFont = getChineseFont(12, Font.BOLD);
PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(param.get("title")), titleFont));
cell.setBorderWidthTop(0.5f);
cell.setBorderWidthLeft(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthBottom(0);
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
titleTable.addCell(cell);
Font dateFont = getChineseFont(10, Font.NORMAL);
Date date = param.get("systemDate") == null ? new Date() : (Date)param.get("systemDate");
cell = new PdfPCell(new Phrase("系统日期:" + format.format(date), dateFont));
cell.setBorderWidthTop(0);
cell.setBorderWidthLeft(0);
cell.setBorderWidthRight(0);
cell.setBorderWidthBottom(0.5f);
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
titleTable.addCell(cell);
document.add(titleTable);
}
PdfPTable table = initReportTableData(titleMap, result);
document.add(table);
document.close();
}
/**
* 初始化Table报表数据
* @param titleMap
* @param result
* @return
*/
private PdfPTable initReportTableData(LinkedHashMap<String, String> titleMap, List<Map<String, Object>> result) {
Font font10B = getChineseFont(10, Font.BOLD);
Font font10 = getChineseFont(10, Font.NORMAL);
PdfPTable table = new PdfPTable(titleMap.size());
table.setSpacingBefore(5);
if("TRUE".equals(prop.getProperty("IS_TITLEHEAD"))) {
table.setHeaderRows(1);
}
table.setWidthPercentage(16 * titleMap.size());
table.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
for(String key : titleMap.keySet()) {
PdfPCell cell = new PdfPCell(new Phrase(titleMap.get(key), font10B));
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cell);
}
table.setHeaderRows(1);
for(int i = 0, iSize = result.size(); i < iSize; i ++) {
Map<String, Object> map = result.get(i);
for(String key : titleMap.keySet()) {
PdfPCell cell = new PdfPCell(new Phrase(String.valueOf(map.get(key)), font10));
cell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
table.addCell(cell);
}
}
return table;
}
/**
* 创建Document文档
* @return
*/
private Document createDocument() {
Document document = null;
Rectangle rectangle = PageSize.A4;
boolean isSelfDefineSize = ("TRUE".equals(prop.getProperty("SELFDEFINE_SIZE")));
if(isSelfDefineSize) {
float iWidth = Float.parseFloat(prop.getProperty("DEFINE_WIDTH"));
float height = Float.parseFloat(prop.getProperty("DEFINE_HEIGHT"));
rectangle = new Rectangle(iWidth, height);
} else {
String pageSize = prop.getProperty("PAGE_SIZE");
rectangle = (Rectangle) getAttributeValue(PAGECLASS_PATH, pageSize);
}
float fTop = Float.parseFloat(prop.getProperty("MARGIN_TOP"));
float fBottom = Float.parseFloat(prop.getProperty("MARGIN_BOTTOM"));
float fLeft = Float.parseFloat(prop.getProperty("MARGIN_LEFT"));
float fRight = Float.parseFloat(prop.getProperty("MARGIN_RIGHT"));
if(fTop != 0 || fBottom != 0 || fLeft != 0 || fRight != 0) {
document = new Document(rectangle, fLeft, fRight, fTop, fBottom);
} else {
document = new Document(rectangle);
}
return document;
}
/**
* 显示处理水印
* @param document
*/
public void showWatermark(Document document) {
if("TRUE".equals(prop.getProperty("IS_WATERMARK"))) {
}
}
/**
* 处理字体
* @param fontSize 大小
* @param fontStyle 样式
* @return
*/
private Font getChineseFont(int fontSize, int fontStyle) {
Font chineseFont = null;
try {
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
chineseFont = new Font(bfChinese, fontSize, fontStyle);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return chineseFont;
}
/**
* 利用反射在指定的类中查找指定属性的值
* @param classPath 类路径
* @param attrName 属性名
* @return 查找的值
*/
private Object getAttributeValue(String classPath, String attrName) {
Object obj = null;
try {
Class<?> cls = Class.forName(classPath);
Field fieldList[] = cls.getDeclaredFields();
for(int i = 0, iSize = fieldList.length; i < iSize; i ++) {
Field field = fieldList[i];
String filedName = field.getName();
if(attrName != null && attrName.equals(filedName)) {
obj = field.get(cls);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
public static void main(String[] args) throws Exception {
LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>();
titleMap.put("id", "用户ID");
titleMap.put("username", "用户名");
titleMap.put("age", "年龄");
titleMap.put("sex", "性别");
titleMap.put("brithday", "出生日期");
titleMap.put("interest", "爱好");
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
for(int i = 0; i < 100; i ++) {
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", 1000+i+1);
map.put("username", 张三");
map.put("age", "24");
map.put("sex", "男");
map.put("brithday", "1988-07-12");
map.put("interest", "看书");
list.add(map);
}
FileOutputStream out = new FileOutputStream("report.pdf");
ExportPdfUtil.newInstance().exportPdfReport(null, titleMap, list, out);
}
}
class PDFMaker extends PdfPageEventHelper {
// PDF模板类
public PdfTemplate tpl;
// 页码字体
public BaseFont helv;
public void onCloseDocument(PdfWriter writer, Document document) {
super.onCloseDocument(writer, document);
tpl.beginText();
tpl.setFontAndSize(helv, 8);
tpl.showText("共" + (writer.getPageNumber() - 1) + "页");
tpl.endText();
tpl.closePath();
}
public void onEndPage(PdfWriter writer, Document document) {
super.onEndPage(writer, document);
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
String text = "第" + writer.getPageNumber() + "页 /";
cb.beginText();
cb.setFontAndSize(helv, 8);
float textWidth = document.getPageSize().getWidth() / 2 - (helv.getWidthPoint(text, 8) + tpl.getWidth()) / 2 + document.left();
cb.setTextMatrix(textWidth, document.bottom() - 10);
cb.showText(text);
cb.endText();
cb.addTemplate(tpl, textWidth + helv.getWidthPoint(text, 8) + 2, document.bottom() - 10);
cb.restoreState();
cb.closePath();
}
public void onOpenDocument(PdfWriter writer, Document document) {
super.onOpenDocument(writer, document);
try {
tpl = writer.getDirectContent().createTemplate(100, 100);
helv = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
} catch (Exception e) {
e.printStackTrace();
}
}
}
package com.szkingdom.kfit.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ExportExcelUtil { private static ExportExcelUtil export = null; private ExportExcelUtil() {} public static ExportExcelUtil newInstance() { if(export == null) { export = new ExportExcelUtil(); } return export; } /** * 导出Excel文档 * @throws FileNotFoundException */ public void exportExcelDocument(Map<String, Object> param, LinkedHashMap<String, String> titleMap, List<Map<String, Object>> result, OutputStream out) throws Exception { Workbook workbook = new HSSFWorkbook(); Sheet sheet = workbook.createSheet(param.get("title") == null ? "未命名" : String.valueOf(param.get("title"))); sheet.setDisplayGridlines(true); Row row = sheet.createRow(0); CellStyle titleStyle = workbook.createCellStyle(); titleStyle.setAlignment(CellStyle.ALIGN_CENTER); titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); Font titleFont = workbook.createFont(); titleFont.setFontName("Arial"); titleFont.setFontHeightInPoints((short)12); titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD); titleStyle.setFont(titleFont); int count = 0; for(String key : titleMap.keySet()) { Cell cell = row.createCell(count); cell.setCellStyle(titleStyle); cell.setCellValue(titleMap.get(key)); count ++; } for(int i = 0, iSize = result.size(); i < iSize; i ++) { Map<String, Object> resultMap = result.get(i); Font contentFont = workbook.createFont(); titleFont.setFontName("Arial"); contentFont.setFontHeightInPoints((short)10); titleFont.setBoldweight(Font.BOLDWEIGHT_NORMAL); CellStyle contentStyle = workbook.createCellStyle(); contentStyle.setAlignment(CellStyle.ALIGN_CENTER); contentStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER); row = sheet.createRow(i + 1); contentStyle.setFont(contentFont); count = 0; for(String key : titleMap.keySet()) { Cell cell = row.createCell(count); cell.setCellStyle(contentStyle); cell.setCellValue(String.valueOf(resultMap.get(key))); count ++; } } workbook.write(out); out.flush(); out.close(); } public static void main(String[] args) throws Exception { LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>(); titleMap.put("id", "用户ID"); titleMap.put("username", "用户名"); titleMap.put("age", "年龄"); titleMap.put("sex", "性别"); titleMap.put("brithday", "出生日期"); titleMap.put("interest", "爱好"); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); for(int i = 0; i < 100; i ++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", 1000+i+1); map.put("username,"张三"); map.put("age", "24"); map.put("sex", "男"); map.put("brithday", "1988-07-12"); map.put("interest", "看书"); list.add(map); } FileOutputStream out = new FileOutputStream("myExcel.xls"); ExportExcelUtil.newInstance().exportExcelDocument(null, titleMap, list, out); } }
package com.szkingdom.kfit.util; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Properties; import com.lowagie.text.Cell; import com.lowagie.text.Document; import com.lowagie.text.DocumentException; import com.lowagie.text.Element; import com.lowagie.text.Font; import com.lowagie.text.HeaderFooter; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.Phrase; import com.lowagie.text.Rectangle; import com.lowagie.text.Table; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.rtf.RtfWriter2; import com.lowagie.text.rtf.field.RtfPageNumber; import com.lowagie.text.rtf.field.RtfTotalPageNumber; import com.lowagie.text.rtf.headerfooter.RtfHeaderFooter; /** * 报表导出成多样式工具类 * @author yanq * */ public class ExportWordUtil { private static final String PRAMATER_PATH = "/report.properties"; //配置文件路径 private static final String PAGECLASS_PATH = "com.lowagie.text.PageSize"; //默认的类路径 private static final String FORMAT_STR = "yyyy-MM-dd HH:mm:ss"; private static ExportWordUtil export = null; private static Properties prop = null; private static SimpleDateFormat format = new SimpleDateFormat(FORMAT_STR); private ExportWordUtil() {} public static ExportWordUtil newInstance() { if(prop == null) { try { //InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(PRAMATER_PATH); InputStream in = Thread.currentThread().getClass().getResourceAsStream(PRAMATER_PATH); prop = new Properties(); prop.load(in); } catch (IOException e) { e.printStackTrace(); } } if(export == null) { export = new ExportWordUtil(); } return export; } /** * 导出Word文档 * @throws FileNotFoundException */ public void exportWordDocument(Map<String, Object> param, LinkedHashMap<String, String> titleMap, List<Map<String, Object>> result, OutputStream out) throws Exception { Document document = createDocument(); RtfWriter2.getInstance(document, out); document.open(); if("TRUE".equals(prop.getProperty("IS_SHOWTITLE"))) { Table titleTable = new Table(1); titleTable.setWidth(16 * titleMap.size()); titleTable.setAlignment(Element.ALIGN_CENTER); titleTable.setAlignment(Element.ALIGN_MIDDLE); titleTable.setAutoFillEmptyCells(true); Font titleFont = getChineseFont(12, Font.BOLD); Cell cell = new Cell(new Phrase(String.valueOf(param.get("title")), titleFont)); cell.setBorderWidthTop(0.5f); cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0); cell.setBorderWidthBottom(0); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_CENTER); titleTable.addCell(cell); Font dateFont = getChineseFont(10, Font.NORMAL); Date date = param.get("systemDate") == null ? new Date() : (Date)param.get("systemDate"); cell = new Cell(new Phrase("系统日期:" + format.format(date), dateFont)); cell.setBorderWidthTop(0); cell.setBorderWidthLeft(0); cell.setBorderWidthRight(0); cell.setBorderWidthBottom(0.5f); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); titleTable.addCell(cell); document.add(titleTable); } Table table = initReportTableData(titleMap, result); document.add(table); if("TRUE".equals(prop.getProperty("IS_PAGECOUNT"))) { Paragraph paraFooter = new Paragraph(); paraFooter.add(new Phrase("第", getChineseFont(8, Font.NORMAL))); paraFooter.add(new RtfPageNumber()); paraFooter.add(new Phrase("页/共", getChineseFont(8, Font.NORMAL))); paraFooter.add(new RtfTotalPageNumber()); paraFooter.add(new Phrase("页", getChineseFont(8, Font.NORMAL))); paraFooter.setAlignment(1); HeaderFooter footer = new RtfHeaderFooter(paraFooter); footer.setAlignment(HeaderFooter.ALIGN_CENTER); footer.setBorder(Rectangle.NO_BORDER); document.setFooter(footer); } document.close(); } /** * 初始化Table报表数据 * @param titleMap * @param result * @return * @throws Exception */ private Table initReportTableData(LinkedHashMap<String, String> titleMap, List<Map<String, Object>> result) throws Exception { Font font10B = getChineseFont(10, Font.BOLD); Font font10 = getChineseFont(10, Font.NORMAL); Table table = new Table(titleMap.size()); table.setWidth(16 * titleMap.size()); table.setAlignment(Element.ALIGN_CENTER); table.setAlignment(Element.ALIGN_MIDDLE); for(String key : titleMap.keySet()) { Cell cell = new Cell(new Phrase(titleMap.get(key), font10B)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); } for(int i = 0, iSize = result.size(); i < iSize; i ++) { Map<String, Object> map = result.get(i); for(String key : titleMap.keySet()) { Cell cell = new Cell(new Phrase(String.valueOf(map.get(key)), font10)); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); } } return table; } /** * 处理字体 * @param fontSize 大小 * @param fontStyle 样式 * @return */ private Font getChineseFont(int fontSize, int fontStyle) { Font chineseFont = null; try { BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); chineseFont = new Font(bfChinese, fontSize, fontStyle); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return chineseFont; } /** * 创建Document文档 * @return */ private Document createDocument() { Document document = null; Rectangle rectangle = PageSize.A4; boolean isSelfDefineSize = ("TRUE".equals(prop.getProperty("SELFDEFINE_SIZE"))); if(isSelfDefineSize) { float iWidth = Float.parseFloat(prop.getProperty("DEFINE_WIDTH")); float height = Float.parseFloat(prop.getProperty("DEFINE_HEIGHT")); rectangle = new Rectangle(iWidth, height); } else { String pageSize = prop.getProperty("PAGE_SIZE"); rectangle = (Rectangle) getAttributeValue(PAGECLASS_PATH, pageSize); } float fTop = Float.parseFloat(prop.getProperty("MARGIN_TOP")); float fBottom = Float.parseFloat(prop.getProperty("MARGIN_BOTTOM")); float fLeft = Float.parseFloat(prop.getProperty("MARGIN_LEFT")); float fRight = Float.parseFloat(prop.getProperty("MARGIN_RIGHT")); if(fTop != 0 || fBottom != 0 || fLeft != 0 || fRight != 0) { document = new Document(rectangle, fLeft, fRight, fTop, fBottom); } else { document = new Document(rectangle); } return document; } /** * 利用反射在指定的类中查找指定属性的值 * @param classPath 类路径 * @param attrName 属性名 * @return 查找的值 */ private Object getAttributeValue(String classPath, String attrName) { Object obj = null; try { Class<?> cls = Class.forName(classPath); Field fieldList[] = cls.getDeclaredFields(); for(int i = 0, iSize = fieldList.length; i < iSize; i ++) { Field field = fieldList[i]; String filedName = field.getName(); if(attrName != null && attrName.equals(filedName)) { obj = field.get(cls); break; } } } catch (Exception e) { e.printStackTrace(); } return obj; } public static void main(String[] args) throws Exception { Map<String, Object> param = new HashMap<String, Object>(); param.put("title", "用户信息列表"); param.put("systemDate", new Date()); LinkedHashMap<String, String> titleMap = new LinkedHashMap<String, String>(); titleMap.put("id", "用户ID"); titleMap.put("username", "用户名"); titleMap.put("age", "年龄"); titleMap.put("sex", "性别"); titleMap.put("brithday", "出生日期"); titleMap.put("interest", "爱好"); List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); for(int i = 0; i < 100; i ++) { Map<String, Object> map = new HashMap<String, Object>(); map.put("id", 1000+i+1); map.put("username", "李四"); map.put("age", "24"); map.put("sex", "男"); map.put("brithday", "1988-07-12"); map.put("interest", "看书"); list.add(map); } FileOutputStream out = new FileOutputStream("myWord.doc"); ExportWordUtil.newInstance().exportWordDocument(param, titleMap, list, out); } }
#标识说明:none:非空属性, select:可选属性 # SELFDEFINE_SIZE为FALSE,该属性none 打印页面大小,A0-A10,_11X17,ARCH_A-ARCH_E,B0-B10,默认值A4 PAGE_SIZE=A4 #自定义子张大小,设置为TRUE,默认为FALSE,none SELFDEFINE_SIZE=FALSE #当SELFDEFINE_SIZE=TRUE,宽度none DEFINE_WIDTH=400 #当SELFDEFINE_SIZE=TRUE,高度none DEFINE_HEIGHT=400 #页面边距-上边距 none MARGIN_TOP=0 #页面边距-下边距 none MARGIN_BOTTOM=0 #页面边距-左边距 none MARGIN_LEFT=0 #页面边距-右边距 none MARGIN_RIGHT=0 #是否显示水银,默认TRUE,NONE IS_WATERMARK=TRUE #水银图片地址,none WATERMARK_PATH=watermark.jpg #显示方式,每页显示:ANY,首页显示:FIRST WATERMARK_TYPE=ANY #是否显示页数,默认TRUE,none IS_PAGECOUNT=TRUE #是否每页显示标题表头,none IS_TITLEHEAD=TRUE #是否显示标题,none IS_SHOWTITLE=TRUE
if("pdf".equals(this.getRequest().getParameter("export"))) { this.getResponse().setContentType("application/x-msdownload;charset=UTF-8"); this.getResponse().setHeader("Content-Disposition","attachment;filename=report.pdf"); out = this.getResponse().getOutputStream(); ExportPdfUtil.newInstance().exportPdfReport(param, titleMap, list, out); } else if("word".equals(this.getRequest().getParameter("export"))) { this.getResponse().setContentType("application/x-msdownload;charset=UTF-8"); this.getResponse().setHeader("Content-Disposition","attachment;filename=report.doc"); out = this.getResponse().getOutputStream(); ExportWordUtil.newInstance().exportWordDocument(param, titleMap, list, out); } else if("excel".equals(this.getRequest().getParameter("export"))) { this.getResponse().setContentType("application/x-msdownload;charset=UTF-8"); this.getResponse().setHeader("Content-Disposition","attachment;filename=report.xls"); out = this.getResponse().getOutputStream(); ExportExcelUtil.newInstance().exportExcelDocument(param, titleMap, list, out); }
附件为代码、配置文件及所需的jar包
相关推荐
在IT行业中,转换数据格式是常见的任务之一,例如将Excel表格转换为PDF文档。...总之,通过Apache POI和iText,开发者可以轻松地在Java环境中实现Excel到PDF的转换,满足不同场景下的数据展示需求。
总结来说,使用ITEXT导出Excel虽然不是其主要功能,但通过创建模拟Excel结构的PDF文档并转换,可以实现这一目标。不过,这种方式可能不如直接使用Apache POI等专门的Excel处理库那么高效和灵活。在实际开发中,应...
虽然IText的主要功能是处理PDF,但它也可以通过使用Apache POI库或iTextAspose库生成Word(.doc或.docx)文件。由于IText自身并不直接支持Word格式,这里我们以使用Apache POI为例: ```java import org.apache.poi...
2. **读取Excel**:使用Apache POI等库读取Excel文件,获取其内容和样式信息。 3. **创建PDF文档**:初始化一个Document对象,设置页边距和大小,准备写入PDF内容。 4. **转换表格**:遍历Excel的工作表,将每个...
同样,导出Excel功能可以通过创建一个新的工作簿,填充数据,然后设置样式和写入输出流来实现。以下是一个简单的导出示例: ```java @GetMapping("exportList") public void exportList(HttpServletResponse ...
对于复杂的Word格式,可能需要使用其他的库,如Apache POI。然而,对于简单的文本输出和基本的格式控制,iText已经足够满足需求。 在实际项目中,你可能会遇到一些问题,比如编码问题、样式控制、特殊字符处理等。...
标题提到的"Java通过IText导出word和pdf所有jar",意味着这个压缩包可能包含了一系列必要的Java库,这些库用于通过IText库导出PDF以及可能通过其他库(如Apache POI)导出Word文档。"包括spring相关jar"表明这个包还...
这通常涉及到先使用iText生成PDF,然后再用第三方工具(如Apache POI)将PDF转换为Word。然而,这种方法可能无法完全保留PDF的所有格式和特性。 **中文字体支持** 在处理中文文档时,iText需要额外的字体资源来...
在IT行业中,Apache POI是一个广泛使用的库,主要用于读写Microsoft Office格式的文件,如Word、Excel和PowerPoint。本文将深入探讨如何利用Apache POI框架根据模板生成Word文档,并进一步将其转换为PDF文件。 首先...
标题中的“使用iText方式导出...总之,使用iText导出Word文档涉及多个步骤,包括设置文档结构、添加内容、选择合适的Writer以及正确处理文件流。熟练掌握这些知识点后,你就能灵活地在Java项目中创建和导出Word文档了。
本文将详细介绍如何使用Apache POI库处理Excel数据,以及使用iText库将这些数据导出为PDF格式。Apache POI是Java中处理Microsoft Office格式文件(如Excel)的库,而iText则是用于创建和编辑PDF文档的库。 首先,...
然而,直接用Itext导出Word文档并不直接支持,所以我们需要用到额外的库。 `iTextAsian.jar`是Itext的一个扩展,特别针对亚洲语言的支持,如中文、日文和韩文。如果你的文档包含这些语言的文本,这个库就非常必要,...
在本示例中,可能还使用了Apache POI库,它是Java处理Microsoft Office格式(如Excel)的工具。POI可以帮助开发者读取Excel数据,将其转换为适合插入PDF的格式,或者根据用户输入的数据动态生成Excel文件。这通常...
在 JSP 中导出 PDF 和 Excel JSP(Java Server Pages)是一种服务器端技术,用于生成动态网页。近年来,随着企业信息化的发展,报表生成和...使用 iText 可以生成 PDF 文件,而使用 Apache POI 可以生成 Excel 文件。
Apache POI是一个流行的库,主要用于处理Microsoft Office格式的文件,如Word(.doc/.docx)和Excel(.xls/.xlsx)。在这个场景中,我们将探讨如何使用Apache POI结合其他工具库来实现Word到PDF的转换。 首先,...
在Java编程中,导出Excel、Word和PDF是常见的数据呈现和报告生成需求。这些文件格式广泛用于数据存储、报表生成、文档分享等场景。以下将详细介绍如何使用Java实现这三种文件类型的导出。 首先,让我们关注Excel的...
Apache POI是一个流行的开源Java API,主要用于读取和写入Microsoft Office格式的文件,如Word(.doc, .docx)、Excel(.xls, .xlsx)等。这里提到的“生成pdf等”,意味着除了PDF之外,可能还包括了HTML、图片或...
在描述中提到的"POI导出.pdf,.doc,.xls,.jpg四种格式通用组件",意味着该组件不仅限于处理Microsoft Office文档,还支持生成PDF和图像文件(如.jpg),实现了多种文件格式间的转换和导出。 1. **Apache POI 概述**...
例如,你可以先使用数据库查询获取数据,然后利用Apache POI或JExcelApi生成Excel报表,接着使用iText将数据转化为PDF或Word格式,便于分发和打印。这些工具和库是IT专业人员日常工作中不可或缺的部分,它们极大地...