java poi XWPFTable *** 作word表格的问题?

java poi XWPFTable *** 作word表格的问题?,第1张

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()

}

Step 01 显示出虚拟表格。在 Word 空白文档中单击【插入】 选项卡【表格】组中的【表格】 按钮, 在d出的下拉列表中显示了虚拟表格。

Step 02 选择创建的行列数。在虚拟表格中移动鼠标可选择表格的行列值。例如, 将鼠标指针指向坐标为 4 列 6行的单元格, 鼠标前的区域将呈选中状态, 并显示为橙色, 选择表格区域时, 虚拟表格的上方会显示“4×6表格”等类似的提示文字, 该信息表示鼠标指针滑过的表格范围, 也意味着即将创建的表格大小。与此同时,文档中将模拟出所选大小的表格。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11597614.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-17
下一篇2023-05-17

发表评论

登录后才能评论

评论列表(0条)

    保存