美文网首页
java 批量生成word 文件

java 批量生成word 文件

作者: cat昵称居然被占用了 | 来源:发表于2017-01-09 20:26 被阅读428次

最近在工作中遇到一个需求,我有一个拥有3000行数据的excel文件和一个word模板。

我需要将excel文件中的每一行数据填充到word模板文件中生成一个Word文件。

考虑到数据量较大且需求有可能重复,所以我干脆花时间写了个程序来解决这个问题。

读取Excel文件的数据

首先我需要读取Excel文件的数据。代码如下:

public static List<Map> readTable() throws Exception {
        Map map = new HashMap<String, String>();
        List<Map> list = new ArrayList<Map>();
        InputStream ips = new FileInputStream("/Users/rar/Documents/123.xlsx");
        XSSFWorkbook wb = new XSSFWorkbook(ips);
        Sheet sheet1 = wb.getSheetAt(0);
        for (Row row : sheet1) {
            String name = row.getCell(0).getStringCellValue();
            String phoneNumber = row.getCell(2).getStringCellValue();
            String account = row.getCell(4).getStringCellValue();

            Map dataMap = new HashMap();
            dataMap.put("name", name);
            dataMap.put("account", idCard);
            dataMap.put("phoneNUmber", phoneNumber);
            list.add(dataMap);
        }
        return list;
    }
    

如果你需要判断单元格中数据的类型,可在迭代中加入如下代码:

        for (Cell cell : row) {
                switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_BOOLEAN:
                        //得到Boolean对象的方法
                        cell.getBooleanCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_NUMERIC:
                        //先看是否是日期格式
                        if(HSSFDateUtil.isCellDateFormatted(cell)){
                            //读取日期格式
                            cell.getDateCellValue();
                        }else{
                            //读取数字
                            cell.getNumericCellValue();
                        }
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA:
                        //读取公式
                        cell.getCellFormula();
                        break;
                    case HSSFCell.CELL_TYPE_STRING:
                        //读取String
                        cell.getRichStringCellValue();
                        break;
                    default:
                }

        }

写入到Word文件中

将数据填充到Word文件中,我使用了freemarker。需要将模板文件中需要填充的字段,使用${}代替,比如我需要在文件开头填入姓名,那么我就在文件开头写${name}。然后将文件导出成xml文件。这个xml文件就是程序需要的模板文件。

代码如下:

        //加载模板文件
        public Template getTemplate() throws IOException {
            configuration.setDirectoryForTemplateLoading(new File("/Users/rar/Documents"));
            Template t = null;
            try {
                // data.xml为要装载的模板
                t = configuration.getTemplate("data.xml");
                t.setEncoding("utf-8");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return t;
        }
        //wordName为word文件名
        public Writer getWriter(String wordName){
            String savePath = "/Users/rar/Documents/";
            File file = new File(savePath+"upload");
            if(!file.exists()){
                file.mkdirs();
            }
            File outFile = new File(savePath+"upload/"+wordName+".doc");
            Writer out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(outFile), "utf-8"));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
            return out;
        }

        //创建 并写入数据到word文件
        public void createDoc(Template t,Map dataMap,Writer out) {
            try {
                t.process(dataMap, out);
                out.close();
            } catch (TemplateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
public class excelToWord {
    public static  void main(String[] args) throws Exception {
        personnelImportWord();
    }



    private static void personnelImportWord() throws Exception{
        DocumentHandler dh = new DocumentHandler();
        Template t = dh.getTemplate();

        List<Map> list=ReadExcelTable.readTable();
        for (Map map : list){
            Writer out = dh.getWriter((String)map.get("name"));
            dh.createDoc(t,map, out);
        }

    }
}

pom文件如下:

<dependencies>   
 <dependency>       
    <groupId>org.freemarker</groupId>   
    <artifactId>freemarker</artifactId>    
    <version>2.3.22</version>  
  </dependency>  
  <dependency>    
     <groupId>org.apache.poi</groupId>  
     <artifactId>poi</artifactId>   
     <version>3.14</version> 
   </dependency> 
   <dependency>    
    <groupId>org.apache.poi</groupId>   
     <artifactId>poi-ooxml</artifactId>    
    <version>3.13</version>  
   </dependency>
</dependencies>

程序成功运行:

1.png

github:https://github.com/erwincat/toWord

相关文章

网友评论

      本文标题:java 批量生成word 文件

      本文链接:https://www.haomeiwen.com/subject/osphbttx.html