poi中,如何向Word文档里添加表格?

poi中,如何向Word文档里添加表格?,第1张

//创建一个表格

XWPFTable table = doc.createTable(4,2)

table.setCellMargins(50, 0, 50,3000)//top, left, bottom, right

//table.setInsideHBorder(XWPFBorderType.NONE, 0, 0, "")//去除单元格间的横线

table.getRow(0).getCell(0).setText("字段一:")

table.getRow(0).getCell(1).setText("字段二:")

table.getRow(1).getCell(0).setText("字段三:")

table.getRow(1).getCell(1).setText("字段四:")

关键代码如下:

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

}

打开要插入Word文档的Excel电子表格文件。

单击要插入Word文档的单元格,然后选择菜单命令“插入”→“对象”。

“对象”对话框“新建”选项卡中,选择对象类型“Microsoft Office Word文档”,并单击“确定”按钮。

这时有Excel中会出现一个Word文档编辑框,在里面直接输入内容,方法与在Word中编辑文档完全相同。

根据需要拖动Word文档对象四周的控点,可以调整Word文档对象的大小,也可以将鼠标移动到边缘,通过拖动改变其位置。编辑完毕可以在对象之外的单元格上单击鼠标,退出编辑状态。

此时如果单击Word文档对象,则会看到四周的控点变成了圆形,可以像拖动绘图对象一样拖动Word对象的位置,及改变其大小, *** 作起来非常方便。双击该对象可以再次进入编辑状态。

除了上述新建一个Word文档对象的方法之外,可以在进行到第3步时,选择“由文件创建”,然后在对话框中单击“浏览命令”,找到已经存在的Word文档,选择完毕,回到该对话框,单击“确定”按钮。插入到Excel文档中的Word文档,可以随时双击打开进行编辑。

如果希望直接使用保存在硬盘或其它存储器上的Word文档,又不希望增大Excel文档的大小,可以勾选对话框中的复选框“链接到文件”,这样当修改源文件时,源文件的更改也会反映到Excel文档中。

使用上述两种方法都有一个复选框“显示为图标”,如果选中它,则会在Excel文档中只显示一个图标。双击该图标,可以启动Word对文档进行编辑。

在Excel电子表格中可以插入Word文档对象,在Word中也可以插入Excel电子表格对象,可以举一反三。   


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

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

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

发表评论

登录后才能评论

评论列表(0条)

    保存