zoukankan      html  css  js  c++  java
  • DocX开源WORD操作组件的学习系列三

    DocX学习系列

    DocX开源WORD操作组件的学习系列一 :  http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_sharp_001_docx1.html

    DocX开源WORD操作组件的学习系列二 :  http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_csharp_005_docx2.html

    DocX开源WORD操作组件的学习系列三:  http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_csharp_006_docx3.html

    DocX开源WORD操作组件的学习系列四:  http://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_csharp_006_docx4.html

    替换文本

            private static void ReplaceText()
            {
                Console.WriteLine("ReplaceText()");
                File.Copy(@"docsLists.docx", @"docsReplaceText.docx", true);
                using (var document = DocX.Load(@"docsReplaceText.docx"))
                {
                    //全局替换
                    document.ReplaceText("zhao", "zhang");
                    //段落定位后替换
                    var p1=   document.Paragraphs.FirstOrDefault(r => r.Text == "赵杰迪");
                    if (p1 == null)
                    {
                        return;
                    }
                    p1.ReplaceText("zhaojiedi","zhaojiedi2");
                    //书签定位后替换
                    document.Bookmarks["书签1"].Paragraph.ReplaceText("zhaojiedi","zhaojiedi2");
                    //基于正则表达式的替换 用途:我们事先做一个模板文件, 然后基于正则表达式查找,然后替换。
                    List<Regex> regexList = new List<Regex>()
                    {
                       new Regex("[name](.*)[/name]"),
                        new Regex("[age](.*)[/age]"),
                         new Regex("[age](.*)[/age]")
                    };
                    foreach (var item in regexList)
                    {
                        Match match = item.Match(document.Text);
                        if (match.Success && match.Groups.Count >= 2)
                        {
                           document.ReplaceText(match.Groups[0].ToString(),match.Groups[1].ToString());
                        }
                    }
                    document.Save();
                    Console.WriteLine("	Created: docs\ReplaceText.docx");
                }
            }

    编号

      private static void AddList()
            {
                Console.WriteLine("	AddList()");
    
                using (var document = DocX.Create(@"docsLists.docx"))
                {
                    var numberedList = document.AddList("First List Item.", 0, ListItemType.Numbered);
                    //Add a numbered list starting at 2
                    document.AddListItem(numberedList, "Second List Item.");
                    document.AddListItem(numberedList, "Third list item.");
                    document.AddListItem(numberedList, "First sub list item", 1);
    
                    document.AddListItem(numberedList, "Nested item.", 2);
                    document.AddListItem(numberedList, "Fourth nested item.");
    
                    var bulletedList = document.AddList("First Bulleted Item.", 0, ListItemType.Bulleted);
                    document.AddListItem(bulletedList, "Second bullet item");
                    document.AddListItem(bulletedList, "Sub bullet item", 1);
                    document.AddListItem(bulletedList, "Second sub bullet item", 2);
                    document.AddListItem(bulletedList, "Third bullet item");
                    document.InsertList(numberedList);
                    document.InsertList(bulletedList);
                    document.Save();
                    Console.WriteLine("	Created: docs\Lists.docx");
                }
            }

     3创建图形

    3.1效果图

            private class ChartData
            {
                public String Mounth { get; set; }
                public Double Money { get; set; }
    
                public static List<ChartData> CreateCompanyList1()
                {
                    List<ChartData> company1 = new List<ChartData>();
                    company1.Add(new ChartData() { Mounth = "January", Money = 100 });
                    company1.Add(new ChartData() { Mounth = "February", Money = 120 });
                    company1.Add(new ChartData() { Mounth = "March", Money = 140 });
                    return company1;
                }
    
                public static List<ChartData> CreateCompanyList2()
                {
                    List<ChartData> company2 = new List<ChartData>();
                    company2.Add(new ChartData() { Mounth = "January", Money = 80 });
                    company2.Add(new ChartData() { Mounth = "February", Money = 160 });
                    company2.Add(new ChartData() { Mounth = "March", Money = 130 });
                    return company2;
                }
            }
    
            private static void BarChart()
            {
                Console.WriteLine("	BarChart()");
                // Create new document. 
                using (DocX document = DocX.Create(@"docsBarChart.docx"))
                {
                    // Create chart.
                    BarChart c = new BarChart();
                    c.BarDirection = BarDirection.Column;
                    c.BarGrouping = BarGrouping.Standard;
                    c.GapWidth = 400;
                    c.AddLegend(ChartLegendPosition.Bottom, false);
    
                    // Create data.
                    List<ChartData> company1 = ChartData.CreateCompanyList1();
                    List<ChartData> company2 = ChartData.CreateCompanyList2();
    
                    // Create and add series
                    Series s1 = new Series("Microsoft");
                    s1.Color = WindowsColor.GreenYellow;
                    s1.Bind(company1, "Mounth", "Money");
                    c.AddSeries(s1);
                    Series s2 = new Series("Apple");
                    s2.Bind(company2, "Mounth", "Money");
                    c.AddSeries(s2);
    
                    // Insert chart into document
                    document.InsertParagraph("Diagram").FontSize(20);
                    document.InsertChart(c);
                    document.Save();
                }
                Console.WriteLine("	Created: docs\BarChart.docx
    ");
            }
    
            private static void PieChart()
            {
                Console.WriteLine("	PieChart()");
                // Create new document. 
                using (DocX document = DocX.Create(@"docsPieChart.docx"))
                {
                    // Create chart.
                    PieChart c = new PieChart();
                    c.AddLegend(ChartLegendPosition.Bottom, false);
    
                    // Create data.
                    List<ChartData> company2 = ChartData.CreateCompanyList2();
    
                    // Create and add series
                    Series s = new Series("Apple");
                    s.Bind(company2, "Mounth", "Money");
                    c.AddSeries(s);
    
                    // Insert chart into document
                    document.InsertParagraph("Diagram").FontSize(20);
                    document.InsertChart(c);
                    document.Save();
                }
                Console.WriteLine("	Created: docs\PieChart.docx
    ");
            }
    
            private static void LineChart()
            {
                Console.WriteLine("	LineChart()");
                // Create new document. 
                using (DocX document = DocX.Create(@"docsLineChart.docx"))
                {
                    // Create chart.
                    LineChart c = new LineChart();
                    c.AddLegend(ChartLegendPosition.Bottom, false);
    
                    // Create data.
                    List<ChartData> company1 = ChartData.CreateCompanyList1();
                    List<ChartData> company2 = ChartData.CreateCompanyList2();
    
                    // Create and add series
                    Series s1 = new Series("Microsoft");
                    s1.Color = WindowsColor.GreenYellow;
                    s1.Bind(company1, "Mounth", "Money");
                    c.AddSeries(s1);
                    Series s2 = new Series("Apple");
                    s2.Bind(company2, "Mounth", "Money");
                    c.AddSeries(s2);
    
                    // Insert chart into document
                    document.InsertParagraph("Diagram").FontSize(20);
                    document.InsertChart(c);
                    document.Save();
                }
                Console.WriteLine("	Created: docs\LineChart.docx
    ");
            }
    
            private static void Chart3D()
            {
                Console.WriteLine("	Chart3D()");
                // Create new document. 
                using (DocX document = DocX.Create(@"docs3DChart.docx"))
                {
                    // Create chart.
                    BarChart c = new BarChart();
                    c.View3D = true;
    
                    // Create data.
                    List<ChartData> company1 = ChartData.CreateCompanyList1();
    
                    // Create and add series
                    Series s = new Series("Microsoft");
                    s.Color = WindowsColor.GreenYellow;
                    s.Bind(company1, "Mounth", "Money");
                    c.AddSeries(s);
    
                    // Insert chart into document
                    document.InsertParagraph("3D Diagram").FontSize(20);
                    document.InsertChart(c);
                    document.Save();
                }
                Console.WriteLine("	Created: docs\3DChart.docx
    ");
            }

     5添加图片

         static void HelloWorldAddPictureToWord()
            {
                Console.WriteLine("	HelloWorldAddPictureToWord()");
    
                // Create a document.
                using (DocX document = DocX.Create(@"docsHelloWorldAddPictureToWord.docx"))
                {
                    // Add an image into the document.    
                    RelativeDirectory rd = new RelativeDirectory(); // prepares the files for testing
                    rd.Up(2);
                    Image image = document.AddImage(rd.Path + @"imageslogo_template.png");
    
                    // Create a picture (A custom view of an Image).
                    Picture picture = image.CreatePicture();
                    picture.Rotation = 10;//旋转10度
                    picture.SetPictureShape(BasicShapes.cube);
    
                    // Insert a new Paragraph into the document.
                    Paragraph title = document.InsertParagraph().Append("This is a test for a picture").FontSize(20).Font(new Font("Comic Sans MS"));
                    title.Alignment = Alignment.center;
    
                    // Insert a new Paragraph into the document.
                    Paragraph p1 = document.InsertParagraph();
    
                    // Append content to the Paragraph
                    p1.AppendLine("Just below there should be a picture ").Append("picture").Bold().Append(" inserted in a non-conventional way.");
                    p1.AppendLine();
                    p1.AppendLine("Check out this picture ").AppendPicture(picture).Append(" its funky don't you think?");
                    p1.AppendLine();
    
                    // Insert a new Paragraph into the document.
                    Paragraph p2 = document.InsertParagraph();
                    // Append content to the Paragraph.
    
                    p2.AppendLine("Is it correct?");
                    p2.AppendLine();
    
                    // Lets add another picture (without the fancy stuff)
                    Picture pictureNormal = image.CreatePicture();
    
                    Paragraph p3 = document.InsertParagraph();
                    p3.AppendLine("Lets add another picture (without the fancy  rotation stuff)");
                    p3.AppendLine();
                    p3.AppendPicture(pictureNormal);
    
                    // Save this document.
                    document.Save();
                    Console.WriteLine("	Created: docs\HelloWorldAddPictureToWord.docx
    ");
                }
            }

    6.替换模板中的图片

          public bool ReplaceImage(string oldImageName, string newImageNmae)
            {
    
                Paragraph paragraph = null;
                int width = 0;
                int height = 0;
                foreach (Paragraph item in Document.Paragraphs){
                    if (item.Pictures.Count > 0 && item.Pictures[0].FileName == oldImageName)
                    {
                        paragraph = item;
                        break;
                    }
                }
                if (paragraph == null)
                {
                    return false;
                }
                width = paragraph.Pictures[0].Width;
                //height = paragraph.Pictures[0].Height;
                paragraph.Pictures[0].Remove();
                using (System.Drawing.Image tmpImage = new Bitmap(newImageNmae))
                {
                    int tmpWidth = tmpImage.Width;
                    int tmpHeight = tmpImage.Height;
                    float radio = tmpHeight  * 1.0f /tmpWidth;
                    height = (int)(width*radio);
                }
                Novacode.Image newImage = this.Document.AddImage(newImageNmae);
               
                // Insert the extracted logo into the paragraph
                paragraph.InsertPicture(newImage.CreatePicture(height, width));//注意createpicture的构造函数
                //paragraph.InsertPicture(newImage.CreatePicture());//注意createpicture的构造函数
                return true;
            }
  • 相关阅读:
    Pyinstaller(python打包为exe文件)
    matplotlib 填充颜色
    Visual Studio 2015 Enterprise
    latex中pdflatex与xelatex的区别
    latex插图续
    dva+umi+antd项目从搭建到使用(没有剖验证,不知道在说i什么)
    umi+dva+antd新建项目(亲测可用)
    HTTP缓存机制
    企业网站常见需求整理
    立足于运维与监控的前端框架 NoahV
  • 原文地址:https://www.cnblogs.com/zhaojiedi1992/p/zhaojiedi_csharp_006_docx3.html
Copyright © 2011-2022 走看看