public void getRenderedCell(Marker input, StyleConfig config, XWPFTableRow parentRow) { StyleConfig markerStyle = (StyleConfig)config.Clone(); XWPFTableCell tableCellContainer = parentRow.CreateCell(); XWPFParagraph cellContents; switch (input) { case THMarker tHMarker: markerStyle.isBold = true; cellContents = tableCellContainer.AddParagraph(markerStyle); cellContents.SetBidi(configDocx.rightToLeft); foreach (Marker marker in input.Contents) { RenderMarker(marker, markerStyle, cellContents); } break; case THRMarker tHRMarker: markerStyle.isAlignRight = true; markerStyle.isBold = true; cellContents = tableCellContainer.AddParagraph(markerStyle); cellContents.SetBidi(configDocx.rightToLeft); foreach (Marker marker in input.Contents) { RenderMarker(marker, markerStyle, cellContents); } break; case TCMarker tCMarker: cellContents = tableCellContainer.AddParagraph(markerStyle); cellContents.SetBidi(configDocx.rightToLeft); foreach (Marker marker in input.Contents) { RenderMarker(marker, markerStyle, cellContents); } break; case TCRMarker tCRMarker: markerStyle.isAlignRight = true; cellContents = tableCellContainer.AddParagraph(markerStyle); cellContents.SetBidi(configDocx.rightToLeft); foreach (Marker marker in input.Contents) { RenderMarker(marker, markerStyle, cellContents); } break; default: break; } }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); XWPFParagraph para = doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("Title1"); para.BorderTop = Borders.Thick; para.FillBackgroundColor = "EEEEEE"; para.FillPattern = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe; XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); // Use this instead of doc.CreateParagraph. XWPFRun r1 = p1.CreateRun(); r1.SetText("The quick brown fox"); r1.IsBold = true; r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.TextPosition = 100; c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("SimpleTableNPOI.docx", FileMode.Create); doc.Write(out1); out1.Close(); }
public static XWPFParagraph AddParagraph(this XWPFTableCell cell, StyleConfig styles) { XWPFParagraph para = cell.AddParagraph(); para.Alignment = (styles.isAlignRight ? ParagraphAlignment.RIGHT : ParagraphAlignment.LEFT); return(para); }
public static XWPFParagraph CreateParagraph(this XWPFTableCell aCell) { XWPFParagraph pIO = aCell.Paragraphs.Count > 0 ? aCell.Paragraphs[0] : aCell.AddParagraph(); pIO.Alignment = ParagraphAlignment.LEFT; return(pIO); }
static void Main(string[] args) { // Create a new document from scratch XWPFDocument doc = new XWPFDocument(); XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph XWPFRun r1 = p1.CreateRun(); r1.SetText("This is test table contents"); r1.IsBold = true; r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.SetTextPosition(100); c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream("data/Format Table in Document.docx", FileMode.Create); doc.Write(out1); out1.Close(); }
private void AddCell(XWPFTableCell cell, string text) { XWPFParagraph paragraph = cell.AddParagraph(); XWPFRun run = paragraph.CreateRun(); run.SetText(text); run.FontFamily = "Times New Roman"; run.FontSize = 12; }
private void setCell(XWPFTableCell cell, string cellText) { XWPFParagraph pIO = cell.AddParagraph(); pIO.Alignment = ParagraphAlignment.CENTER; XWPFRun rIO = pIO.CreateRun(); rIO.FontFamily = "宋体"; rIO.FontSize = 12; rIO.SetText(cellText); }
private static void CreateConverText(XWPFTableCell cell, string text, int fontSize) { cell.RemoveParagraph(0); XWPFParagraph paragraph = cell.AddParagraph(); paragraph.Alignment = ParagraphAlignment.CENTER; XWPFRun run = paragraph.CreateRun(); run.SetText(text); run.SetFontFamily("黑体", FontCharRange.None); run.FontSize = fontSize; }
void SetRedFontCell(XWPFTableCell cell, string value) { XWPFParagraph pIO = cell.AddParagraph(); pIO.Alignment = ParagraphAlignment.CENTER; XWPFRun rIO = pIO.CreateRun(); rIO.SetColor("red"); rIO.SetText(value); SetAlign(cell); cell.RemoveParagraph(0); }
private void AppendParagraph(XWPFTableCell cell, String cellText) { XWPFParagraph paragraph = cell.AddParagraph(); XWPFRun run = paragraph.CreateRun(); run.FontFamily = "宋体"; //设置字体大小 run.FontSize = 11; //字体是否加粗,这里加粗了 run.SetBold(true); run.SetText(cellText); }
private static void CreateText(XWPFTableCell cell, string text, bool isBold) { cell.RemoveParagraph(0); XWPFParagraph paragraph = cell.AddParagraph(); paragraph.Alignment = ParagraphAlignment.LEFT; XWPFRun run = paragraph.CreateRun(); run.SetText(text); run.SetFontFamily("宋体", FontCharRange.None); if (isBold) { run.IsBold = true; } run.FontSize = 11; }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); XWPFParagraph para = doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("Title1"); para.BorderTop = Borders.Thick; para.FillBackgroundColor = "EEEEEE"; para.FillPattern = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe; XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("EXAMPLE OF TABLE"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph XWPFRun r1 = p1.CreateRun(); r1.SetText("The quick brown fox"); r1.IsBold = true; r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); r1.TextPosition = 100; c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); var r2 = table.GetRow(2).GetCell(0).AddParagraph().CreateRun(); var widthEmus = (int)(400.0 * 9525); var heightEmus = (int)(300.0 * 9525); using (FileStream picData = new FileStream("image/HumpbackWhale.jpg", FileMode.Open, FileAccess.Read)) { r2.AddPicture(picData, (int)PictureType.JPEG, "image1", widthEmus, heightEmus); } using (FileStream fs = new FileStream("simpleTable.docx", FileMode.Create)) { doc.Write(fs); } }
private static XWPFTableCell SetCell(XWPFTableCell cell, string text, int width, string color = "", bool isCenter = true, int fontSize = 0, bool isBold = false) { CT_Tc cttc = cell.GetCTTc(); CT_TcPr ctpr = cttc.AddNewTcPr(); //垂直居中 ctpr.AddNewVAlign().val = ST_VerticalJc.center; //设置单元格列宽 ctpr.tcW = new CT_TblWidth(); ctpr.tcW.w = width.ToString(); ctpr.tcW.type = ST_TblWidth.dxa; //设置单元格背景色 if (!string.IsNullOrEmpty(color)) { cell.SetColor(color); } //设置文本 text = text == "PRI" ? "Y" : text; text = text == "YES" ? "Y" : text; text = text == "NO" ? "N" : text; text = text == "CURRENT_TIMESTAMP" ? "now()" : text; cell.RemoveParagraph(0); XWPFParagraph gp = cell.AddParagraph(); if (isCenter) { //水平居中 gp.Alignment = ParagraphAlignment.CENTER; } //文字格式 gp.Style = "NoSpacing"; XWPFRun gr = gp.CreateRun(); if (fontSize > 0) { gr.FontSize = fontSize; } gr.IsBold = isBold; gr.SetText(text); return(cell); }
private static void CopyCell(XWPFTableCell templateCell, XWPFTableCell cell) { cell.SetColor(templateCell.GetColor()); CT_TcBorders templateBorders = templateCell.GetCTTc().tcPr.tcBorders; if (templateBorders != null) { CT_TcBorders borders = cell.GetCTTc().AddNewTcPr().AddNewTcBorders(); WordGenerator.CopyBorders(templateBorders, borders); } for (int i = 0; i < cell.Paragraphs.Count; i++) { cell.RemoveParagraph(0); } foreach (XWPFParagraph templateph in templateCell.Paragraphs) { XWPFParagraph ph = cell.AddParagraph(); WordGenerator.CopyParagraph(templateph, ph); } }
private static void SaveWordDoc(string pFfName) { try { XWPFDocument doc = new XWPFDocument(); XWPFParagraph para = doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("FileFormat"); para.FillBackgroundColor = "EEEEEE"; para.FillPattern = NPOI.OpenXmlFormats.Wordprocessing.ST_Shd.diagStripe; XWPFTable table = doc.CreateTable(3, 3); table.GetRow(1).GetCell(1).SetText("File Format Developer Guide"); XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); XWPFRun r1 = p1.CreateRun(); r1.SetText("NPOI - DOCX"); r1.IsBold = true; r1.FontFamily = "Courier"; r1.SetUnderline(UnderlinePatterns.DotDotDash); // r1.SetTextPosition(100); c1.SetColor("FF0000"); table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream(pFfName, FileMode.Create); doc.Write(out1); out1.Close(); } catch (Exception) { throw; } }
public static void CreateFileByTemplate(List <TaskResultModel> resultList, string tempFile, string saveFile, string taskId) { using (FileStream stream = File.OpenRead(tempFile)) { XWPFDocument doc = new XWPFDocument(stream); //遍历段落 foreach (var para in doc.Paragraphs) { } //遍历表格 List <string> picFormat = new List <string>(); picFormat.Add(".jpeg"); picFormat.Add(".jpg"); picFormat.Add(".png"); picFormat.Add(".bmp"); picFormat.Add(".tiff"); picFormat.Add(".svg"); picFormat.Add(".gif"); //picFormat.Add(""); for (int index = 0; index < doc.Tables.Count; index++) { XWPFTable table = doc.Tables[index]; if (index == 2) { int num = table.Rows.Count - 3 - resultList.Count;//总行数-文字描述的行数-测试项目的数量 = 要删除,或者增加的单元格行数 if (num >= 0) { for (int i = 0; i < num; i++) { table.RemoveRow(2 + resultList.Count); } } else//如何测试项目大于当前文档已有的行数,需要进行添加行的操作 { for (int i = num; i < 0; i++) { NPOI.OpenXmlFormats.Wordprocessing.CT_Row nr = new NPOI.OpenXmlFormats.Wordprocessing.CT_Row(); XWPFTableRow mr = new XWPFTableRow(nr, table);//创建行 //mr.AddNewTableCell(); //mr.AddNewTableCell(); //mr.AddNewTableCell(); //mr.AddNewTableCell(); //mr.AddNewTableCell(); //mr.AddNewTableCell(); mr.CreateCell(); mr.CreateCell(); mr.CreateCell(); mr.CreateCell(); mr.CreateCell(); mr.CreateCell(); table.AddRow(mr, table.Rows.Count - 1); //XWPFTableRow newRow = table.GetRow(2); //for (int j = 0; j < newRow.GetTableCells().Count; j++) //{ // XWPFParagraph par = doc.CreateParagraph(); // XWPFRun run = par.CreateRun(); // run.SetText(""); // newRow.GetCell(j).SetParagraph(par); //} //table.AddRow(newRow, table.Rows.Count - 1); } } int item = 0; for (int i = 0; i < table.Rows.Count; i++) { if (i >= 2 && i < table.Rows.Count - 1) { List <XWPFTableCell> columnsList = table.Rows[i].GetTableCells(); int columns = columnsList.Count; for (int col = 0; col < columns; col++) { if (col == 0) //序号 列 { if (columnsList[col].GetText() != "") { columnsList[col].Paragraphs[0].RemoveRun(0); } columnsList[col].SetText((item + 1).ToString()); string test = columnsList[col].GetText(); //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); //run.SetText((item + 1).ToString()); //table.Rows[i].GetCell(col).SetParagraph(par); } else if (col == 1) //检验项目 { //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); //run.SetText(resultList[item].indicatorName); //table.Rows[i].GetCell(col).SetParagraph(par); columnsList[col].SetText(resultList[item].indicatorName); } else if (col == 2)//技术标准要求 { //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); //run.SetText(resultList[item].indicatorDesc); //table.Rows[i].GetCell(col).SetParagraph(par); columnsList[col].SetText(resultList[item].indicatorDesc); } else if (col == 3) { //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); //run.SetText(resultList[item].indicatorId.ToString()); //table.Rows[i].GetCell(col).SetParagraph(par); columnsList[col].SetText(resultList[item].indicatorId.ToString()); } else if (col == 4) { //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); //run.SetText(resultList[item].taskRecord); //table.Rows[i].GetCell(col).SetParagraph(par); columnsList[col].SetText(resultList[item].taskRecord); } else if (col == 5) { //XWPFParagraph par = doc.CreateParagraph(); //XWPFRun run = par.CreateRun(); if (resultList[item].taskResult == 2) { //run.SetText("合格"); columnsList[col].SetText("合格"); } else { //run.SetText("不合格"); columnsList[col].SetText("不合格"); } //table.Rows[i].GetCell(col).SetParagraph(par); } } item++; } } } if (index == 3) { XWPFTableCell Cell = table.GetRow(table.Rows.Count - 1).GetCell(0);//获取到进行图片插入的单元格 XWPFParagraph p = Cell.AddParagraph(); XWPFRun run = p.CreateRun(); foreach (var item in resultList) { if (item.attachment != "") { string path = item.attachment; string[] picArr = path.Split(new char[] { ';' }); foreach (var str in picArr) { string strTask = string.Format("/{0}/", taskId); string fileName = str.Replace(strTask, ""); foreach (var picItem in picFormat) { //GetFTPFilePath(); if (str.Contains(picItem)) { GetFTPFilePath(str); string localFilePath = Application.StartupPath + @"\temp" + str.Replace("/", @"\"); System.Drawing.Image image = System.Drawing.Image.FromFile(localFilePath); using (FileStream img = new FileStream(localFilePath, FileMode.Open, FileAccess.Read)) { PictureType picType = PictureType.PNG; switch (picItem) { case ".png": picType = PictureType.PNG; break; case ".jpg": picType = PictureType.JPEG; break; case ".jpeg": picType = PictureType.JPEG; break; case ".bmp": picType = PictureType.BMP; break; default: break; } run.AddPicture(img, (int)picType, fileName, NPOI.Util.Units.ToEMU(image.Width), NPOI.Util.Units.ToEMU(image.Height)); } //img.Close(); } } } } //string localFilePath = Application.StartupPath + @"\temp" + remoteFilePath.Replace("/", @"\"); } } } string fileRename = string.Format("\\航科院安保设施实验室_测试报告{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmss")); FileStream out1 = new FileStream(saveFile + fileRename, FileMode.Create, FileAccess.Write); doc.Write(out1); out1.Close(); } }
public void generateWork(Invoce.Entity.Invoce invoce) { XWPFDocument doc = new XWPFDocument(); XWPFTable table = doc.CreateTable(11, 1); table.SetLeftBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); table.SetRightBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); table.SetTopBorder(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); XWPFTableCell cellFIO = table.GetRow(0).GetCell(0); XWPFTableCell cellStreetBuild = table.GetRow(1).GetCell(0); XWPFTableCell cellCityAndIndex = table.GetRow(2).GetCell(0); XWPFTableCell cellCountry = table.GetRow(3).GetCell(0); XWPFTableCell cellEmail = table.GetRow(4).GetCell(0); XWPFTableCell cellNumber = table.GetRow(5).GetCell(0); XWPFTableCell cellDescription = table.GetRow(6).GetCell(0); XWPFTableCell cellRaid = table.GetRow(7).GetCell(0); XWPFTableCell cellSignature = table.GetRow(8).GetCell(0); XWPFTableCell cellHelper = table.GetRow(9).GetCell(0); XWPFTableCell cellFIOEnd = table.GetRow(10).GetCell(0); cellFIO.SetText(invoce.GetFIO()); cellStreetBuild.SetText(invoce.GetStreetBuild()); cellCityAndIndex.SetText(invoce.GetCityAndIndex()); cellCountry.SetText(invoce.GetCountry()); cellEmail.SetText(invoce.GetEmail()); cellNumber.SetText("+" + invoce.GetTelephoneNumber()); cellDescription.SetText(invoce.GetDescription()); cellRaid.SetText(invoce.GetRaid()); cellSignature.SetText(invoce.GetSignature()); cellHelper.SetText("Signature Data"); cellFIOEnd.SetText(invoce.GetFIO()); cellFIO.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF");///Убирает нижний бордер cellStreetBuild.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellCityAndIndex.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellCountry.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellEmail.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellNumber.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellRaid.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellSignature.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellFIOEnd.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellDescription.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); cellHelper.SetBorderBottom(XWPFBorderType.SINGLE, 3, 3, "#FFFFFF"); XWPFParagraph p1 = cellRaid.AddParagraph(); //XSSFCellStyle raidStyle = (HSSFCellStyle)table.CreateCellStyle();//don't use doc.CreateParagraph //XWPFRun r1 = p1.CreateRun(); //cellRaid. //r1.SetText("This is test table contents"); //r1.FontFamily = "Courier"; //r1.SetUnderline(UnderlinePatterns.DotDotDash); //r1.SetTextPosition(100); //r1.set //r1.SetColor("FF0000"); //table.GetRow(2).GetCell(2).SetText("only text"); FileStream out1 = new FileStream( this._wordFile.GetWritePath(), FileMode.Create ); doc.Write(out1); out1.Close(); }
/// <summary> /// 表格中查找替换 /// </summary> /// <param name="CurCell"></param> /// <param name="PMember"></param> /// <param name="PResumes"></param> /// <param name="PRelations"></param> /// <param name="PPrizePunishs"></param> /// <param name="PAppraises"></param> private void ReplaceKeyInCell(XWPFDocument WDoc, XWPFTableCell CurCell, Lib.MemberInfoEntity PMember, List <MemberResume> PResumes, List <MemberRelations> PRelations, List <MemberPrizePunish> PPrizePunishs, List <MemberAppraise> PAppraises) { for (int i = 0; i < CurCell.Paragraphs.Count; i++) { XWPFParagraph CurPara = CurCell.Paragraphs[i]; //头像 if (CurPara.ParagraphText.Trim().Contains("[HeadImage]")) { while (CurPara.Runs.Count > 0) { CurPara.RemoveRun(0); } if (_FixedDocVM.HeadImage != null && _FixedDocVM.HeadImage.StreamSource != null) { XWPFRun imageCellRun = CurPara.CreateRun(); //必须将流位置指针设置到开始处,否则显示不出来。 _FixedDocVM.HeadImage.StreamSource.Position = 0; var picID = WDoc.AddPictureData(_FixedDocVM.HeadImage.StreamSource, (int)PictureType.PNG); CreatePictureInLine(imageCellRun, picID, 100, 140); // CreatePictureWithAnchor(imageCellRun, picID, 90, 120); } break; } //简历 if (CurPara.ParagraphText.Trim().Contains("[Resume]")) { if (PResumes != null && PResumes.Count > 0) { for (int pr = 0; pr < PResumes.Count; pr++) { string EndDateStr = PResumes[pr].EndDate.ToString("yyy.MM"); if (PResumes[pr].EndDate.Year == 1) { EndDateStr = "今"; } string tempValue = $"{PResumes[pr].BeginDate:yyyy.MM}--{EndDateStr} {PResumes[pr].Content}"; if (pr == 0) { CurPara.ReplaceText("[Resume]", tempValue); } else { XWPFParagraph NewParagraph = CurCell.AddParagraph(); XWPFRun NewRun = NewParagraph.CreateRun(); NewRun.FontFamily = CurPara.Runs[0].FontFamily; NewRun.FontSize = CurPara.Runs[0].FontSize; NewRun.SetText(tempValue); } } } else { while (CurPara.Runs.Count > 0) { CurPara.RemoveRun(0); } } break; } //奖情惩况 if (CurPara.ParagraphText.Trim().Contains("[PrizePunish]")) { if (PPrizePunishs != null && PPrizePunishs.Count > 0) { for (int pr = 0; pr < PPrizePunishs.Count; pr++) { string tempValue = $"{PPrizePunishs[pr].OccurDate:yyyy.MM} {PPrizePunishs[pr].PrizrOrPunishUnit} {PPrizePunishs[pr].PrizrOrPunishName}"; if (pr == 0) { CurPara.ReplaceText("[PrizePunish]", tempValue); } else { XWPFParagraph NewParagraph = CurCell.AddParagraph(); XWPFRun NewRun = NewParagraph.CreateRun(); NewRun.FontFamily = CurPara.Runs[0].FontFamily; NewRun.FontSize = CurPara.Runs[0].FontSize; NewRun.SetText(tempValue); } } } else { while (CurPara.Runs.Count > 0) { CurPara.RemoveRun(0); } } break; } //近三年考核情况 if (CurPara.ParagraphText.Trim().Contains("[Appraise]")) { if (PAppraises != null && PAppraises.Count > 0) { for (int pr = 0; pr < PAppraises.Count; pr++) { string tempValue = $"{PAppraises[pr].Year:yyyy} {PAppraises[pr].Result}"; if (pr == 0) { CurPara.ReplaceText("[Appraise]", tempValue); } else { XWPFParagraph NewParagraph = CurCell.AddParagraph(); XWPFRun NewRun = NewParagraph.CreateRun(); NewRun.FontFamily = CurPara.Runs[0].FontFamily; NewRun.FontSize = CurPara.Runs[0].FontSize; NewRun.SetText(tempValue); } } } else { while (CurPara.Runs.Count > 0) { CurPara.RemoveRun(0); } } break; } //主要社会关系 if (CurPara.ParagraphText.Trim().Contains("[Relations")) { string tempValue = ""; for (int p = 1; p <= 7; p++) { for (int k = 0; k <= 4; k++) { if (CurPara.ParagraphText.Trim().Equals($"[Relations{p}{k}]")) { if (PRelations != null && PRelations.Count >= p) { switch (k) { case 0: tempValue = $"{PRelations[p - 1].Relation}"; break; case 1: tempValue = $"{PRelations[p - 1].Name}"; break; case 2: tempValue = $"{PRelations[p - 1].Birthday:yyyy.MM}"; break; case 3: tempValue = $"{PRelations[p - 1].PoliticalStatus}"; break; case 4: tempValue = $"{PRelations[p - 1].UnitName} {PRelations[p - 1].Role} {PRelations[p - 1].Remark}"; break; } } CurPara.ReplaceText($"[Relations{p}{k}]", tempValue == null ? "" : tempValue.Trim()); break; } } } } //基本信息 { Type t = PMember.GetType(); PropertyInfo[] pi = t.GetProperties(); foreach (PropertyInfo p in pi) { if (CurPara.ParagraphText.Trim().Contains($"[{p.Name}]")) { string CurValue = p.GetValue(PMember)?.ToString(); if (string.IsNullOrWhiteSpace(CurValue)) { CurValue = ""; } else { DateTime tempDate; switch (p.Name) { case "Birthday": tempDate = DateTime.Parse(CurValue); CurValue = $"{tempDate:yyyy.MM}"; XWPFParagraph NewParagraph = CurCell.AddParagraph(); NewParagraph.Alignment = ParagraphAlignment.CENTER; XWPFRun NewRun = NewParagraph.CreateRun(); NewRun.FontFamily = CurPara.Runs[0].FontFamily; NewRun.FontSize = CurPara.Runs[0].FontSize; NewRun.SetText($"({DateTime.Now.Year - tempDate.Year}岁)"); break; case "JoinCPC": tempDate = DateTime.Parse(CurValue); CurValue = $"{tempDate:yyyy.MM}"; break; case "BeginWork": tempDate = DateTime.Parse(CurValue); CurValue = $"{tempDate:yyyy.MM}"; break; } } CurPara.ReplaceText("[" + p.Name + "]", CurValue); break; } } } } }
/// <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; } }
public void Word(Subject subj) { XWPFDocument doc = new XWPFDocument(); #region ЧНУ імені Петра Могили XWPFParagraph para = doc.CreateParagraph(); XWPFRun r0 = para.CreateRun(); r0.SetText("ЧНУ імені Петра могили"); para.Alignment = ParagraphAlignment.CENTER; r0.FontSize = 16; r0.IsBold = true; #endregion #region Направлення №1234 para = doc.CreateParagraph(); r0 = para.CreateRun(); r0.SetText("Направлення № 123 на перескладання екзамену (заліку)"); para.Alignment = ParagraphAlignment.CENTER; r0.FontSize = 16; r0.IsBold = true; #endregion #region Імя студента та назва предмету para = doc.CreateParagraph(); para.Alignment = ParagraphAlignment.BOTH; r0 = para.CreateRun(); XWPFRun r1 = para.CreateRun(); XWPFRun r2 = para.CreateRun(); XWPFRun r3 = para.CreateRun(); r0.FontSize = 14; r1.FontSize = 14; r2.FontSize = 14; r3.FontSize = 14; r0.SetText("З дисципліни "); r1.SetText(subj.Name); r1.SetUnderline(UnderlinePatterns.Single); r2.SetText(" видане студенту "); r3.SetText(subj.Student.Name); r3.SetUnderline(UnderlinePatterns.Single); r3.AddCarriageReturn(); #endregion #region Група para = doc.CreateParagraph(); r0 = para.CreateRun(); r1 = para.CreateRun(); r2 = para.CreateRun(); r3 = para.CreateRun(); XWPFRun r4 = para.CreateRun(); r0.FontSize = 14; r1.FontSize = 14; r2.FontSize = 14; r3.FontSize = 14; r4.FontSize = 14; r0.SetText("Курсу "); r1.SetText(subj.Student.Group.NameGroup[0].ToString()); r1.SetUnderline(UnderlinePatterns.Single); r2.SetText(" групи "); r3.SetText(subj.Student.Group.NameGroup); r3.SetUnderline(UnderlinePatterns.Single); r4.SetText(" факультету комп'ютерних наук"); #endregion #region Викладач XWPFTable table = doc.CreateTable(4, 5); table.SetBottomBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.SetLeftBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.SetRightBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.SetTopBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.SetInsideHBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.SetInsideVBorder(XWPFTable.XWPFBorderType.NONE, table.InsideHBorderSize, table.InsideHBorderSpace, "FFFFFF"); table.Width = 5000; XWPFTableCell c1 = table.GetRow(0).GetCell(0); XWPFParagraph p1 = c1.AddParagraph(); //don't use doc.CreateParagraph r0 = p1.CreateRun(); r1 = p1.CreateRun(); r0.FontSize = 14; r1.FontSize = 14; r0.SetText("Викладач "); r1.SetText(subj.Lecture); r1.SetUnderline(UnderlinePatterns.Single); XWPFTableCell c2 = table.GetRow(0).GetCell(1); XWPFParagraph p2 = c2.AddParagraph(); //don't use doc. r0 = p2.CreateRun(); r0.FontSize = 14; r0.SetText("Підпис ______________"); p2.Alignment = ParagraphAlignment.RIGHT; #endregion #region Дата XWPFTableCell c3 = table.GetRow(1).GetCell(0); XWPFParagraph p3 = c3.AddParagraph(); //don't use doc.CreateParagraph r0 = p3.CreateRun(); r1 = p3.CreateRun(); r0.FontSize = 14; r1.FontSize = 14; r0.SetText("Дата видачі "); r1.SetText(DateTime.Now.ToShortDateString()); r1.SetUnderline(UnderlinePatterns.Single); XWPFTableCell c4 = table.GetRow(1).GetCell(1); XWPFParagraph p4 = c4.AddParagraph(); //don't use doc. r0 = p4.CreateRun(); r0.FontSize = 14; r0.SetText("Дата складання ______________"); p4.Alignment = ParagraphAlignment.RIGHT; #endregion #region Оцінка XWPFTableCell c5 = table.GetRow(2).GetCell(0); XWPFParagraph p5 = c5.AddParagraph(); //don't use doc.CreateParagraph r0 = p5.CreateRun(); r0.FontSize = 14; r0.SetText("Оцінка _______________________"); XWPFTableCell c6 = table.GetRow(2).GetCell(1); XWPFParagraph p6 = c6.AddParagraph(); //don't use doc. r0 = p6.CreateRun(); r0.FontSize = 14; r0.SetText("Кількість балів сем. ______+______=________"); p6.Alignment = ParagraphAlignment.RIGHT; #endregion #region Декан XWPFTableCell c7 = table.GetRow(3).GetCell(0); XWPFParagraph p7 = c7.AddParagraph(); //don't use doc.CreateParagraph r0 = p7.CreateRun(); r0.FontSize = 14; r0.SetText("Дійсне до _____________"); p7.Alignment = ParagraphAlignment.CENTER; XWPFTableCell c8 = table.GetRow(3).GetCell(1); XWPFParagraph p8 = c8.AddParagraph(); //don't use doc. r0 = p8.CreateRun(); r0.FontSize = 14; r0.SetText("Декан _____________"); p8.Alignment = ParagraphAlignment.CENTER; #endregion FileStream out1 = new FileStream("E:\\simpleTable.docx", FileMode.Create); doc.Write(out1); out1.Close(); }
/// <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); }