操作NPOI中的Word表格,复制/克隆完整表格
NPOI中没有提供复制表格/元素的方法,所以需要自己实现复制表格的方法
注意 以下操作均是操作docx
文件
操作Word文档需要操作XWPFDocument
对象,复制表格需要操作XWPFTable
对象
NPOI项目地址:https://github.com/tonyqus/npoi
代码如下,需要修改XWPFTable
的构造函数:
public XWPFTable(CT_Tbl table, IBody part, XWPFTable source)
// create new table by origin table
{
this.part = part;
this.ctTbl = table;
tableRows = new List<XWPFTableRow>();
XWPFTable target = this;
target.ctTbl.tblPr = source.ctTbl.tblPr;
target.ctTbl.tblGrid = source.ctTbl.tblGrid;
for (int i = 0; i < source.Rows.Count; i++)
{
CT_Row targetRow = target.ctTbl.AddNewTr();
XWPFTableRow row = source.Rows[i];
targetRow.trPr = row.GetCTRow().trPr;
targetRow.rsidR = row.GetCTRow().rsidR;
targetRow.rsidTr = row.GetCTRow().rsidTr;
targetRow.Table = table;
XWPFTableRow tabRow = new XWPFTableRow(targetRow, this);
tableRows.Add(tabRow);
for (int c = 0; c < row.GetTableCells().Count; c++)
{
CT_Tc targetCell = targetRow.AddNewTc();
XWPFTableCell cell = row.GetTableCells()[c];
targetCell.tcPr = cell.GetCTTc().tcPr;
for (int p = 0; p < cell.Paragraphs.Count; p++)
{
CT_P targetPhs = targetCell.AddNewP();
XWPFParagraph para = cell.Paragraphs[p];
targetPhs.pPr = para.GetCTP().pPr;
targetPhs.rsidR = para.GetCTP().rsidR;
targetPhs.rsidRPr = para.GetCTP().rsidRPr;
targetPhs.rsidRDefault = para.GetCTP().rsidRDefault;
targetPhs.rsidP = para.GetCTP().rsidP;
for (int r = 0; r < para.Runs.Count; r++)
{
CT_R targetRun = targetPhs.AddNewR();
XWPFRun run = para.Runs[r];
targetRun.rPr = run.GetCTR().rPr;
targetRun.rsidRPr = run.GetCTR().rsidRPr;
targetRun.rsidR = run.GetCTR().rsidR;
CT_Text text = targetRun.AddNewT();
text.Value = run.Text;
}
}
}
}
}
不理解的可以Clone github上的代码 拿工具看一下Word(docx)的结构就能大概明白了
不想修改构造函数的,可以使用反射直接操作元素
另外,NPOI毕竟是根据Java的POI改过来的,有些东西很多作者都没有实现,商用请慎重!