標籤:
@RequestMapping("download") public void exportWord( HttpServletRequest request, HttpServletResponse response) throws Exception { User user = AppContext.getLoginUser(); Student student = studentSvc.findByUserId(user.getId()); try { //word內容 String content="<html><body></body></html>"; 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="實習考核評鑑表"; request.setCharacterEncoding("utf-8"); response.setContentType("application/msword");//匯出word格式 response.addHeader("Content-Disposition", "attachment;filename=" + new String( (fileName + ".doc").getBytes(), "iso-8859-1")); OutputStream ostream = response.getOutputStream(); poifs.writeFilesystem(ostream); bais.close(); ostream.close(); }catch(Exception e){ AppUtils.logError("匯出出錯:%s", e.getMessage()); } }
Java 將html匯出word格式