admin管理员组文章数量:1581021
网上介绍的方法都挺好,网上一搜也一大把,我用的是制作模板的那个方法,还挺好用的,现在分享一下。
先找一个教程,制作一个模板,然后就是测试:
代码它来了,
public class WordTest {
private Configuration configuration = null;
public WordTest(){
configuration = new Configuration();
configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
WordTest test = new WordTest();
test.createWord();
}
public void createWord(){
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap);
configuration.setClassForTemplateLoading(this.getClass(), "");//模板文件所在路径
Template t=null;
try {
t = configuration.getTemplate("测试.ftl"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
File outFile = new File("D:/outFile"+Math.random()*10000+".doc"); //导出文件
Writer out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void getData(Map<String, Object> dataMap) {
dataMap.put("title", "标题");
dataMap.put("nian", "2016");
dataMap.put("yue", "3");
dataMap.put("ri", "6");
dataMap.put("shenheren", "lc");
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
for (int i = 0; i < 10; i++) {
Map<String,Object> map = new HashMap<String,Object>();
map.put("xuehao", i);
map.put("neirong", "内容"+i);
list.add(map);
}
dataMap.put("list", list);
}
}
成了。
还可以直接输出到浏览器。
只需要添加
response.setContentType("application/x-msdownload;");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("文件名", "UTF-8") + ".doc");
然后其中的createWord()方法就成了下面这个代码:
public void createWord(HttpServletResponse resp){
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap);
configuration.setClassForTemplateLoading(this.getClass(), "");//模板文件所在路径
Template t=null;
try {
t = configuration.getTemplate("测试.ftl"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
//File outFile = new File("D:/outFile"+Math.random()*10000+".doc"); //导出文件
Writer out = null;
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("文件名", "UTF-8") + ".doc");
try {
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件
} catch (TemplateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
版权声明:本文标题:java导出word,输出到浏览器下载 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1726894970a1089054.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论