服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Android - Android使用模板生成支持手机直接查看的Word文档

Android使用模板生成支持手机直接查看的Word文档

2022-09-03 15:01丶Veer Android

这篇文章主要为大家详细介绍了Android 使用模板生成Word文档,支持手机直接查看word,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

最近在项目工作中,碰到一个很棘手的需求,说是要在手机端根据模板生成word文档,而且不借助第三方的软件可以查看word文档,一开始听这个需求差不多蒙了,这要怎么做,为什么不把生成word文档这个工作放在后台呢,抱怨归抱怨,但是面对需求只能硬着头皮做了,经过各种拷问度娘和谷哥,终于找了一个比较好用的方法。特此跟他家分享。

Apache 公司推出的 Apache POI,我们来看下他的介绍:Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程式对Microsoft Office格式档案读和写的功能。

废话少说开始编码,首先我们要下Apache POI的开发jar包,下载地址,这里推荐不要下最新版本的,因为一开始我用最新版本的会出一下莫名其妙的问题,后面换旧的版本就OK了。这里我用的是3.9的还是比较稳定的、

Android使用模板生成支持手机直接查看的Word文档

开发有2个包,有一点我就非常郁闷Apache居然没有提供api稳定,开发起来还是比较蛋疼的,可能是我自己没有找到把,如果有知道的筒子可以@我、嘿嘿。不过Apache还是提供了Demo大家可以参考。还有我们要准备我们使用的word模板文件、这里我们放在了assets下面了。首先我们来看看怎么使用模板:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
package com.test.poiword;
 
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
 
import com.test.poiword.utils.FileUtils;
 
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
 
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
 
public class MainActivity extends Activity {
 // 模板文集地址
 private static final String demoPath = "/mnt/sdcard/doc/test.doc";
 // 创建生成的文件地址
 private static final String newPath = "/mnt/sdcard/doc/testS.doc";
 private Button btn,btns;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 btn=(Button)findViewById(R.id.btn);
 btns=(Button)findViewById(R.id.btns);
 btn.setOnClickListener(new OnClickListener() {
 
 @Override
 public void onClick(View arg0) {
 try {
  InputStream inputStream = getAssets().open("test.doc");
  FileUtils.writeFile(new File(demoPath), inputStream);
 } catch (Exception e) {
  e.printStackTrace();
 }
 doScan();
 }
 });
 btns.setOnClickListener(new OnClickListener() {
 
 @Override
 public void onClick(View arg0) {
 Intent intent = new Intent(MainActivity.this,WordHtmlActivity.class);
 startActivity(intent);
 }
 });
 
 }
 
 private void doScan(){
 //获取模板文件
 File demoFile=new File(demoPath);
 //创建生成的文件
 File newFile=new File(newPath);
 Map<String, String> map = new HashMap<String, String>();
 map.put("$QYMC$", "xxx科技股份有限公司");
 map.put("$QYDZ$", "上海市杨浦区xx路xx号");
 map.put("$QYFZR$", "张三");
 map.put("$FRDB$", "李四");
 map.put("$CJSJ$", "2000-11-10");
 map.put("$SCPZMSJWT$", "5");
 map.put("$XCJCJBQ$", "6");
 map.put("$JLJJJFF$", "7");
 map.put("$QYFZRQM$", "张三");
 map.put("$CPRWQM$", "赵六");
 map.put("$ZFZH$", "100001");
 map.put("$BZ$", "无");
 writeDoc(demoFile,newFile,map);
 //查看
 doOpenWord();
 }
 /**
 * 调用手机中安装的可打开word的软件
 */
 private void doOpenWord(){
 Intent intent = new Intent();
 intent.setAction("android.intent.action.VIEW");
 intent.addCategory("android.intent.category.DEFAULT");
 String fileMimeType = "application/msword";
 intent.setDataAndType(Uri.fromFile(new File(newPath)), fileMimeType);
 try{
 MainActivity.this.startActivity(intent);
 } catch(ActivityNotFoundException e) {
 //检测到系统尚未安装OliveOffice的apk程序
 Toast.makeText(MainActivity.this, "未找到软件", Toast.LENGTH_LONG).show();
 //请先到www.olivephone.com/e.apk下载并安装
 }
 }
 /**
 * demoFile 模板文件
 * newFile 生成文件
 * map 要填充的数据
 * */
 public void writeDoc(File demoFile ,File newFile ,Map<String, String> map)
 {
 try
 {
 FileInputStream in = new FileInputStream(demoFile);
 HWPFDocument hdt = new HWPFDocument(in);
 // Fields fields = hdt.getFields();
 // 读取word文本内容
 Range range = hdt.getRange();
 // System.out.println(range.text());
 
 // 替换文本内容
 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();
 }
 catch(IOException e)
 {
 e.printStackTrace();
 }
 catch(Exception e)
 {
 e.printStackTrace();
 }
 }
 
}

