Android基于Poi生成Word

该文章介绍了如何在Android平台上利用Poi库读取Word模板并替换内容生成新的Word文档。首先,需要下载Poi相关的jar包并导入项目。然后,通过代码实现从assets读取模板,创建新文件,并用HashMap存储要替换的数据,最后进行文本替换并保存到指定路径。
摘要由CSDN通过智能技术生成

一、前期准备

1、编写Word模板

2、下载poi相关jar包

将jar包导入到项目lib中


网上编写的生成word 文档 和 预览基本是一样的,难点在于正确的这两个库的寻找。word文档的生成基本不会有问题。下载地址:用于Android生成Word的Poi 包https://download.csdn.net/download/Hearbeat/87380805

二、代码实现

    private static final String newPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/doc/test.doc";
    private static final String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/doc";

    public void Save() {
        try {
            //从assets读取Word模板
            InputStream is = getAssets().open("调查报告模板.doc");/当前模板放到项目工程中assets目录
            //创建生成的文件
            File old = new File(newPath);
            File newFile=null;
            if(old.exists()){
                old.delete();
                newFile=new File(newPath);
            }else{
                newFile=new File(newPath);
            }
            Map<String, String> map = new HashMap<String, String>();
            map.put("$Name$", "李四");
            writeDoc(is, newFile, map);
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "Save: "+e.toString() );
        }
    }

    /**
     * newFile 生成文件
     * map 要填充的数据
     */
    public void writeDoc(InputStream in, File newFile, Map<String, String> map) {
        try {

            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            HWPFDocument hdt = new HWPFDocument(in);
            Range range = hdt.getRange();

            // 替换文本内容
            Log.e(TAG, "writeDoc: "+file.getAbsolutePath() );
            for (Map.Entry<String, String> entry : map.entrySet()) {
                range.replaceText(entry.getKey(), entry.getValue());
            }
            ByteArrayOutputStream ostream = new ByteArrayOutputStream();
            FileOutputStream out = new FileOutputStream(newFile, true);
            hdt.write(ostream);
            // 输出字节流
            out.write(ostream.toByteArray());
            out.close();
            ostream.close();
            Log.e(TAG, "writeDoc: successs " );
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, "writeDoc: 1"+e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "writeDoc: 2"+e.toString());
        }
    }

自此Word可以生成并能够导出。

三、效果展示

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Leonban

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值