- 导入jar
下载连接:Free Spire.Doc for JAVA | 下载
推荐用免费版,使用商业版有水印,删除之后再用这个jar操作会报索引越界的问题。
- 定义好的 doc 模板,把内容注入进去(不会定义word书签的百度一下,我这里就不写了)
public static String writeParams(HttpServletRequest request, Map<String,String> params){
//获得定义好的模板的路径
request.getSession().getServletContext().getRealPath("template/template1.doc");
//new 一个文档并加载它
Document document = new Document(templatePath);
//获得文件定义的书签
BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document);
params.forEach((key, value) -> {
//移动到书签的位置
bookmarksNavigator.moveToBookmark(key);
if (value == null){
value = "";
}
//替换书签的内容,参数:String、Boolean(true不更换书签的样式)
bookmarksNavigator.replaceBookmarkContent(value.replaceAll("<br/>",""),true);
});
//保存文档,格式为doc
String path = request.getSession().getServletContext().getRealPath("upload/");
path += params.get("id")+".doc";
document.saveToFile(path,FileFormat.Doc);
return path;
}
- 用代码来设置 Word 格式
获取文档的
public static void format(String path){
//创建并加载文档
Document document = new Document(path,FileFormat.Doc);
//循环节段
SectionCollection sections = document.getSections();
for (int i = 0; i < sections.getCount(); i++) {
// 循环段落
ParagraphCollection paragraphs = sections.get(i).getParagraphs();
for (int i1 = 0; i1 < paragraphs.getCount(); i1++) {
}
}
}
使用 TextRange 的两种方式,基本上所有的调格式的都可以用 TextRange 来完成
//创建亲的段落并设置字体样式
Paragraph paragraph = document.createParagraph();
TextRange textRange = paragraph.appendText(joiner.toString());//添加文本
paragraph.getFormat().setFirstLineIndent(30f);//缩进
textRange.getCharacterFormat().setFontName("仿宋_GB2312");//字体
textRange.getCharacterFormat().setFontSize(16);//字体大小
//找出需要加颜色的文字,参数(String,Boolean:是否区分大小写,Boolean:启用全字匹配)
TextSelection textSelection = paragraph.find(strings[i2], false, true);
TextRange asOneRange = textSelection.getAsOneRange();
asOneRange.getCharacterFormat().setTextColor(Color.red);
//添加段落到后面
paragraphs.insert(i1+i2-1,paragraph);
- 删除第一行的警告:Evaluation Warning: The document was created with Spire.Doc for JAVA.
使用 Spire.doc 的一个问题在于保存过的文件都有一个红色的警告,我是直接删除第一行,但是这个是商业版的问题,用免费版就没有这个问题了。
下载地址:Free Spire.Doc for JAVA | 下载
/**
* 删除Word.docx第一行
* @param path
*/
public static void deleteDocxFirstText(String path){
try {
InputStream inputStream = new FileInputStream(path);
XWPFDocument document = new XWPFDocument(inputStream);
inputStream.close();
XWPFParagraph toDelete = document.getParagraphs().stream()
.filter(p -> StringUtils.equalsIgnoreCase(DELTEXT, p.getParagraphText()))
.findFirst().orElse(null);
if (toDelete != null) {
document.removeBodyElement(document.getPosOfParagraph(toDelete));
OutputStream fos = new FileOutputStream(path);
document.write(fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 删除Word.doc第一行
* @param path
*/
public static void deleteDocFirstText(String path){
try {
InputStream inputStream = new FileInputStream(path);
HWPFDocument document = new HWPFDocument(inputStream);
inputStream.close();
int numParagraphs = document.getRange().numParagraphs();
if (numParagraphs > 0){
document.getRange().getParagraph(0).delete();
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(path));
document.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
需要注意的是,在删除第一行后,如果下次进行操作的话,要用wps保存下,不然就会报 index list 越界错误,解决方法就是在没有操作完成先不要删除第一行,在最后才删除第一行,或者用免费版。