码迷,mamicode.com
首页 > 编程语言 > 详细

java生成word文档【二】

时间:2015-08-04 19:33:58      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

/**
 * <p>expWordByItext方法主要用于-采用itext导出文档到word.</p>
 * <p>优缺点-可将随意控制生成word的格式,但代码控制上比采用模板的方式稍微复杂,可设置页眉页脚等其他文档属性.</p>
 * <p>第三方jar-itext-2.1.7.jar、itext-rtf-2.1.7.jar.<br>
 * import com.lowagie.text.Document;<br>
 * import com.lowagie.text.DocumentException;<br>
 * import com.lowagie.text.Element;<br>
 * import com.lowagie.text.HeaderFooter;<br>
 * import com.lowagie.text.Paragraph;<br>
 * import com.lowagie.text.Phrase;<br>
 * import com.lowagie.text.Rectangle;<br>
 * import com.lowagie.text.rtf.RtfWriter2;
 * </p>
 * <p>
 * 山河戀夢 Jul 30, 2015 - 5:07:55 PM
 * </p>
 * @param content
 * @param filePath
 * @throws FileNotFoundException 
 * @throws DocumentException 
 */
private static void expWordByItext(String content, String filePath) throws FileNotFoundException, DocumentException {
	Document doc = new Document(PageSize.A4);
	RtfWriter2.getInstance(doc, new FileOutputStream(filePath));
	doc.open();
	Paragraph p = new Paragraph(content);
	doc.add(p);
	doc.close();
}

 

/**
 * <p>
 * dowmload方法主要用于-下载.
 * </p>
 */
public String dowmload(HttpServletRequest request, HttpServletResponse response) throws IOException {
	String fileName = "导出测试.doc";
	String fullPath = "D:/" + fileName;
	File file = new File(fullPath);
	InputStream in = new BufferedInputStream(new FileInputStream(fullPath));
	
	// ContentType参见http://tool.oschina.net/commons
	response.setContentType("application/octet-stream");
	fileName = new String(fileName.replaceAll(" ", "").getBytes("gb2312"), "ISO8859-1");
	response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
	response.addHeader("Content-Length", "" + file.length());
	
	// 方式一
	OutputStream out = new BufferedOutputStream(response.getOutputStream());
	byte[] buffer = new byte[in.available()];
	in.read(buffer);
	out.write(buffer);

	in.close();
	out.flush();
	out.close();

	// 方式二
	String line = null;
	OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
	BufferedReader reader = new BufferedReader(new InputStreamReader(in));
	while ((line = reader.readLine()) != null) {
		writer.write(line);
		writer.write("\r\n");
	}
	in.close();
	writer.flush();
	writer.close();

	return "download";
}

 

java生成word文档【二】

标签:

原文地址:http://my.oschina.net/chwencong/blog/487624

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!