java导出word
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.aliyuncs.utils.IOUtils;
import com.boerxin.entity.Model.AccessoryModel;
import com.boerxin.entity.Model.RetrieveHistoryModel;
import com.boerxin.service.RetrieveHistoryService;
import com.boerxin.util.AjaxJson;
import com.boerxin.util.FilePathUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@RestController
@CrossOrigin
@RequestMapping("/aaa")
public class WordTest3 {
@Autowired
private RetrieveHistoryService retrieveHistoryService;
@RequestMapping(value = "/a", method = RequestMethod.GET)
public void createWord(HttpServletResponse resp,String rhId) throws IOException{
Map<String,Object> dataMap=new HashMap<String,Object>();
getData(dataMap,rhId);
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
Template t=null;
try {
t = cfg.getTemplate("QualityInspectionResults.ftl"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
//File outFile = new File("D:/outFile"+Math.random()*10000+".doc"); //导出文件
Writer out = null;
resp.setContentType("application/vnd.ms-excel");
try {
resp.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("文件名", "UTF-8") + ".doc");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream()));
} 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,String rhId) {
RetrieveHistoryModel model = retrieveHistoryService.selectOneRetrieveHistory(rhId);
if(model!=null) {
dataMap.put("searchContent", model.getSearchContent());
dataMap.put("klKeyword", model.getKlKeyword());
}else {
dataMap.put("searchContent", "");
dataMap.put("klKeyword","");
}
}
}
pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
下面是我在项目中的实际用法 需求是导出质检文章,文章中的关键字显示红色
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.aliyuncs.utils.IOUtils;
import com.boerxin.entity.Model.AccessoryModel;
import com.boerxin.entity.Model.RetrieveHistoryModel;
import com.boerxin.service.AccessoryService;
import com.boerxin.service.RetrieveHistoryService;
import com.boerxin.util.AjaxJson;
import com.boerxin.util.FilePathUtil;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@RestController
@CrossOrigin
@RequestMapping("/generateWord")
public class generateWord {
@Autowired
private RetrieveHistoryService retrieveHistoryService;
@Autowired
private AccessoryService accessoryService;
@RequestMapping(value = "/toGenerateWord", method = RequestMethod.GET)
public void createWord(HttpServletResponse resp,String rhid) throws IOException{
Map<String,Object> dataMap=new HashMap<String,Object>();
RetrieveHistoryModel model = retrieveHistoryService.selectOneRetrieveHistory(rhid);
AccessoryModel acc = accessoryService.selectOneAccessory(model.getAccid());
String filename=acc.getName();
getData(dataMap,rhid);
Configuration cfg = new Configuration();
cfg.setDefaultEncoding("UTF-8");
cfg.setClassForTemplateLoading(this.getClass(), "/templates");
Template t=null;
try {
t = cfg.getTemplate("QualityInspectionResults.ftl","UTF-8"); //获取模板文件
} catch (IOException e) {
e.printStackTrace();
}
//File outFile = new File("D:/outFile"+Math.random()*10000+".doc"); //导出文件
Writer out = null;
resp.setContentType("application/vnd.ms-excel");
try {
resp.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("《"+filename+"》质检详情", "UTF-8") + ".doc");
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
//out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
out = new BufferedWriter(new OutputStreamWriter(resp.getOutputStream(),"UTF-8"));
} 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,String rhId) {
RetrieveHistoryModel model = retrieveHistoryService.selectOneRetrieveHistory(rhId);
String alist = StringToArrayList(model.getSearchContent(),model.getKlKeyword());
String j = "<w:r wsp:rsidRPr=\"005B2A66\">" +
" <w:rPr>" +
" <w:rFonts w:hint=\"fareast\" />" +
" <w:b />" +
" <w:b-cs />" +
" <w:color w:val=\"FF0000\" />" +
" <w:sz w:val=\"32\" />" +
" <w:sz-cs w:val=\"32\" />" +
" </w:rPr>" +
" <w:t>";
String k ="</w:t></w:r>";
alist = alist.replace("@@",j);
alist = alist.replace("##",k);
List<String> result = Arrays.asList(alist.split("<w:r wsp:rsidRPr=\"005B2A66\">"));
String data="";
if(model!=null) {
for(int i=0;i<result.size();i++) {
String a = result.get(i).toString().trim();
if(a.contains("<w:color w:val=\"FF0000\"")) {
String b="<w:r wsp:rsidRPr=\"005B2A66\">"+a;
List<String> bList = Arrays.asList(b.split("</w:r>"));
data+=bList.get(0)+"</w:r>";
if(bList.size()>1) {
data+=" <w:r wsp:rsidRPr=\"005B2A66\">" +
" <w:rPr>" +
" <w:rFonts w:hint=\"fareast\" />" +
" <w:sz w:val=\"28\" />" +
" <w:sz-cs w:val=\"28\" />" +
" </w:rPr>" +
" <w:t>"+bList.get(1).trim()+"</w:t>" +
" </w:r>";
}
}else{
data+=" <w:r wsp:rsidRPr=\"005B2A66\">" +
" <w:rPr>" +
" <w:rFonts w:hint=\"fareast\" />" +
" <w:sz w:val=\"28\" />" +
" <w:sz-cs w:val=\"28\" />" +
" </w:rPr>" +
" <w:t>"+a.trim()+"</w:t>" +
" </w:r>";
}
}
System.out.println(data+"------------------data");
dataMap.put("searchContent", data);
}
}
public static String StringToArrayList(String searchContent, String klKeyword) {
String str = searchContent.replace(" ", ""); //字符串
str = str.replace("<", "<"); //字符串
str = str.replace(">", ">"); //字符串
str = str.replace("&", "&"); //字符串
str = str.replace("'", "'"); //字符串
str = str.replaceAll("\"",""");
String d ="@@";
String e ="##";
List<String> klKeywordList = Arrays.asList(klKeyword.split(","));
for(int i=0;i<klKeywordList.size();i++) {
str = str.replace(klKeywordList.get(i),d+klKeywordList.get(i).trim()+e);
}
System.out.println(str+"------------------str");
return str;
}
}