Java操作word文档
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
Java操作Word文档
操作微软word办公软件的开发工具:
1.Apache基金会提供的POI
2.通过freemarker去解析xml
3.Java2word
4.iText
5.Jacob
通过对以上工具的对比,本人发现还是Itext比较简单易用,很容易上手,能够很轻松的处理word的样式、表格等。
贴上代码,供大家参考:
Jar包准备:
itext-2.0.1.jar -------------------核心包
iTextAsian.jar--------------------解决word样式、编码问题扩展包
1、设置标题样式
public static Paragraph setParagraphTitle(String content,Font contentFont){
Paragraph p = new Paragraph(content, contentFont);
p.setAlignment(Table.ALIGN_CENTER);
p.setIndentationLeft(60);
p.setIndentationRight(60);
p.setSpacingBefore(20);
return p;
}
2、设置内容样式:
public static Paragraph setParagraphStyle(String content,Font contentFont){
Paragraph p = new Paragraph(content, contentFont);
p.setFirstLineIndent(40);// 首行缩进
p.setAlignment(Paragraph.ALIGN_JUSTIFIED);// 对齐方式
p.setLeading(30);// 行间距
p.setIndentationLeft(60);// 左边距,右边距
p.setIndentationRight(60);
return p;
}
3、设置文档末尾时间:
public static Paragraph setParagraphTime(Font contentFont){ Paragraph p = new Paragraph(FormatUtil.getCurrentDate(), contentFont);
p.setIndentationLeft(250);
p.setIndentationRight(60);
p.setLeading(30);
p.setFirstLineIndent(40);
return p;
}
4、开始写word文档咯:
public static void WriteDoc(String path,Map
Document document = null;
try {
File file = new File(path);
if (!file.exists()) {
file.createNewFile();
}
document = new Document(PageSize.A4);
RtfWriter2.getInstance(document, new
FileOutputStream(file));
document.open();
// 设置title body 中文字体及样式
BaseFont cnFont =
BaseFont.createFont("STSongStd-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font titleFont = new Font(cnFont,22, Font.NORMAL, new
Color(0,0, 0));
Font contentFont = new Font(cnFont, 16, Font.NORMAL, new Color(0,0, 0));
// 设置文本标题
String titleInfo = “标题”;
// 设置文本内容
String contentFirst ="啊啊啊啊啊啊啊啊啊啊";
String contentSecond="啊啊啊啊啊啊啊啊啊啊啊啊";
String contentThird="啊啊啊啊啊啊啊啊啊啊啊啊啊";
String contentFourth="啊啊啊啊啊啊啊啊啊啊";
document.add(setParagraphTitle(titleInfo,titleFont));
document.add(setParagraphStyle(contentFirst,contentFont));
document.add(setParagraphStyle(contentSecond,contentFont));
document.add(setParagraphStyle(contentThird,contentFont));
document.add(setParagraphStyle(contentFourth,contentFont));
document.add(setParagraphTime(contentFont));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if (document != null) {
document.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
5、上传下载大家就自个动手了。