1、插入表格
代码:
https://blog.csdn.net/a3562323/article/details/116146544
效果:
2、插入行
代码:
//加载文档
Document doc1 = new Document("D://AsposeTest//123.doc");
//获取文档中的第2个表格,下标从0开始
Table table = (Table) doc1.getChild(NodeType.TABLE, 1, true);
//创建行
Row row = new Row(doc1);
//给行插入列,CreateCell是个方法
row.getCells().add(CreateCell("插入值1",doc1));
row.getCells().add(CreateCell("插入值2",doc1));
row.getCells().add(CreateCell("插入值3",doc1));
//插入到表格的第0行,下标0开始,从上到下
table.getRows().insert(0,row);
//table.getRows().add(row); add方法是插入到最后一行
//保存到指定文件
doc1.save("D://AsposeTest//插入值.doc");
效果:
3、插入列
代码:
//加载文档
Document doc1 = new Document("D://AsposeTest//123.doc");
//获取文档中的第2个表格,下标从0开始
Table table = (Table) doc1.getChild(NodeType.TABLE, 1, true);
//获取第4行,下标0开始
Row row2 = table.getRows().get(3);
//给该行0位置插入单元格
row2.getCells().insert(0, CreateCell("11111",doc1));
//保存到指定位置
doc1.save("D://AsposeTest//插入值.doc");
效果:
4、CreateCell
/**
* 创建列值
* @param value 要插入的值
* @param doc Document对象
* @return
*/
public static Cell CreateCell(String value,Document doc)
{
Cell cell = new Cell(doc);
Paragraph p = new Paragraph(doc);
p.appendChild(new Run(doc,value));
cell.appendChild(p);
return cell;
}
5、moveToCell
使用row2.getCells().insert()
插入内容的时候,想要手动换行,\n是无效的 ,暂时不知道怎么实现,所以找了个替换的方法,使用builder.moveToCell
,一共四个参数,原理是移动到指定位置,插入值
tableIndex—要移动的表的索引。
rowIndex -表中行的索引。
columnIndex—表中列的索引。
字符在单元格中的索引。目前只能指定0移动到单元格的开头,或指定-1移动到单元格的结尾。
moveToCell(int tableIndex, int rowIndex, int columnIndex, int characterIndex)
移动到当前文档的第2个表格的第1行的第2列的开头
builder.moveToCell(1, 0, 1, 0);
//开始写入东西
builder.write("asd\n123");*
效果:第2个表格的第1行的第2列的开头
要是有值,想清空再写入,也是自己研究的,不知道还要什么方法能实现,
Table table = (Table) doc.getChild(NodeType.TABLE, 1, true);
//给第1行第2列的值设为空,
table.getRows().get(0).getCells().get(1).getFirstParagraph().getRuns().get(0).setText("");
//再移动到当前文档的第2个表格的第1行的第2列的开头
builder.moveToCell(1, 0, 1, 0);
//开始写入东西
builder.write("asd\n123");*
效果:
换行无效:使用row2.getCells().insert()
插入内容的时候,想要手动换行,\n是无效的,
解决:使用控制符ControlChar