/// <summary> /// 从中XML读取物理图信息 /// </summary> /// <returns> List</returns> public List <PhysicalDiagramInfo> GetPDInfo() { try { List <PhysicalDiagramInfo> PDList = new List <PhysicalDiagramInfo>(); XWPFDocument doc = InitXWPFDocument(); if (mTables == null) { mTables = GetTableInfo(); } PhysicalDiagramInfo pdInfo = new PhysicalDiagramInfo(); string pid = System.Guid.NewGuid().ToString(); pdInfo.Id = pid; pdInfo.Name = "所有数据"; PDList.Add(pdInfo); PhysicalDiagramInfo pd = new PhysicalDiagramInfo(); string pid1 = System.Guid.NewGuid().ToString(); pd.Id = pid1; pd.Name = "数据表"; pd.PhyParentId = pid; PDList.Add(pd); foreach (TableInfo t in mTables) { pd = new PhysicalDiagramInfo(); pd.Id = System.Guid.NewGuid().ToString(); pd.Name = t.Code; pd.IfEnd = true; pd.PhyParentId = pid1; PDList.Add(pd); } return(PDList); } catch (Exception ex) { throw ex; } }
public void TestSetBorderTop() { //new clean instance of paragraph XWPFDocument doc = new XWPFDocument(); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(ST_Border.none, EnumConverter.ValueOf <ST_Border, Borders>(p.BorderTop)); CT_P ctp = p.GetCTP(); CT_PPr ppr = ctp.pPr == null?ctp.AddNewPPr() : ctp.pPr; //bordi CT_PBdr bdr = ppr.AddNewPBdr(); CT_Border borderTop = bdr.AddNewTop(); borderTop.val = (ST_Border.@double); bdr.top = (borderTop); Assert.AreEqual(Borders.Double, p.BorderTop); p.BorderTop = (Borders.Single); Assert.AreEqual(ST_Border.single, borderTop.val); }
public void TestOverrideList() { //TODO: for now the try/catch block ensures loading/inclusion of CTNumLevel //for down stream Processing. //Ideally, we should find files that actually use overrides and test against those. //Use XWPFParagraph's GetNumStartOverride() in the actual tests XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Numbering.docx"); XWPFParagraph p = doc.Paragraphs[(18)]; XWPFNumbering numbering = doc.CreateNumbering(); bool ex = false; Assert.IsNull(p.GetNumStartOverride()); try { numbering.GetNum(p.GetNumID()).GetCTNum().GetLvlOverrideArray(1); } catch (ArgumentOutOfRangeException) { ex = true; } Assert.IsTrue(ex); }
public void TestLoadFootnotesOnce() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("Bug54849.docx"); IList <XWPFFootnote> footnotes = doc.GetFootnotes(); int hits = 0; foreach (XWPFFootnote fn in footnotes) { foreach (IBodyElement e in fn.BodyElements) { if (e is XWPFParagraph) { String txt = ((XWPFParagraph)e).Text; if (txt.IndexOf("Footnote_sdt") > -1) { hits++; } } } } Assert.AreEqual(1, hits, "Load footnotes once"); }
public void TestFieldRuns() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("FldSimple.docx"); IList <XWPFParagraph> ps = doc.Paragraphs; Assert.AreEqual(1, ps.Count); XWPFParagraph p = ps[0]; Assert.AreEqual(1, p.Runs.Count); Assert.AreEqual(1, p.IRuns.Count); XWPFRun r = p.Runs[0]; Assert.AreEqual(typeof(XWPFFieldRun), r.GetType()); XWPFFieldRun fr = (XWPFFieldRun)r; Assert.AreEqual(" FILENAME \\* MERGEFORMAT ", fr.FieldInstruction); Assert.AreEqual("FldSimple.docx", fr.Text); Assert.AreEqual("FldSimple.docx", p.Text); }
public void TestAddParagraph() { XWPFDocument doc = XWPFTestDataSamples.OpenSampleDocument("sample.docx"); Assert.AreEqual(3, doc.Paragraphs.Count); XWPFParagraph p = doc.CreateParagraph(); Assert.AreEqual(p, doc.Paragraphs[(3)]); Assert.AreEqual(4, doc.Paragraphs.Count); Assert.AreEqual(3, doc.GetParagraphPos(3)); Assert.AreEqual(3, doc.GetPosOfParagraph(p)); //CTP ctp = p.CTP; //XWPFParagraph newP = doc.GetParagraph(ctp); //Assert.AreSame(p, newP); //XmlCursor cursor = doc.Document.Body.GetPArray(0).newCursor(); //XWPFParagraph cP = doc.InsertNewParagraph(cursor); //Assert.AreSame(cP, doc.Paragraphs[(0)]); //Assert.AreEqual(5, doc.Paragraphs.Count); }
public void integration() { XWPFDocument doc = new XWPFDocument(); XWPFParagraph p1 = doc.CreateParagraph(); XWPFRun r1 = p1.CreateRun(); r1.SetText("Lorem ipsum dolor sit amet."); doc.IsTrackRevisions = (true); MemoryStream out1 = new MemoryStream(); doc.Write(out1); MemoryStream inputStream = new MemoryStream(out1.ToArray()); XWPFDocument document = new XWPFDocument(inputStream); inputStream.Close(); Assert.IsTrue(document.IsTrackRevisions); }
static void Main(string[] args) { if (args.Length != 2) { return; } string src = args[0]; string target = args[1]; RunMode mode = RunMode.Excel; if (src.Contains(".docx")) { mode = RunMode.Word; } if (mode == RunMode.Excel) { Stream rfs = File.OpenRead(src); IWorkbook workbook = new XSSFWorkbook(rfs); rfs.Close(); using (FileStream fs = File.Create(target)) { workbook.Write(fs); } } else { Stream rfs = File.OpenRead(src); XWPFDocument workbook = new XWPFDocument(rfs); rfs.Close(); using (FileStream fs = File.Create(target)) { workbook.Write(fs); } } }
private void zapiszPlikWord2(string nazwaPlikuWord, string plikJpg) { var newFile2 = sciezka + nazwaPlikuWord + ".docx"; using (var fs = new FileStream(newFile2, FileMode.Create, FileAccess.Write)) { //var wDoc = new XWPFDocument(); //var bytes = File.ReadAllBytes(sciezkaplikuJpg + plikJpg+".jpeg"); //wDoc.AddPictureData(bytes, (int)NPOI.SS.UserModel.PictureType.JPEG); XWPFDocument doc = new XWPFDocument(); var p0 = doc.CreateParagraph(); p0.Alignment = ParagraphAlignment.CENTER; XWPFRun r0 = p0.CreateRun(); var bytes = File.ReadAllBytes(sciezkaplikuJpg + plikJpg + ".jpeg"); Stream stream = new System.IO.MemoryStream(bytes); r0.AddPicture(stream, (int)NPOI.SS.UserModel.PictureType.JPEG, "image1", Units.ToEMU(700), Units.ToEMU(800)); doc.Write(fs); } }
/// <summary> /// 测试书签 /// 不知道书签咋用。用其他方法查找指定表 /// </summary> /// <param name="file"></param> private void NPOITestBookMark(string file) { #region 读取Word XWPFDocument doc; using (FileStream fileread = File.OpenRead(file)) { doc = new XWPFDocument(fileread); } #endregion //XWPFTable table = LocationTable(doc, "本年发生的非同一控制下企业合并情况"); XWPFTable table = LocationTableByBookMark(doc, "本年发生的非同一控制下企业合并情况"); //CT_Bookmark bm = new CT_Bookmark(); //CT_P p = doc.Document.body.AddNewP(); //List<ParagraphItemsChoiceType> x = new List<ParagraphItemsChoiceType>(); //x = p.ItemsElementName; //CT_TrPr tp = new CT_TrPr(); //CT_OnOff oo = new CT_OnOff(); }
public void TestGetUsedStyles() { XWPFDocument sampleDoc = XWPFTestDataSamples.OpenSampleDocument("Styles.docx"); List <XWPFStyle> testUsedStyleList = new List <XWPFStyle>(); XWPFStyles styles = sampleDoc.GetStyles(); XWPFStyle style = styles.GetStyle("berschrift1"); testUsedStyleList.Add(style); testUsedStyleList.Add(styles.GetStyle("Standard")); testUsedStyleList.Add(styles.GetStyle("berschrift1Zchn")); testUsedStyleList.Add(styles.GetStyle("Absatz-Standardschriftart")); style.HasSameName(style); List <XWPFStyle> usedStyleList = styles.GetUsedStyleList(style); //Assert.AreEqual(usedStyleList, testUsedStyleList); Assert.AreEqual(usedStyleList.Count, testUsedStyleList.Count); for (int i = 0; i < usedStyleList.Count; i++) { Assert.AreEqual(usedStyleList[i], testUsedStyleList[i]); } }
static void Main(string[] args) { XWPFDocument doc = new XWPFDocument(); XWPFParagraph paragraph = doc.CreateParagraph(); XWPFRun run = paragraph.CreateRun(); run.SetText("This is a text paragraph having "); XWPFHyperlinkRun hyperlinkrun = CreateHyperlinkRun(paragraph, "https://www.google.com"); hyperlinkrun.SetText("a link to Google"); hyperlinkrun.SetColor("0000FF"); hyperlinkrun.SetUnderline(UnderlinePatterns.Single); run = paragraph.CreateRun(); run.SetText(" in it."); using (FileStream out1 = new FileStream("hyperlink.docx", FileMode.Create)) { doc.Write(out1); } }
public MemoryStream CreateTableDoc(List <StaffViewModel> staffs, int countRecord = 0) { MemoryStream result = new MemoryStream(); XWPFDocument doc = new XWPFDocument(); XWPFStyles styles = doc.CreateStyles(); XWPFParagraph pCha = doc.CreateParagraph(); XWPFTable table = doc.CreateTable(countRecord + 1, 7); table.Width = 3500; AddCell(table.GetRow(0).GetCell(0), "Фамилия"); AddCell(table.GetRow(0).GetCell(1), "Имя"); AddCell(table.GetRow(0).GetCell(2), "Отчество"); AddCell(table.GetRow(0).GetCell(3), "Должность"); AddCell(table.GetRow(0).GetCell(4), "Звание"); AddCell(table.GetRow(0).GetCell(5), "Подразделение"); AddCell(table.GetRow(0).GetCell(6), "Уволен"); int i = 1; if (staffs != null) { foreach (var item in staffs) { AddCell(table.GetRow(i).GetCell(0), item.Second); AddCell(table.GetRow(i).GetCell(1), item.First); AddCell(table.GetRow(i).GetCell(2), item.MiddleName); AddCell(table.GetRow(i).GetCell(3), item.Position.Name); AddCell(table.GetRow(i).GetCell(4), item.Rank.Name); AddCell(table.GetRow(i).GetCell(5), item.SubDepartmen.Name); AddCell(table.GetRow(i).GetCell(6), item.Fired == true ? "Уволен" : "Работает"); // table.GetRow(i).GetCell(0).SetText(item.Second); ++i; } } table.ColBandSize = 14; doc.Write(result); return(result); }
public static void 追加表格行() { List <Student> students = new List <Student>() { new Student() { StuNo = "new4321", Age = 10, PhoneNum = "4321", Nationality = "Japan", Sex = 5 }, new Student() { StuNo = "new3214", Age = 20, PhoneNum = "1243", Nationality = "Japan", Sex = 4 }, new Student() { StuNo = "new2143", Age = 30, PhoneNum = "4321", Nationality = "Japan", Sex = 3 }, new Student() { StuNo = "new1432", Age = 10, PhoneNum = "1234", Nationality = "Japan", Sex = 2 }, }; DataTable td = ListDatatableMapper <Student> .ListToDataTable(students); XWPFDocument doc = null; using (FileStream fs = new FileStream(Demo.docPath, FileMode.Open, FileAccess.Read)) { doc = new XWPFDocument(fs); } XWPFTable t = doc.Tables[0]; WordHelper.AppendTable(t, td); using (FileStream fs = new FileStream(docToPath, FileMode.OpenOrCreate, FileAccess.Write)) { doc.Write(fs); } }
public static XWPFDocument SaveWord(Letter letter) { XWPFDocument doc = null; switch (letter.Book) { case Book.Notification: doc = _modelNotificationPath.OpenWord(); break; case Book.Protocol: doc = _modelProtocolPath.OpenWord(); break; } if (doc != null) { var paras = doc.Paragraphs; foreach (var para in paras) { var text = para.ParagraphText; var runs = para.Runs; for (var i = 0; i < runs.Count; i++) { var run = runs[i]; var str = run.Text .Replace("{Number}", letter.Number) .Replace("{Name}", letter.Name) .Replace("{Credit}", letter.Credit) .Replace("{Description}", letter.Description) .Replace("{Contact}", letter.Contact) .Replace("{TelPhone}", letter.TelPhone) .Replace("{Time}", letter.Time); run.SetText(str); } } } return(doc); }
public static XWPFParagraph Paragraph(XWPFDocument doc, int spacingAfter = -1, int spacingAfterLines = -1, int indentationFirstLine = -1, ParagraphAlignment alignment = ParagraphAlignment.LEFT, string lineSpacing = null) { var p = doc?.Document?.body?.AddNewP(); if (p == null) { return(null); } if (!string.IsNullOrEmpty(lineSpacing)) { var ppr = p?.AddNewPPr(); var spacing = ppr?.AddNewSpacing(); if (spacing != null) { spacing.line = lineSpacing; spacing.lineRule = N.OpenXmlFormats.Wordprocessing.ST_LineSpacingRule.auto; } } var paragraph = new XWPFParagraph(p, doc) { Alignment = alignment }; if (spacingAfter > 0) { paragraph.SpacingAfter = spacingAfter; } if (spacingAfterLines > 0) { paragraph.SpacingAfterLines = spacingAfterLines; } if (indentationFirstLine > 0) { paragraph.IndentationFirstLine = indentationFirstLine; } return(paragraph); }
/// <summary> /// 文档替换变量 /// </summary> /// <param name="doc">文档</param> /// <param name="dics">变量信息:key:变量名-value:变量值</param> protected virtual void DocReplaceVariable(XWPFDocument doc, Dictionary <string, string> dics) { //段落变量替换 foreach (var paragraph in doc.Paragraphs) { foreach (var item in dics) { if (!paragraph.Text.Contains("${" + item.Key + "}")) { continue; } paragraph.ReplaceText("${" + item.Key + "}", item.Value); } } //表格变量替换 foreach (var table in doc.Tables) { foreach (var row in table.Rows) { foreach (var cell in row.GetTableCells()) { foreach (var paragraph in cell.Paragraphs) { foreach (var item in dics) { if (!paragraph.Text.Contains("${" + item.Key + "}")) { continue; } paragraph.ReplaceText("${" + item.Key + "}", item.Value); } } } } } }
private void readWord() { using (FileStream stream = File.OpenRead("C:\\Users\\NBJZ\\Desktop\\施工说明书(模板).docx")) //using (FileStream stream=File.OpenRead("C:\\Users\\NBJZ\\Desktop\\施工说明书(组合).docx")) { XWPFDocument doc = new XWPFDocument(stream); foreach (XWPFTable table in doc.Tables) { //循环表格行 foreach (XWPFTableRow row in table.Rows) { foreach (XWPFTableCell cell in row.GetTableCells()) { //sb.Append(cell.GetText()); } } } } FileStream fs = new FileStream("C:\\Users\\NBJZ\\Desktop\\01 施工说明书(2).doc", FileMode.Open, FileAccess.Read); XWPFDocument myDocx = new XWPFDocument(fs);//打开07(.docx)以上的版本的文档 //读取表格 foreach (XWPFTable table in myDocx.Tables) { //循环表格行 foreach (XWPFTableRow row in table.Rows) { foreach (XWPFTableCell cell in row.GetTableCells()) { //sb.Append(cell.GetText()); } } } }
/// <summary> /// 生成一个工程的word文件 /// </summary> /// <param name="datalist">当前工程的数据List</param> /// <param name="outputPath">word文件输出路径</param> public static void word_creat_one(List <DbBean> datalist, string outputPath) { XWPFDocument m_Docx = new XWPFDocument(); word_init(m_Docx); //内容 for (int i = 0; i < datalist.Count; i++) { word_inster_table(m_Docx, datalist[i], i + 1); //TODO 此处插入图片 word_insert_picture(m_Docx, datalist[i].PrjName, datalist[i].PhotoPathName); } //输出 FileStream sw = null; try { sw = File.Create(outputPath); if (m_Docx == null) { Log.Err(TAG, "m_Docx is null"); } if (sw == null) { Log.Err(TAG, "sw is null"); } m_Docx.Write(sw); sw.Close(); } catch { Log.Err(TAG, "something is wrong"); } finally { sw.Close(); } }
public static void RemoveParagraphs(this XWPFDocument doc, string beginTag, string endTag) { var remove = false; int i = 0; while (i < doc.BodyElements.Count) { if (!(doc.BodyElements[i] is XWPFParagraph)) { i++; continue; } var runText = (doc.BodyElements[i] as XWPFParagraph).Text; if (runText == beginTag) { remove = true; } if (remove) { doc.RemoveBodyElement(i); } if (runText == endTag) { remove = false; continue; } if (!remove) { i++; } } }
/// <summary> /// Npoi处理Docx /// </summary> /// <param name="stream"></param> /// <param name="uploadImgUrlyDelegate">上传图片事件 入参byte[] 为图片数据 string为图片类型 </param> /// <returns></returns> public async Task <string> NpoiDocx(Stream stream, Func <byte[], string, string> uploadImgUrlyDelegate = null) { var myDocx = new XWPFDocument(stream); //打开07(.docx)以上的版本的文档 var picturesConvert = new PicturesConvert(); picturesConvert.uploadImgUrlyDelegate += uploadImgUrlyDelegate; var paraGraphConvert = new ParaGraphConvert(); var tableConvert = new TableConvert(); var picInfoList = await picturesConvert.PicturesHandleAsync(myDocx); var sb = new StringBuilder(); foreach (var para in myDocx.BodyElements) { switch (para.ElementType) { case BodyElementType.PARAGRAPH: { var paragraph = (XWPFParagraph)para; sb.Append(paraGraphConvert.ParaGraphHandle(paragraph, picInfoList)); break; } case BodyElementType.TABLE: var paraTable = (XWPFTable)para; sb.Append(tableConvert.TableHandle(paraTable, picInfoList)); break; } } return(sb.Replace(" style=''", "").ToString()); }
public void TestBug58922() { XWPFDocument document = new XWPFDocument(); XWPFRun run = document.CreateParagraph().CreateRun(); Assert.AreEqual(-1, run.FontSize); run.FontSize = 10; Assert.AreEqual(10, run.FontSize); run.FontSize = short.MaxValue - 1; Assert.AreEqual(short.MaxValue - 1, run.FontSize); run.FontSize = short.MaxValue; Assert.AreEqual(short.MaxValue, run.FontSize); run.FontSize = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.FontSize); run.FontSize = int.MaxValue - 1; Assert.AreEqual(int.MaxValue - 1, run.FontSize); run.FontSize = int.MaxValue; Assert.AreEqual(int.MaxValue, run.FontSize); run.FontSize = -1; Assert.AreEqual(-1, run.FontSize); Assert.AreEqual(-1, run.TextPosition); run.TextPosition = 10; Assert.AreEqual(10, run.TextPosition); run.TextPosition = short.MaxValue - 1; Assert.AreEqual(short.MaxValue - 1, run.TextPosition); run.TextPosition = short.MaxValue; Assert.AreEqual(short.MaxValue, run.TextPosition); run.TextPosition = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.TextPosition); run.TextPosition = short.MaxValue + 1; Assert.AreEqual(short.MaxValue + 1, run.TextPosition); run.TextPosition = int.MaxValue - 1; Assert.AreEqual(int.MaxValue - 1, run.TextPosition); run.TextPosition = int.MaxValue; Assert.AreEqual(int.MaxValue, run.TextPosition); run.TextPosition = -1; Assert.AreEqual(-1, run.TextPosition); }
//地政函审批表(改功能) /// <summary> /// 将模板文档的源关键字替换成目标文本 /// </summary> /// <param name="dic">基础替换文本字典</param> /// <param name="formatParaDic">包含换行符的替换目标字典</param> /// <param name="tplFilePath">模板文件的路径</param> /// <param name="outputPrintFilePath">输出文件路径</param> public static void DZHSPBGGN(Dictionary <string, string> dic, Dictionary <string, string> formatParaDic, string tplFilePath, string outputPrintFilePath) { using (FileStream tplFileStream = new FileStream(tplFilePath, FileMode.Open, FileAccess.Read)) using (FileStream outputFileStream = File.Create(outputPrintFilePath)) { List <RespDZHSPBChild> list = new DbHelper().QueryDZHSPB1_Child(SharpDbPrinter.Program.globalYwid); XWPFDocument tplDoc = new XWPFDocument(tplFileStream); var printDoc = DocxRepalceWithParaFormat(tplDoc, formatParaDic); printDoc = DocxBaseRelace(printDoc, dic); int row1 = 9; var firstTable = printDoc.Tables[0]; for (int i = 0; i < list.Count; i++) { XWPFTableRow newRow = new XWPFTableRow(new NPOI.OpenXmlFormats.Wordprocessing.CT_Row(), firstTable); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.CreateCell(); newRow.MergeCells(5, 9); newRow.MergeCells(0, 4); newRow.GetCell(0).SetParagraph(SetCellText(printDoc, firstTable, list[i].th ?? "")); newRow.GetCell(1).SetParagraph(SetCellText(printDoc, firstTable, list[i].YTDSYZH ?? "")); newRow.GetCell(2).SetParagraph(SetCellText(printDoc, firstTable, list[i].PZMJ ?? "")); firstTable.AddRow(newRow, row1 + 1 + i); } firstTable.RemoveRow(row1); printDoc.Write(outputFileStream); } }
public void TestWhitespace() { String[] text = new String[] { " The quick brown fox", "\t\tjumped over the lazy dog" }; MemoryStream bos = new MemoryStream(); XWPFDocument doc = new XWPFDocument(); foreach (String s in text) { XWPFParagraph p1 = doc.CreateParagraph(); XWPFRun r1 = p1.CreateRun(); r1.SetText(s); } doc.Write(bos); MemoryStream bis = new MemoryStream(bos.ToArray()); var doc2 = new XWPFDocument(bis); var paragraphs = doc2.Paragraphs; Assert.AreEqual(2, paragraphs.Count); for (int i = 0; i < text.Length; i++) { XWPFParagraph p1 = paragraphs[i]; String expected = text[i]; Assert.AreEqual(expected, p1.Text); CT_P ctp = p1.GetCTP(); CT_R ctr = ctp.GetRArray(0); CT_Text ctText = ctr.GetTArray(0); // if text has leading whitespace then expect xml-fragment to have xml:space="preserve" set // <xml-fragment xml:space="preserve" xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> bool isWhitespace = Character.isWhitespace(expected[0]); Assert.AreEqual(isWhitespace, ctText.space == "preserve"); } }
private string TranslateBaiduResult(string ResultTest) { if (string.IsNullOrEmpty(ResultTest)) { return(null); } string ResultStr = string.Empty; XWPFDocument doc = new XWPFDocument(); string[] Plist = ResultTest.Split(Environment.NewLine.ToCharArray()); Plist = Plist.Where(s => !string.IsNullOrEmpty(s)).ToArray(); string value = string.Empty; for (int i = 0; i < Plist.Length; i++) { if (!Plist[i].Contains("words") || Plist[i].Contains("words_result_num") || Plist[i].Contains("words_result")) { continue; } else { value = Plist[i]; value = value.Replace("words", "").Replace("\"", "").Replace(":", ""); value = value.Replace("\"words\": \"", "").Trim(); } XWPFParagraph P1 = doc.CreateParagraph(); P1.Alignment = ParagraphAlignment.LEFT; XWPFRun P1Text = P1.CreateRun(); P1Text.SetText(value); } Globaldoc = doc; foreach (XWPFParagraph xWPF in doc.Paragraphs) { ResultStr += xWPF.Text; ResultStr += "\r\n"; } return(ResultStr); }
/// <summary> /// This Functions Erases the Docx File and create a new one, using the /// simpleXml generated by the TransformToSimpleXml() method. /// </summary> /// <param name="docLocation"></param> /// <param name="simplerXml"></param> private static void ReWriteDocument(string docLocation, XElement simplerXml) { string newDocLocation = docLocation.Split('.')[0] + " Simplificado.docx"; using (FileStream fileStream = new FileStream(newDocLocation, FileMode.Create, FileAccess.Write)) { XWPFDocument newWordDoc = new XWPFDocument(); foreach (XElement paragraph in simplerXml.Elements()) { XWPFParagraph newDocParagraph = newWordDoc.CreateParagraph(); newDocParagraph.Alignment = ParagraphAlignment.LEFT; XWPFRun newDocRun = newDocParagraph.CreateRun(); newDocRun.FontFamily = "Arial"; newDocRun.FontSize = 12; newDocRun.IsBold = false; newDocRun.SetText(paragraph.Value); } newWordDoc.Write(fileStream); newWordDoc.Close(); } }
/// <summary> /// 将数据趋势图插入到word文档指定位置 /// </summary> /// <param name="templateFile">模板</param> /// <param name="structStream">结构物下各个监测因素对应的图片流集合</param> /// <returns></returns> public XWPFDocument ChartHandler(XWPFDocument templateFile, List <ChartByFactor> structStream) { XWPFDocument template = templateFile; for (int i = 0; i < template.Paragraphs.Count; i++) { var runs = template.Paragraphs[i].Runs; for (int j = 0; j < runs.Count; j++) { var run = runs[j]; string text = run.GetText(0); if (text == "$Chart") { run.SetText("", 0); run.AddCarriageReturn(); XWPFRun chartRunPoint = run.Paragraph.CreateRun(); //XWPFRun chartRunPoint = run; PutChartToWord(template, chartRunPoint, structStream); } } } return(template); }
/// <summary> /// 保存文件 /// </summary> /// <param name="savePath"></param> /// <param name="doc"></param> public static void SaveXWPFDocument(string savePath, XWPFDocument doc) { FileStream file = null; try { var dir = Path.GetDirectoryName(savePath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } file = new FileStream(savePath, FileMode.Create, FileAccess.Write); doc.Write(file); } catch (Exception) { throw; } finally { file.Close(); } }
/// <summary> /// 从模板文件读取 /// </summary> /// <param name="contentRootPath"></param> /// <returns></returns> public static XWPFDocument GetXWPFDocument(string fileUrl) { XWPFDocument word; if (!File.Exists(fileUrl)) { throw new Exception("找不到模板文件"); } try { using (FileStream fs = File.OpenRead(fileUrl)) { word = new XWPFDocument(fs); } } catch (Exception) { throw new Exception("打开模板文件失败"); } return(word); }
/// <summary> /// 创建Word文件 /// </summary> /// <param name="name"></param> /// <returns></returns> public static XWPFDocument CreateXWPFDocument(string name) { XWPFDocument doc = new XWPFDocument(); var p0 = doc.CreateParagraph(); p0.Alignment = ParagraphAlignment.CENTER; XWPFRun r0 = p0.CreateRun(); r0.FontFamily = "microsoft yahei"; r0.FontSize = 18; r0.IsBold = true; r0.SetText(""); var p1 = doc.CreateParagraph(); p1.Alignment = ParagraphAlignment.LEFT; p1.IndentationFirstLine = 500; XWPFRun r1 = p1.CreateRun(); r1.FontFamily = "·ÂËÎ"; r1.FontSize = 12; r1.IsBold = true; return(doc); }