本文章来源 POI 导出 Word 文档—黑壳网
昨天晚上被壳妹,威逼利诱,做点小东西,其中就有一个 POI 导出 Word 文档。并且最好不要用 freemarker 模板导出 word 文档,只好手动来一个工具类了。
供参考学习
显示界面
控制层代码
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"; /** * 创建工具类实例 */ 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);//将字节数组包装到流中 /** * 关键地方 * 生成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()); } } }
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于