POI使用

练习目标:
通过将excel作为数据源,动态将excel中的数据填入word模板中
具体操作如下

  private ThreadLocal<ArrayList<String>> contentTL = new ThreadLocal<ArrayList<String>>();
 public void handleFileInfo() throws Exception {
        List<Map<String, Map<String, String>>> excelConfig = getExcelConfig();
        Map<String, String> regexMap = new HashMap<String, String>();

        try {
            String filePath = "E:" + File.separator + "活动轨迹.docx";

            for (int i = 0; i < excelConfig.size(); i++) {
                Map<String, Map<String, String>> map = excelConfig.get(i);
                Set<Map.Entry<String, Map<String, String>>> entries = map.entrySet();
                Iterator<Map.Entry<String, Map<String, String>>> iterator = entries.iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, Map<String, String>> next = iterator.next();
                    Map<String, String> valueMap = next.getValue();
                    for (int j = 0; j < contentTL.get().size(); j++) {
                        regexMap.put(contentTL.get().get(j), valueMap.get(contentTL.get().get(j)));
                    }
                }
                String filePathCopy = "E:" + File.separator + "活动轨迹" + i + ".docx";

                replaceAndGenerateWord(filePath,
                        filePathCopy, regexMap);
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {

        }


    }

  /*
     * 获取excel中的配置
     * */
    public List<Map<String, Map<String, String>>> getExcelConfig() {
        String filePath = "E:" + File.separator + "表.xlsx";
//        keys.clear();
//        ArrayList<Area> list = new ArrayList<>();
        contentTL.set(new ArrayList<>());
        ArrayList<Map<String, Map<String, String>>> list = new ArrayList<>();
        try {
            //1、获取文件输入流
            InputStream inputStream = new FileInputStream(filePath);
            //2、获取Excel工作簿对象
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            //3、得到Excel工作表对象
            XSSFSheet sheetAt = workbook.getSheetAt(0);


            //4、循环读取表格数据
            for (Row row : sheetAt) {
                int sumCOunt = row.getPhysicalNumberOfCells(); // 总列数
                //首行(即表头)不读取
                if (row.getRowNum() == 0) {
                    for (int i = 0; i < sumCOunt; i++) {
                        contentTL.get().add(row.getCell(i).getStringCellValue());
                    }
                    continue;
                }

                HashMap<String, String> map = new HashMap<>();
                HashMap<String, Map<String, String>> rowmap = new HashMap<>();
                for (int j = 0; j < contentTL.get().size(); j++) {
                    if (null != row) {
                        Cell cell = row.getCell(j);
                        if (null != cell) {
                            map.put(contentTL.get().get(j), cell.toString());
                        }
                    }

                }
                rowmap.put(String.valueOf(row.getRowNum()), map);
                list.add(rowmap);


            }
            //5、关闭流
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;

    }
 public boolean replaceAndGenerateWord(String srcPath,
                                          String destPath, Map<String, String> map) {
        String[] sp = srcPath.split("\\.");
        String[] dp = destPath.split("\\.");
        if ((sp.length > 0) && (dp.length > 0)) {// 判断文件有无扩展名
            // 比较文件扩展名
            if (sp[sp.length - 1].equalsIgnoreCase("docx")) {
                try {
                    XWPFDocument document = new XWPFDocument(
                            POIXMLDocument.openPackage(srcPath));
                    // 替换段落中的指定文字
                    Iterator<XWPFParagraph> itPara = document
                            .getParagraphsIterator();
                    while (itPara.hasNext()) {
                        XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (int i = 0; i < runs.size(); i++) {
                            String oneparaString = runs.get(i).getText(
                                    runs.get(i).getTextPosition());
                            for (Map.Entry<String, String> entry : map
                                    .entrySet()) {
                                oneparaString = oneparaString.replace(
                                        entry.getKey(), entry.getValue());
                            }
                            runs.get(i).setText(oneparaString, 0);
                        }
                    }

                    // 替换表格中的指定文字
                    Iterator<XWPFTable> itTable = document.getTablesIterator();
                    while (itTable.hasNext()) {
                        XWPFTable table = (XWPFTable) itTable.next();
                        int rcount = table.getNumberOfRows();
                        for (int i = 0; i < rcount; i++) {
                            XWPFTableRow row = table.getRow(i);
                            List<XWPFTableCell> cells = row.getTableCells();
                            for (XWPFTableCell cell : cells) {
                                String cellTextString = cell.getText();
                                for (Map.Entry<String, String> e : map.entrySet()) {
                                    if (cellTextString.contains(e.getKey()))
                                        cellTextString = cellTextString
                                                .replace(e.getKey(),
                                                        e.getValue());
                                }
                                cell.removeParagraph(0);
                                cell.setText(cellTextString);
                            }
                        }
                    }
                    FileOutputStream outStream = null;
                    outStream = new FileOutputStream(destPath);
                    document.write(outStream);
                    outStream.close();
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }

            } else
                // doc只能生成doc,如果生成docx会出错
                if ((sp[sp.length - 1].equalsIgnoreCase("doc"))
                        && (dp[dp.length - 1].equalsIgnoreCase("doc"))) {
                    HWPFDocument document = null;
                    try {
                        document = new HWPFDocument(new FileInputStream(srcPath));
                        Range range = document.getRange();
                        for (Map.Entry<String, String> entry : map.entrySet()) {
                            range.replaceText(entry.getKey(), entry.getValue());
                        }
                        FileOutputStream outStream = null;
                        outStream = new FileOutputStream(destPath);
                        document.write(outStream);
                        outStream.close();
                        return true;
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                        return false;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return false;
                    }
                } else {
                    return false;
                }
        } else {
            return false;
        }
    }
	<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>4.1.2</version>
		</dependency>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值