java如何生存word文档_java生成word文档【二】

/**

*

expWordByItext方法主要用于-采用itext导出文档到word.

*

优缺点-可将随意控制生成word的格式,但代码控制上比采用模板的方式稍微复杂,可设置页眉页脚等其他文档属性.

*

第三方jar-itext-2.1.7.jar、itext-rtf-2.1.7.jar.

* import com.lowagie.text.Document;

* import com.lowagie.text.DocumentException;

* import com.lowagie.text.Element;

* import com.lowagie.text.HeaderFooter;

* import com.lowagie.text.Paragraph;

* import com.lowagie.text.Phrase;

* import com.lowagie.text.Rectangle;

* import com.lowagie.text.rtf.RtfWriter2;

*

*

* 山河戀夢 Jul 30, 2015 - 5:07:55 PM

*

* @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();

}

/**

*

* dowmload方法主要用于-下载.

*

*/

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";

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值