上面代码的代码并不多,首先我们要注意的是我们使用的poi的api大部分是在org.apache.poi.hwpf下面的,大家不要导错包了,因为apache每个包对应的内容不同:

Android使用模板生成支持手机直接查看的Word文档

上面代码不难懂,就是把我们要放的内容使用特定的代号组装一个map塞到我们的模板里面去,然后重新存储下,不过我们模板也要使用相同的代号、poi才能识别:

Android使用模板生成支持手机直接查看的Word文档

这样我们就使用模板大功告成了,就可以查看了、但是有些手机并没有装wps类似的工具,要是手机可以直接查看那就好了,嘿嘿、当然apache肯定也想到了、提供了这样的api下面上代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package com.test.poiword;
 
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.webkit.WebSettings;
import android.webkit.WebView;
 
import com.test.poiword.utils.FileUtils;
 
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.w3c.dom.Document;
 
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
 
/**
 * Created by fuweiwei on 2015/11/28.
 */
public class WordHtmlActivity extends FragmentActivity {
 //文件存储位置
 private String docPath = "/mnt/sdcard/doc/";
 //文件名称
 private String docName = "test.doc";
 //html文件存储位置
 private String savePath = "/mnt/sdcard/doc/";
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.html);
 String name = docName.substring(0, docName.indexOf("."));
 try {
 convert2Html(docPath + docName, savePath + name + ".html");
 } catch (Exception e) {
 e.printStackTrace();
 }
 //WebView加载显示本地html文件
 WebView webView = (WebView)this.findViewById(R.id.office);
 WebSettings webSettings = webView.getSettings();
 webSettings.setLoadWithOverviewMode(true);
 webSettings.setSupportZoom(true);
 webSettings.setBuiltInZoomControls(true);
 webView.loadUrl("file:/"+savePath+name+".html");
 }
 
 /**
 * word文档转成html格式
 * */
 public void convert2Html(String fileName, String outPutFile) {
 HWPFDocument wordDocument = null;
 try {
 wordDocument = new HWPFDocument(new FileInputStream(fileName));
 WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
  DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
 //设置图片路径
 wordToHtmlConverter.setPicturesManager(new PicturesManager() {
 public String savePicture(byte[] content,
   PictureType pictureType, String suggestedName,
   float widthInches, float heightInches) {
  String name = docName.substring(0, docName.indexOf("."));
  return name + "/" + suggestedName;
 }
 });
 //保存图片
 List<Picture> pics=wordDocument.getPicturesTable().getAllPictures();
 if(pics!=null){
 for(int i=0;i<pics.size();i++){
  Picture pic = (Picture)pics.get(i);
  System.out.println( pic.suggestFullFileName());
  try {
  String name = docName.substring(0,docName.indexOf("."));
  String file = savePath+ name + "/"
  + pic.suggestFullFileName();
  FileUtils.makeDirs(file);
  pic.writeImageContent(new FileOutputStream(file));
  } catch (FileNotFoundException e) {
  e.printStackTrace();
  }
 }
 }
 wordToHtmlConverter.processDocument(wordDocument);
 Document htmlDocument = wordToHtmlConverter.getDocument();
 ByteArrayOutputStream out = new ByteArrayOutputStream();
 DOMSource domSource = new DOMSource(htmlDocument);
 StreamResult streamResult = new StreamResult(out);
 TransformerFactory tf = TransformerFactory.newInstance();
 Transformer serializer = tf.newTransformer();
 serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
 serializer.setOutputProperty(OutputKeys.INDENT, "yes");
 serializer.setOutputProperty(OutputKeys.METHOD, "html");
 serializer.transform(domSource, streamResult);
 out.close();
 //保存html文件
 writeFile(new String(out.toByteArray()), outPutFile);
 } catch (Exception e) {
 e.printStackTrace();
 }
 }
 /**
 * 将html文件保存到sd卡
 * */
 public void writeFile(String content, String path) {
 FileOutputStream fos = null;
 BufferedWriter bw = null;
 try {
 File file = new File(path);
 if(!file.exists()){
 file.createNewFile();
 }
 fos = new FileOutputStream(file);
 bw = new BufferedWriter(new OutputStreamWriter(fos,"utf-8"));
 bw.write(content);
 } catch (FileNotFoundException fnfe) {
 fnfe.printStackTrace();
 } catch (IOException ioe) {
 ioe.printStackTrace();
 } finally {
 try {
 if (bw != null)
  bw.close();
 if (fos != null)
  fos.close();
 } catch (IOException ie) {
 }
 }
 }
}

上面的代码的原理起始也很简单,poi提供了让word文档转换成html页面的方法、我们只需要使用webview来加载这个html就ok了,这样我们就可以再手机端直接查看我们的word文档了,是不是好强大。其实看起来的比较复杂的功能只要我们静下心来想想就没有我们想象中的那么复杂,今天就为大家分享到这了。

分享Demo的源码:Android使用模板生成Word文档

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/u011916937/article/details/50085441

延伸 · 阅读

精彩推荐