Java POI 导出 Word 文档

本文章来源 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";

	/**
	* 创建工具类实例
	*/
	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());
	}
    }
}

源代码-GitHub

黑壳博客 blog.bhusk.com

E-mail:keshu@bhusk.com

本文由 黑壳博客的壳叔 创作或转载,采用 知识共享署名 3.0 中国大陆许可协议 进行许可。

可自由转载、引用,但需署名作者且注明文章

留下你的脚步
推荐阅读