android 按照模板导出word表格数据

1.下载poi相关libhttp://poi.apache.org/download.html

文件夹lib:doc功能实现依赖的包

文件夹:docx功能实现依赖的包

poi-4.1.2.jar  :基础类

poi-scratchpad-4.0.0.jar:doc功能实现

poi-ooxml-4.1.2.jar ,poi-ooxml-schemas-4.1.2.jar :docx功能实现相关类

3.要实现根据docx导出docx表格数据需要导入poi-4.1.2.jar,poi-ooxml-4.1.2.jar, poi-ooxml-schemas-4.1.2.jar,dom4j-1.6.1.jar

stax-api-1.0.1.jar,xmlbeans-2.3.0.jar

4.配置word模板:将需要替换的单元格内容用${  }  替换  

5.实现代码

try {
    // 配置需要替换的数据
    Map<String, String> dataMap = new HashMap<String, String>();
    dataMap.put("${1}","数据1");
    dataMap.put("${2}", "数据2");   
    //打开word模板
    InputStream inputStream = context.getAssets().open("模板.docx");
    XWPFDocument document = new XWPFDocument(inputStream);
//获取表格
    Iterator<XWPFTable> it = document.getTablesIterator();
    //表格内容替换添加
    while (it.hasNext()) {
        XWPFTable table = it.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) {  //单元格
                for (Map.Entry<String, String> e : dataMap.entrySet()) {
                    if (cell.getText().trim().equals(e.getKey())) {
                        //删除原来内容
                        cell.removeParagraph(0);
                        //写入新内容
                        cell.setText((String) e.getValue());
                    }
                }
            }
        }
    }
    // 写入数据  (path:导出的文件路径)
    OutputStream os = new FileOutputStream(path);
    document.write(os);
    os.flush();
    if (null != os) {
        os.close();
    }
    if (null != inputStream) {
        inputStream.close();
    }
} catch (IOException e) {
    e.printStackTrace();
}

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值