
1.下载
下载3.8beta4版本,请记得一定要下载该版本,其他版本读取word模板并改写内容生成新的文件后,打开新文件时会提示“word无法读取文档,文档可能损坏。”
2.集成到项目
这一步很简单,只要把下载后解压得到的poi-3.8-beta4-20110826.jar和poi-scratchpad-3.8-beta4-20110826.jar两个文件复制到java web项目的lib目录下就行了
3.制作word模板
把需要变动的值全部用代码来代替,例如你需要改变名称的值,则可以在模板中用name来表示。详细见附件中的doc文件。
4.调用接口方法实现对word的读写 *** 作
整个过程就是先读取模板,然后修改内容,再重新生成新的文档保存到本地或者输出文件流提供下载,下面分别是生成新文档和输出文件流两种方式的代码片断,详细的代码请见下列代码中的readwriteWord()两个重载方法。
关键代码如下:FileInputStream fileInputStream = new FileInputStream( soureFile)
POIFSFileSystem pfs = new POIFSFileSystem( fileInputStream )
HWPFDocument hwpf = new HWPFDocument(pfs)// make a HWPFDocument object
OutputStream output = new FileOutputStream( targetFile )
hwpf.write(output)// write to the target file
output.close()
(2)再word中插入表格。HWPF的情况:
Table tcDataTable = range.insertTableBefore( (short)column , row)//column and row列数和行数
tcDataTable.getRow(i).getCell(j).getParagraph(0).getCharacterRun(0).insertBefore("插入i行j列的内容" )
XWPF的情况:
String outputFile = "D:\\test.doc"
XWPFDocument document = new XWPFDocument()
XWPFTable tableOne = document.createTable()
XWPFTableRow tableOneRowOne = tableOne.getRow(0)
tableOneRowOne.getCell(0).setText("11")
XWPFTableCell cell12 = tableOneRowOne.createCell()
cell12.setText("12")
// tableOneRowOne.addNewTableCell().setText("第1行第2列")
// tableOneRowOne.addNewTableCell().setText("第1行第3列")
// tableOneRowOne.addNewTableCell().setText("第1行第4列")
XWPFTableRow tableOneRowTwo = tableOne.createRow()
tableOneRowTwo.getCell(0).setText("21")
tableOneRowTwo.getCell(1).setText("22")
// tableOneRowTwo.getCell(2).setText("第2行第3列")
XWPFTableRow tableOneRow3 = tableOne.createRow()
tableOneRow3.addNewTableCell().setText("31")
tableOneRow3.addNewTableCell().setText("32")
FileOutputStream fOut
try {
fOut = new FileOutputStream(outputFile)
document.write(fOut)
fOut.flush()
// *** 作结束,关闭文件
fOut.close()
} catch (Exception e) {
e.printStackTrace()
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)