/// <summary> /// 为XWPFDocument文档复制指定索引的表 /// </summary> /// <param name="readDoc">模板文件</param> /// <param name="tableIndex">需要复制模板的table的索引</param> /// <param name="targetIndex">复制到目标位置的table索引(如果目标位置原来有表格,会被覆盖)</param> /// <param name="myDoc">新创建的文件</param> public static void CopyTable(XWPFDocument readDoc, int tableIndex, int targetIndex, XWPFDocument myDoc) { var sourceTable = readDoc.Tables[tableIndex]; CT_Tbl sourceCTTbl = readDoc.Document.body.GetTblArray(8); var targetTable = myDoc.CreateTable(); myDoc.SetTable(targetIndex, targetTable); var targetCTTbl = myDoc.Document.body.GetTblArray()[myDoc.Document.body.GetTblArray().Length - 1]; targetCTTbl.tblPr = sourceCTTbl.tblPr; targetCTTbl.tblPr.jc.val = ST_Jc.left;//表格在页面水平位置 //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; 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); }
/// <summary> /// 复制行 /// </summary> /// <param name="targetRow"></param> /// <param name="sourceRow"></param> private void XWPFTableRowCopy(XWPFTableRow targetRow, XWPFTableRow sourceRow) { targetRow.GetCTRow().trPr = sourceRow.GetCTRow().trPr; List <XWPFTableCell> cellList = sourceRow.GetTableCells(); //复制列及其属性和内容 foreach (var sourceCell in cellList) { var index = cellList.IndexOf(sourceCell); var targetCell = targetRow.GetCell(index); if (targetCell == null) { break; } targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr; if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0) { //设置段落样式 var sourceParagraph = sourceCell.Paragraphs[0]; targetCell.Paragraphs[0].Alignment = ParagraphAlignment.CENTER; if (sourceParagraph.Runs != null && sourceParagraph.Runs.Count > 0) { var cellR = targetCell.Paragraphs[0].CreateRun(); cellR.SetText(sourceCell.GetText()); cellR.IsBold = sourceParagraph.Runs[0].IsBold; //cellR.FontFamily = sourceParagraph.Runs[0].FontFamily; cellR.FontSize = 10; } else { targetRow.GetCell(index).SetText(sourceCell.GetText()); } } else { targetRow.GetCell(index).SetText(sourceCell.GetText()); } } }
/// <summary> /// 将行拷贝到目标表格 /// 只拷贝了基本的样式 /// </summary> /// <param name="targetTable">目标表格</param> /// <param name="sourceRow">源表格行</param> /// <param name="rowIndex">行索引</param> /// <param name="maxCol">表格最大列数</param> public static void CopyRowToTable(XWPFTable targetTable, XWPFTableRow sourceRow, int rowIndex, int maxCol) { //在表格指定位置新增一行 XWPFTableRow targetRow = rowIndex == 0 ? targetTable.GetRow(0) : targetTable.CreateRow(); //复制行属性 targetRow.GetCTRow().trPr = sourceRow.GetCTRow().trPr; List <XWPFTableCell> cellList = sourceRow.GetTableCells(); if (null == cellList) { return; } //复制列及其属性和内容 int colIndex = 0; foreach (XWPFTableCell sourceCell in cellList) { XWPFTableCell targetCell = null; //新增行会默认有一个单元格,因此直接获取就好 try { targetCell = targetRow.GetCell(colIndex); } catch (Exception) { } if (targetCell == null) { targetCell = targetRow.CreateCell(); } //列属性 targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr; //段落属性 if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0) { var paragraph = targetCell.Paragraphs[0]; var ctp = (CT_P)typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(paragraph); var sourceParagraph = sourceCell.Paragraphs[0]; var sourceCtp = (CT_P)typeof(XWPFParagraph).GetField("paragraph", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(sourceParagraph); paragraph.Alignment = sourceParagraph.Alignment; ctp.pPr = sourceCtp.pPr; if (sourceCell.Paragraphs[0].Runs != null && sourceCell.Paragraphs[0].Runs.Count > 0) { XWPFRun cellR = targetCell.Paragraphs[0].CreateRun(); var srcRun = sourceCell.Paragraphs[0].Runs[0]; cellR.SetText(sourceCell.GetText()); cellR.IsBold = srcRun.IsBold; cellR.SetColor(srcRun.GetColor()); cellR.FontFamily = srcRun.FontFamily; cellR.IsCapitalized = srcRun.IsCapitalized; cellR.IsDoubleStrikeThrough = srcRun.IsDoubleStrikeThrough; cellR.IsEmbossed = srcRun.IsEmbossed; cellR.IsImprinted = srcRun.IsImprinted; cellR.IsItalic = srcRun.IsItalic; cellR.IsShadowed = srcRun.IsShadowed; } else { targetCell.SetText(sourceCell.GetText()); } } else { targetCell.SetText(sourceCell.GetText()); } colIndex++; } if (cellList.Count < maxCol) { try { targetRow.MergeCells(cellList.Count - 1, maxCol - 1); } catch { } } }
/// <summary> /// 复制一行到指定位置 /// 样式信息也复制了,但需要完善。 /// </summary> /// <param name="sourceRow"></param> /// <param name="table"></param> /// <param name="rowIndex"></param> /// <returns></returns> public static XWPFTableRow CopyRow(XWPFTableRow sourceRow, XWPFTable table, int rowIndex) { //在表格指定位置新增一行 var needRemove = false; if (table.NumberOfRows <= rowIndex) { table.CreateRow(); needRemove = true; } XWPFTableRow targetRow = table.InsertNewTableRow(rowIndex); if (needRemove) { table.RemoveRow(rowIndex + 1); } //复制行属性 targetRow.GetCTRow().trPr = sourceRow.GetCTRow().trPr; List <XWPFTableCell> sourceCells = sourceRow.GetTableCells(); if (null == sourceCells) { return(targetRow); } //复制列及其属性和内容 foreach (var sourceCell in sourceCells) { XWPFTableCell targetCell = targetRow.AddNewTableCell(); targetCell.RemoveParagraph(0);//新建cell会自动创建paragraph,将其删除,下面代码循环添加 //列属性 targetCell.GetCTTc().tcPr = sourceCell.GetCTTc().tcPr; //段落属性 if (sourceCell.Paragraphs != null && sourceCell.Paragraphs.Count > 0) { foreach (var sourcePa in sourceCell.Paragraphs) { if (sourcePa.Runs != null && sourcePa.Runs.Count > 0) { var targetPa = targetCell.AddParagraph(); targetPa.Alignment = sourcePa.Alignment; foreach (var srcR in sourcePa.Runs) { XWPFRun tarR = targetPa.CreateRun(); tarR.SetText(srcR.Text); tarR.SetTextPosition(srcR.GetTextPosition()); tarR.FontFamily = srcR.FontFamily; tarR.FontSize = srcR.FontSize <= 0 ? 12 : srcR.FontSize; tarR.IsBold = srcR.IsBold; tarR.IsItalic = srcR.IsItalic; tarR.IsCapitalized = srcR.IsCapitalized; tarR.SetColor(srcR.GetColor()); tarR.SetUnderline(srcR.Underline); tarR.CharacterSpacing = srcR.CharacterSpacing; } } else { targetCell.SetText(sourceCell.GetText()); } } } else { targetCell.SetText(sourceCell.GetText()); } } return(targetRow); }
/// <summary> /// 处理表格 /// </summary> /// <param name="tableCell"></param> /// <param name="list"></param> private void ProcessTableCell(TableCell tableCell, IEnumerable <DynamicEntity> list) { var newList = list.ToList(); list = list.ToList(); //if (tableCell.Paragraph.Runs.Count != 1) return; //Regex reg = new Regex(matchDouble, RegexOptions.Multiline | RegexOptions.Singleline); //MatchCollection matchs = reg.Matches(tableCell.Paragraph.ParagraphText); //if (matchs == null || matchs.Count != 1) return; //string propertyName = Regex.Replace(matchs[0].Value, repDouble, ""); string propertyName = Regex.Replace(tableCell.Paragraph.Text, repDouble, ""); var runs = tableCell.Paragraph.Runs.Where(t => t.Text.Contains(propertyName.Trim())); if (runs == null || runs.Any() == false) { return; } var run = runs.FirstOrDefault(); int index = tableCell.Paragraph.Runs.IndexOf(run); CT_RPr oldStyle = tableCell.Paragraph.Runs[index].GetCTR().rPr; DealSurlusRun(tableCell.Paragraph, run, validDouble); index = tableCell.Paragraph.Runs.IndexOf(run); //int num = 0; //if (index >= 1) //{ // var frontRun = tableCell.Paragraph.Runs[index - 1]; // if (frontRun.Text.Contains(validDouble)) // { // tableCell.Paragraph.RemoveRun(index - 1); // num += 1; // } //} //var afterRun = tableCell.Paragraph.Runs[index + 1 - num]; //if (afterRun.Text.TrimStart().StartsWith("}")) //{ // tableCell.Paragraph.RemoveRun(index + 1 - num); //} int rowIndex = tableCell.RowIndex; var rowPr = tableCell.Table.GetRow(tableCell.RowIndex).GetCTRow().trPr; var cellPr = tableCell.Cell.GetCTTc().tcPr; for (var i = 0; i < list.Count(); i++) { DynamicEntity entity = newList[i]; //if (entity.IsEntityProperty(propertyName.Trim()) == false) continue; object value = entity.GetPropertyValue(propertyName.Trim(), false); if (value == null) { value = string.Empty; } if (i == 0) { tableCell.Paragraph.RemoveRun(index); XWPFRun newRun = tableCell.Paragraph.CreateRun(); if (value != null) { if (value is byte[]) { byte[] bytes = value as byte[]; using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { newRun.AddPicture(ms, (int)PictureType.PNG, "test.png", NPOI.Util.Units.ToEMU(100), NPOI.Util.Units.ToEMU(100)); ms.Close(); } } else { newRun.SetText(value.ToString()); } } rowIndex += 1; continue; } XWPFTableRow row = tableCell.Table.GetRow(rowIndex); if (row == null) { row = tableCell.Table.CreateRow(); row.GetCTRow().trPr = rowPr; } XWPFTableCell cell = row.GetCell(tableCell.CellIndex); var cells = row.GetTableCells(); if (cells != null && cells.Count == 1) { string sdasd = string.Empty; XWPFTableRow newRow = tableCell.Table.CreateRow(); newRow.GetCTRow().trPr = rowPr; tableCell.Table.AddRow(newRow, rowIndex); tableCell.Table.RemoveRow(rowIndex + 2); cell = newRow.GetCell(tableCell.CellIndex); newRow.GetCell(0).SetText(rowIndex.ToString()); newRow.GetCell(0).GetCTTc().AddNewTcPr(); newRow.GetCell(0).GetCTTc().tcPr = cellPr; } if (cell == null) { continue; } if (value != null) { //cell.SetText(value.ToString()); if (cell.Paragraphs == null || cell.Paragraphs.Count == 0) { cell.AddParagraph(); } cell.Paragraphs[0].RemoveRun(0); XWPFRun newRun = cell.Paragraphs[0].CreateRun(); if (value is byte[]) { byte[] bytes = value as byte[]; using (MemoryStream ms = new MemoryStream(bytes, 0, bytes.Length)) { newRun.AddPicture(ms, (int)PictureType.PNG, "test.png", NPOI.Util.Units.ToEMU(100), NPOI.Util.Units.ToEMU(100)); ms.Close(); } } else { newRun.SetText(value.ToString()); } newRun.GetCTR().rPr = oldStyle; //XWPFRun newRun = cell.AddParagraph().CreateRun(); //newRun.SetText(value.ToString()); //newRun.GetCTR().rPr = oldStyle; } cell.GetCTTc().AddNewTcPr(); cell.GetCTTc().tcPr = cellPr; rowIndex += 1; } }
private void NPOITestFillData(string file) { #region 读取Word XWPFDocument doc; using (FileStream fileread = File.OpenRead(file)) { doc = new XWPFDocument(fileread); } #endregion List <string>[] data = new List <string> [3]; #region 组织填充数据 List <string> a = new List <string>(); List <string> b = new List <string>(); List <string> c = new List <string>(); a.Add("1.1"); a.Add("1.2"); a.Add("1.3"); a.Add("1.4"); a.Add("1.5"); a.Add("1.6"); a.Add("1.7"); b.Add("2.1"); b.Add("2.2"); b.Add("2.3"); b.Add("2.4"); b.Add("2.5"); b.Add("2.6"); c.Add("3.1"); c.Add("3.2"); c.Add("3.3"); c.Add("3.4"); c.Add("3.5"); c.Add("3.6"); c.Add("3.7"); c.Add("3.8"); c.Add("3.9"); data[0] = a; data[1] = b; data[2] = c; #endregion WordTable wt = new WordTable(data); wt.CaptionLineCount = 2; //标题行数 XWPFTable table = LocationTable(doc, "本年发生的非同一控制下企业合并情况"); if (wt.ObjectData != null) { for (int i = 0; i < wt.ObjectData.Length + wt.CaptionLineCount; i++) { if (i >= wt.CaptionLineCount) { XWPFTableRow row; string[] rowdata = wt.ObjectData[i - wt.CaptionLineCount].ToArray <string>(); if (i < table.Rows.Count) { row = table.GetRow(i); row.GetCTRow().AddNewTrPr().AddNewTrHeight().val = 397; row.GetCTRow().trPr.GetTrHeightArray(0); for (int n = 0; n < rowdata.Length; n++) { XWPFTableCell cell = row.GetCell(n); //模板中的单元格少时,接收数据将会部分丢失 //也可以在下边if后添加else在该行后补充单元格 //按接收数据循环,所以单元格数多于接收数据时不需要另做处理,该行后边的部分单元格无法补填充 if (cell != null) { //SetText是追加内容,所以要先删除单元格内容(删除单元格内所有段落)再写入 for (int p = 0; p < cell.Paragraphs.Count; p++) { cell.RemoveParagraph(p); } for (int t = 0; t < cell.Tables.Count; t++) { //表格删除 //cell.RemoveTable(t); } cell.SetText(rowdata[n]); } } } else { //添加新行 //row = table.InsertNewTableRow(table.Rows.Count - 1); row = new XWPFTableRow(new CT_Row(), table); row.GetCTRow().AddNewTrPr().AddNewTrHeight().val = 100; table.AddRow(row); for (int n = 0; n < rowdata.Length; n++) { XWPFTableCell cell = row.CreateCell(); CT_Tc tc = cell.GetCTTc(); CT_TcPr pr = tc.AddNewTcPr(); tc.GetPList()[0].AddNewR().AddNewT().Value = rowdata[n]; } } } } } #region 保存Word FileStream filewrite = new FileStream(file, FileMode.Create, FileAccess.Write); try { doc.Write(filewrite); } catch (Exception x) { lblStatus.Text = x.Message; } finally { filewrite.Close(); } #endregion }