java IText 导出word表格

之前写的导出表格都是导出成Excel,但是接到的项目新需求要求导出成横表类型的Word文本,据了解,POI对word的导出支持略低,之前用的是自己设置本地模板,然后读取到模板后进行数值的获取补充,但是由于博主接到的需求所有的数据都是动态的,所以不可能画个模板然后读取模板导出,因此找到了对导出表单支持良好的iText进行导出,实验效果绝佳,先参考一篇博客写了个小demo,看到导出的是表格,而且是很easy的表格,所以加上自己需要的数据以及代码逻辑就搞定了.废话不多说,首先来看一个简单的IText导出建议表格demo.
首先说下jar包依赖:

  <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext</artifactId>
            <version>2.1.7</version>
        </dependency>
        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>iTextAsian</artifactId>
            <version>2.1.7</version>
        </dependency>

        <dependency>
            <groupId>com.lowagie</groupId>
            <artifactId>itext-rtf</artifactId>
            <version>2.1.7</version>
        </dependency>

然后是网上的小demo:

package com.rye.test;    
import java.awt.Color;    
import java.io.FileNotFoundException;    
import java.io.FileOutputStream;    
import java.io.IOException;    

import com.lowagie.text.Cell;    
import com.lowagie.text.Document;    
import com.lowagie.text.DocumentException;    
import com.lowagie.text.Font;    
import com.lowagie.text.PageSize;    
import com.lowagie.text.Paragraph;    
import com.lowagie.text.Table;    
import com.lowagie.text.rtf.RtfWriter2;    
/**   
  * 创建word文档 步骤:    
  * 1,建立文档    
  * 2,创建一个书写器    
  * 3,打开文档    
  * 4,向文档中写入数据    
  * 5,关闭文档   
  */   
 public class WordDemo {    

  public WordDemo() {    
  }    

  /**   
   * @param args   
   */   
  public static void main(String[] args) {    
 // 创建word文档,并设置纸张的大小  
   Document document = new Document(PageSize.A4);   
   try {    
    RtfWriter2.getInstance(document,  
 new FileOutputStream("E:/word.doc"));    

    document.open();    

   //设置合同头    

   Paragraph ph = new Paragraph();    
   Font f  = new Font();    

   Paragraph p = new Paragraph("出口合同",   
 new Font(Font.NORMAL, 18, Font.BOLDITALIC, new Color(0, 0, 0)) );    
    p.setAlignment(1);    
    document.add(p);    
    ph.setFont(f);    

    // 设置中文字体    
    // BaseFont bfFont =    
    // BaseFont.createFont("STSongStd-Light",  
 "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);    
    // Font chinaFont = new Font();    
    /*   
     * 创建有三列的表格   
     */   
    Table table = new Table(4);    
    document.add(new Paragraph("生成表格"));    
    table.setBorderWidth(1);    
    table.setBorderColor(Color.BLACK);    
    table.setPadding(0);    
    table.setSpacing(0);    

    /*   
     * 添加表头的元素   
     */   
    Cell cell = new Cell("表头");//单元格    
    cell.setHeader(true);    
    cell.setColspan(3);//设置表格为三列    
    cell.setRowspan(3);//设置表格为三行    
    table.addCell(cell);    
    table.endHeaders();// 表头结束    

    // 表格的主体    
    cell = new Cell("Example cell 2");    
    cell.setRowspan(2);//当前单元格占两行,纵向跨度    
    table.addCell(cell);    
    table.addCell("1,1");    
    table.addCell("1,2");    
    table.addCell("1,3");    
    table.addCell("1,4");    
    table.addCell("1,5");    
    table.addCell(new Paragraph("用java生成的表格1"));    
    table.addCell(new Paragraph("用java生成的表格2"));    
    table.addCell(new Paragraph("用java生成的表格3"));    
    table.addCell(new Paragraph("用java生成的表格4"));    
    document.add(new Paragraph("用java生成word文件"));    
    document.add(table);    
    document.close();    
   } catch (FileNotFoundException e) {    
    e.printStackTrace();    
   } catch (DocumentException e) {    
    e.printStackTrace();    
   } catch (IOException e) {    
    e.printStackTrace();    
   }    
  }    

 }  

来自:http://blog.csdn.net/liuxiao723846/article/details/38613411
下面是博主自己写的:其中的参数String[] ids,是不同人员的id的数组,String[] field是传入的需要导出的人员熟性,那么接下来—-上代码:

