本文章來源 POI導出Word文檔—黑殼網
昨天晚上被殼妹热监,威逼利誘展姐,做點小東西沐绒,其中就有一個POI導出Word文檔蔗彤。并且最好不要用freemarker模板導出word文檔川梅,只好手動來一個工具類了。
供參考學習
顯示界面

49da6226c7fb4e8492c610d0af3103fa-WX201706141301502x.png
控制層代碼
public class ExportController {
private static Logger logger = LoggerFactory.getLogger(ExportController.class);
@RequestMapping("index")
public String index(HttpServletRequest request, HttpServletResponse response) {
/**
* context 為以html樣式導出到word文檔里
*/
String context = " \n" +
"\n" +
"\n" +
" \n" +
"\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" +
" \n" +
" \n" +
" \"2\"align=\"center\"height=\"900px\"width=\"600px\"bordercolor=\"black\">\n" +
" \"table\"style=\"height: 200px;\">\n" +
" \n" +
"\n" +
" \n" +
" \n" +
" \"width: 50%;\" align=\"center\"> \n" +
" 分 析 報 告\n" +
" Failure Analysis Report\n" +
" 名稱:黑殼網\n" +
"\"http://www.bhusk.com\">http:\\\\www.bhusk.com" +
" \n" +
" \n" +
"\n" +
"\n";
/**
* 創(chuàng)建工具類實例
*/
ExportUtil exportUtil = new ExportUtil();
/**
* 調用~~~ 導出word成功
*/
exportUtil.exportWord(request, response, context);
return "index";
}
util類代碼
/**
* POI導出word文檔 無插件
* Created by kzyuan on 2017/6/14.
*/
public class ExportUtil {
private static final Logger logger = LoggerFactory.getLogger(ExportUtil.class);
public void exportWord(HttpServletRequest request, HttpServletResponse response, String content) {
try {
byte b[] = content.getBytes("utf-8"); //這里是必須要設置編碼的然遏,不然導出中文就會亂碼贫途。
ByteArrayInputStream bais = new ByteArrayInputStream(b);//將字節(jié)數組包裝到流中
/**
* 關鍵地方
* 生成word格式
*/
POIFSFileSystem poifs = new POIFSFileSystem();
DirectoryEntry directory = poifs.getRoot();
DocumentEntry documentEntry = directory.createDocument("WordDocument", bais);
//輸出文件
String fileName = "wordFileName";
request.setCharacterEncoding("utf-8");
response.setContentType("application/msword");//導出word格式
response.addHeader("Content-Disposition", "attachment;filename=" +
new String((fileName + ".doc").getBytes(),
"UTF-8"));
OutputStream ostream = response.getOutputStream();
poifs.writeFilesystem(ostream);
bais.close();
ostream.close();
} catch (Exception e) {
logger.error("導出出錯:%s", e.getMessage());
}
}
}
<a href=“https://github.com/ykz200/POIExportWord”>源代碼-GitHub</a>