`
keep_going
  • 浏览: 11643 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

使用ITEXT导出PDF、WORD,APACHE POI导出EXCEL报表文件

阅读更多
    描述:
最近在项目开发中,需要导出对账单报表信息为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包   

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics