本教程是通过apache的POI工具导出word,亲测在office2016上测试成功。
step1:
测试所用jar包:commons-codec-1.10.jar、commons-collections4-4.1.jar、commons-logging-1.2.jar、log4j-1.2.17.jar、poi-3.16.jar、poi-scratchpad-3.16.jar
下载地址:http://apache.fayea.com/poi/release/bin/poi-bin-3.16-20170419.zip
step2:
首先需要一个template.doc模版
step3:
直接在temolate.doc文件当中把当中的”username”(不包括”“),修改为“${username}”,同理其他的变量也这样修改。修改后的template.doc为:
step4:
将修改后的template.doc拷贝带assets文件夹中(android studio中没有此文件夹的在main文件下创建此目录.
step5:
代码实现
package com.bsi.demo;
import android.content.Context;
import android.os.Environment;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Created by qianmang on 2017/7/14.
*/
public class POITest {
private final Context context;
public POITest(Context context) {
this.context = context;
}
public void testWrite() {
InputStream open = null;
BufferedInputStream fis = null;
try {
open = context.getAssets().open("template.doc");
fis = new BufferedInputStream(open);
HWPFDocument document = new HWPFDocument(fis);
Range range = document.getRange();
range.replaceText("${username}", "张三");
range.replaceText("${age}", "24");
range.replaceText("${birthday}", "1994-5-20");
range.replaceText("${mianmao}", "党员");
range.replaceText("${mobile}", "13026131188");
range.replaceText("${address}", "天堂");
range.replaceText("${id}", "421126199405200077");
//导出后保存的doc文件位置,笔者是将文件保存在SD卡上因此还要申请SD卡写权限
OutputStream os = new FileOutputStream(Environment.getExternalStorageDirectory()+ System.getProperty("file.separator") + "export_template.doc");
document.write(os);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (open != null) {
try {
open.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
step6:
添加写SD卡权限,6.0以上的自行申请动态权限,不在此处赘述
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
step8:
在andoid studio有可能会出现无法运行的安装原因是依赖的jar有多个LICENSE文件导致的,
只需要在modle的build.gradle文件中添加
android{
//......code
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
//.....code
}