1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > java 导出word 乱码问题 如何解决POI生成WORD中文乱码问题?

java 导出word 乱码问题 如何解决POI生成WORD中文乱码问题?

时间:2022-02-18 01:15:40

相关推荐

java 导出word 乱码问题 如何解决POI生成WORD中文乱码问题?

需求:因为系统用户需要把合同,产品,证书导出WORD。

设计:写好合同,产品,证书的模板,然后读取模板,写入WORD,最后弹出窗口让用户保存。

我写了二个方法,但是感觉方法一对以后的表单问题不能解决,而方法二我用POI实现生成WORD时出现乱码,这个不知道怎么解决,我已研究了一天了。还没有解决。

方法一:

[C:\\doc.doc]内容:

我是$[name];

Word.java-writeWord方法:

public void writeWord(HttpServletResponse response) {

String URL = "C:\\doc.doc";

File file = new File(URL);

try {

FileInputStream in = new FileInputStream(file);

POIFSFileSystem pfs = new POIFSFileSystem(in);

HWPFDocument hwpf = new HWPFDocument(pfs);

Range range = hwpf.getRange();

String str = range.text();

str = str.replace("$[name]", "黄锋");

System.out.println(str);

response.setCharacterEncoding("GB2312");

response.setContentType("application/ms-word");

response.setHeader("Content-disposition", "attachment; filename=1.doc");

PrintWriter out = response.getWriter();

out.println(str);

out.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

方法二:生成时出现乱码问题,待解决。

public void printWord(HttpServletResponse response) {

String URL = "C:\\test.doc";

File file = new File(URL);

try {

FileInputStream in = new FileInputStream(file);

POIFSFileSystem pfs = new POIFSFileSystem(in);

HWPFDocument hwpf = new HWPFDocument(pfs);

Range range = hwpf.getRange();

String str = FileKit.readFile("C:\\doc.text");

str = str.replace("$[name]", "黄锋");

System.out.println(str);

//str = StringKit.getISO8859ToGBK(str);

range.insertBefore(str);

response.setContentType("application/ms-word");

response.setHeader("Content-disposition", "attachment; filename=2.doc");

OutputStream out = response.getOutputStream();

hwpf.write(out);

out.close();

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

现在需要解决的是

HWPFDocument.write(out);中文乱码问题。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。