java导出word 拿来直接用

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","");  
    	}
    	
       
    }
	
	
}

ftl文件就放这里,代码总的路径不用改
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("<", "&lt;"); //字符串
 		str = str.replace(">", "&gt;"); //字符串
 		str = str.replace("&", "&amp;"); //字符串
 		str = str.replace("'", "&apos;"); //字符串
 		str = str.replaceAll("\"","&quot;");
		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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值