public  void createTable(String[] ids,String[] field,HttpServletResponse response,HttpServletRequest request) {
        // 创建word文档,并设置纸张的大小
        Document document;
        if (field.length<20){
            document = new Document(PageSize.A4);
        }else {
            document = new Document(PageSize.A2);
        }

        try {
            Date date = new Date();
         /*   try {
                RtfWriter2.getInstance(document,
                        new FileOutputStream("E:/员工花名册.doc"));
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }*/
            //测试改变路径
            String fileName = "员工花名册"+".doc";
            ServletOutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            RtfWriter2.getInstance(document,
                    output);
            document.open();

            //设置合同头

            Paragraph ph = new Paragraph();
            Font f  = new Font();

            Paragraph p = new Paragraph("员工基本信息",
                    new Font(Font.NORMAL, 18, Font.BOLD, new Color(0, 0, 0)) );
            p.setAlignment(1);
            try {
                document.add(p);
            } catch (DocumentException e) {
                e.printStackTrace();
            }
            ph.setFont(f);

            // 设置中文字体
            // BaseFont bfFont =
            // BaseFont.createFont("STSongStd-Light",
            //"UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // Font chinaFont = new Font();
    /*
     * 创建有三列的表格
     */
            Table table = new Table(field.length);
            //table.setWidth((field.length-1)*2);
            /*document.add(new Paragraph("员工信息"));*/
            table.setBorderWidth(1);
            table.setBorderColor(Color.BLACK);
            table.setPadding(0);
            table.setSpacing(0);


            //准备数据
            List<PersonInfoEntity> personInfoEntityList = new ArrayList<>();
            //Arrays.sort(charArray);
            Map<String,Object> map = new HashMap<>();
            for(int h = 0 ; h<ids.length;h++){
                map.put("id", ids[ids.length-h-1]);
                PersonInfoEntity personInfoEntity = personInfoService.selectByMap(map);
                personInfoEntityList.add(personInfoEntity);
            }
            for (int b = 0;b<=personInfoEntityList.size();b++){
              /*  可以自定义table的列宽
              Table table2 = new Table(field.length-1);
                table2.setWidth((field.length-1)*2);
                添加图片信息
            *//*document.add(new Paragraph("员工信息"));*//*
                table2.setBorderWidth(1);
                table2.setBorderColor(Color.BLACK);
                table2.setPadding(0);
                table2.setSpacing(0);*/
                    //设置第一行,也就是表头,不涉及行合并列合并,具体的行合并列合并也可以使用rowSpan之类的进行实现
                if (b==0){
                    for (int a =0;a<field.length;a++){
                        //table.addCell(field[a]);
                        if (field[a].equals("fullName")||field[a]=="fullName"){
                            table.addCell("姓名");
                        }else if (field[a].equals("beforeName")||field[a]=="beforeName"){
                            table.addCell("曾用名");
                        }else if (field[a].equals("idNumber")||field[a]=="idNumber"){
                            table.addCell("身份证号");
                        }else if (field[a].equals("birthplace")||field[a]=="birthplace"){
                            table.addCell("生日");
                        }else if (field[a].equals("age")||field[a]=="age"){
                            table.addCell("年龄");
                        }else if (field[a].equals("jobNo")||field[a]=="jobNo"){
                            table.addCell("工号");
                        }else if (field[a].equals("deptId")||field[a]=="deptId"){
                            table.addCell("部门");
                        }else if (field[a].equals("nation")||field[a]=="nation"){
                            table.addCell("民族");
                        }else{
                        //由于条目过多:50个字段,所以此处进行省略
                            table.addCell("暂无title");
                        }
                    }
                }
                else {
        //设置接下来的数据,也就是真实的人员信息数据           
                            for (int a = 0;a<field.length;a++){
                                //row1.setRowStyle(style);
                                if (field[a].equals("fullName")||field[a]=="fullName"){
                                    table.addCell(personInfoEntityList.get(b-1).getFullName());
                                }else if (field[a].equals("beforeName")||field[a]=="beforeName"){
                                    table.addCell(personInfoEntityList.get(b-1).getBeforeName()==null?"":personInfoEntityList.get(b-1).getBeforeName());
                                }else if (field[a].equals("idNumber")||field[a]=="idNumber"){
                                    table.addCell(personInfoEntityList.get(b-1).getIdNumber()==null?"":personInfoEntityList.get(b-1).getIdNumber());
                                }else if (field[a].equals("birthplace")||field[a]=="birthplace"){
                                    table.addCell(personInfoEntityList.get(b-1).getBirthday()==null?"":personInfoEntityList.get(b-1).getBirthday());
                                }else if (field[a].equals("age")||field[a]=="age"){
                                    String age = "";
                                    if (personInfoEntityList.get(b-1).getAge()!=null){
                                        age = personInfoEntityList.get(b-1).getAge().toString();
                                    }
                                    table.addCell(age);
                                }else if (field[a].equals("jobNo")||field[a]=="jobNo"){
                                    table.addCell(personInfoEntityList.get(b-1).getJobNo()==null?"":personInfoEntityList.get(b-1).getJobNo());
                                }else if (field[a].equals("deptId")||field[a]=="deptId"){
                                    String deptName = "";
             ...
                                    table.addCell(deptName);
                                }else if (field[a].equals("nation")||field[a]=="nation"){
                                    //枚举
                                    String nationName = "";
                                    if (personInfoEntityList.get(b-1).getNation()!=null&&personInfoEntityList.get(b-1).getNation()!=""){
                                        nationName = NationEnum.getName(Integer.parseInt(personInfoEntityList.get(b-1).getNation()));
                                    }
                                    table.addCell(nationName);
                               }else{
                        //由于条目过多:50个字段,所以此处进行省略
                            table.addCell("暂无title");
                        }
                            }

                    }
                }

           /* document.add(new Paragraph("用java生成word文件"));
            document.add(new Paragraph("这是我自己添加的一行,我最后要的是动态的"));*/
            document.add(table);
            document.close();
        } catch (DocumentException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

值得一提的是:

String fileName = "员工花名册"+".doc";
            ServletOutputStream output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            RtfWriter2.getInstance(document,
                    output);
            document.open();

RtfWriter2.getInstance(document,
output);getInstance中的流可以是fileOutPutstream也可以是ServletOurPutPtream,开始时想着可不可以转换下,未果,所以看下源码:

 public static RtfWriter2 getInstance(Document var0, OutputStream var1) {
        return new RtfWriter2(var0, var1);
    }

发现想着转换着实可笑,也是跳进demo的框子里了.

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值