NPOI导出word,NPOI导出word表格,NPOI复制table表格 XWPFDocument中XWPFTable
使用NPOI可以对Word中的文本做替换,当遇到表格时,单个表格也可以循环遍历替换,但是如果需要根据数据源的条数,动态生成多个表格时,该怎么办?这里提供一种方案,
①先获取到word文档XWPFDocument myDoc
②再获取到word原本的表格模板myDoc.Tables[tableIndex]
③复制表格模板,有多少条源数据,复制多少个表格
④遍历源数据,一条数据替换并生成一个表格
/// <summary>
/// 为XWPFDocument文档复制指定索引的表
/// </summary>
/// <param name="myDoc"></param>
/// <param name="tableIndex">需要复制的table的索引</param>
/// <param name="targetIndex">复制到目标位置的table索引(如果目标位置原来有表格,会被覆盖)</param>
public static void CopyTable(XWPFDocument myDoc, int tableIndex, int targetIndex)
{
var sourceTable = myDoc.Tables[tableIndex];
CT_Tbl sourceCTTbl = myDoc.Document.body.GetTblArray(8);
var targetTable = myDoc.CreateTable();
myDoc.SetTable(targetIndex, targetTable);
var targetCTTbl = myDoc.Document.body.GetTblArray()[myDoc.Document.body.GetTblArray().Length - 1];
//CopyTable(sourceTable, targetCTTbl);
targetCTTbl.tblPr = sourceCTTbl.tblPr;
targetCTTbl.tblGrid = sourceCTTbl.tblGrid;
for (int i = 0; i < sourceTable.Rows.Count; i++)
{
var tbRow = targetTable.CreateRow();
var targetRow = tbRow.GetCTRow();
tbRow.RemoveCell(0);
XWPFTableRow row = sourceTable.Rows[i];
targetRow.trPr = row.GetCTRow().trPr;
targetRow.trPr = row.GetCTRow().trPr;
targetRow.trPr = row.GetCTRow().trPr;
targetRow.trPr = row.GetCTRow().trPr;
for (int c = 0; c < row.GetTableCells().Count; c++)
{
var tbCell = tbRow.CreateCell();
tbCell.RemoveParagraph(0);
var targetCell = tbCell.GetCTTc();
XWPFTableCell cell = row.GetTableCells()[c];
targetCell.tcPr = cell.GetCTTc().tcPr;
for (int p = 0; p < cell.Paragraphs.Count; p++)
{
var tbPhs = tbCell.AddParagraph();
CT_P targetPhs = tbPhs.GetCTP();
XWPFParagraph para = cell.Paragraphs[p];
var paraCTP = para.GetCTP();
targetPhs.pPr = paraCTP.pPr;
targetPhs.rsidR = paraCTP.rsidR;
targetPhs.rsidRPr = paraCTP.rsidRPr;
targetPhs.rsidRDefault = paraCTP.rsidRDefault;
targetPhs.rsidP = paraCTP.rsidP;
for (int r = 0; r < para.Runs.Count; r++)
{
var tbRun = tbPhs.CreateRun();
CT_R targetRun = tbRun.GetCTR();
XWPFRun run = para.Runs[r];
var runCTR = run.GetCTR();
targetRun.rPr = runCTR.rPr;
targetRun.rsidRPr = runCTR.rsidRPr;
targetRun.rsidR = runCTR.rsidR;
CT_Text text = targetRun.AddNewT();
text.Value = run.Text;
}
}
}
}
targetTable.RemoveRow(0);
}