itext实现导出word

需要的jar包

       iText-2.0.8.jar,itextasian-1.5.2.jar(语言包)

java代码

public void exportWord(String sheetName, String[] headers,String[] columns,JSONArray array, OutputStream out){
		try {    
			//设置纸张大小   
			Document document = new Document(PageSize.A4);   
			//建立一个书写器,与document对象关联   
			RtfWriter2.getInstance(document,out);   
			document.open();   
			//设置中文字体   
			BaseFont bfChinese = BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);   
			//标题字体风格   
			Font titleFont = new Font(bfChinese,12,Font.BOLD);   
			//正文字体风格   
			//Font contextFont = new Font(bfChinese,10,Font.NORMAL);   
			
			Paragraph context = new Paragraph(sheetName);   
			context.setAlignment(Element.ALIGN_CENTER);   
			context.setFont(titleFont);   
			//段间距   
			context.setSpacingBefore(3);   
			//设置第一行空的列数   
			context.setFirstLineIndent(20);   
			document.add(context);   
			//设置Table表格,创建表格   
			Table table = new Table(headers.length);   
			table.setWidth(90);//占页面宽度比例   
			table.setAlignment(Element.ALIGN_CENTER);//居中   
			table.setAlignment(Element.ALIGN_MIDDLE);//垂直居中   
			table.setAutoFillEmptyCells(true);//自动填满   
			table.setBorderWidth(1);//边框宽度   
			//设置表头   
			for(String header : headers){
				Cell haderCell = new Cell(header);   
				haderCell.setHeader(true);   
				table.addCell(haderCell);   
			}
			table.endHeaders();   
			
			for(int i=0;i<array.size();i++){
				JSONObject obj = array.getJSONObject(i);
				for(int j=0;j<columns.length;j++){
					Object o = obj.get(columns[j]);
					String value=null;
					if(o == null || o instanceof JSONNull){
						value="";
					}
					else if(o instanceof JSONObject){
						JSONObject jsonobj = (JSONObject)o;
						Date d = (Date)JSONObject.toBean(jsonobj, Date.class);
						value = DateFormatUtils.format(d, "yyyy-MM-dd hh:mm:ss");
					}else{
						value = obj.getString(columns[j]);
					}
					table.addCell(new Cell(value));
				}
			}
			
			document.add(table);   
			document.close();   
			           
		}catch(Exception e){
			e.printStackTrace();
		}
	}

猜你喜欢

转载自chaojiang.iteye.com/blog/2117429