Docx组件读写Word文档介绍

Docx介绍

     官方原文:DocX is a .NET library that allows developers to manipulate Word 2007/2010/2013 files, in an easy and intuitive manner. DocX is fast, lightweight and best of all it does not require Microsoft Word or Office to be installed.(DocX是允许开发者以非常简单的方式操作Word 2007/2010/2013文件的轻量级.NET组件。它的速度非常快,而且不需要安装微软的Office软件。)

Docx特征

DocX组件目前版本的主要特点有:

1)支持在文件中插入、删除和替代文本,支持所有的文本格式,如字体,颜色,大小,斜体字,下划线,删除线,高亮等。

2)支持段落的对齐方式,最新版本支持插入各级标题。

3)支持插入图片、超链接、表格、页眉页脚以及自定义属性等。

Docx实例

    官方已经列举了Docx组件几乎所有的功能和实例,这里就不全部说明了。想要了解更多的实例,可以参考官方网站:http://docx.codeplex.com/SourceControl/latest#Examples/Program.cs

    使用之前,可以到官网下载最新版本的Docx组件。点击这里下载

实例1:输出支持的所有标题级别

using (DocX document = DocX.Create(@"C:\DocumentHeading.docx"))
{
    foreach (HeadingType heading in (HeadingType[])Enum.GetValues(typeof(HeadingType)))
    {
        string text = string.Format("{0} - The quick brown fox jumps over the lazy dog", heading.EnumDescription());

        Paragraph p = document.InsertParagraph();
        p.AppendLine(text).Heading(heading);
    }
    document.Save();
}

实例2:文档中插入表格

Table table1 = document1.AddTable(1, 3); //一行三列
table1.Design = TableDesign.TableGrid;    //表格样式
table1.Alignment = Alignment.center;      //设置表格居中
table1.Rows[0].Cells[0].Paragraphs[0].Append("列1").Bold();
table1.Rows[0].Cells[1].Paragraphs[0].Append("列2").Bold();
table1.Rows[0].Cells[2].Paragraphs[0].Append("列3").Bold();

table1.Rows[0].Cells[0].Width = 100;   //设置单元格宽度
table1.Rows[0].Cells[1].Width = 100;
table1.Rows[0].Cells[2].Width = 100;


Paragraph p = document1.InsertParagraph();
p.Alignment = Alignment.center;
p.Append("表格名称").Bold();
p.InsertTableAfterSelf(table1);

实例3:文档中插入图片

Paragraph pPicture = document1.InsertParagraph();
pPicture.Alignment = Alignment.center;

Novacode.Image image = document1.AddImage(@"C:\images\1.png);

Picture picture = image.CreatePicture();
picture.Width = 240; //设置图片大小
picture.Height = 180;
pPicture.AppendPicture(picture).AppendLine("图片名称").Bold();

实例4:文档中插入文档

DocX document1 = DocX.Create(@"C:\1.docx");
Paragraph p1 = document1.InsertParagraph();
p1.Append("文档document1");
document1.Save();

DocX document2 = DocX.Create(@"C:\2.docx");
Paragraph p2 = document2 .InsertParagraph();
p2.Append("文档document2");
document2.Save();

//文档2插入到文档1
document1.InsertDocument(document2, true);

实例5:根据模板生成文档

    1、设置文档模板,模板形式如下图:

    2、通过DocX的Load(string path)方法加载模板

    3、通过ReplaceText(string seachValue, string newValue)替换模板中标识

//加载模板
DocX document = DocX.Load(@"C:\templateDocx.docx");

//替换文档中标识
document.ReplaceText("$value$", "根据模板生成文档");

//根据表格模板填充表数据
DataTable dataTable = new DataTable();
dataTable.Columns.Add("Column1");
dataTable.Columns.Add("Column2");
dataTable.Rows[0]["Column1"] = "列1内容";
dataTable.Rows[0]["Column2"] = "列2内容";
DataTable resultNew = new DataTable();
resultNew = dataTable.DefaultView.ToTable(false, new string[] { "Column1", "Column2" });
int templateRowId = 1;   //从第2列填充数据
Table table = document.Tables[0];    //模板文档中表格索引,从0开始
MakeTableByTemplate(table, resultNew, templateRowId);

private void MakeTableByTemplate(Table table, DataTable result, int templateRowId)
{
    Row templateRow = table.Rows[templateRowId];
    int rowId = 0;
    foreach (DataRow row in result.Rows)
    {
        table.InsertRow(templateRow);
        int colId = 0;
        foreach (Cell cell in table.Rows[templateRowId + 1 + rowId].Cells)
        {
            cell.ReplaceText("$d$", row[colId].ToString());

            colId++;
        }
        rowId++;
    }
    table.RemoveRow(templateRowId);
}

//生成文档到指定目录
document.SaveAs(@"C:\sourceFileName.docx");

实例6:文档中生成柱状图

using (DocX document = DocX.Create(@"C:\BarChart.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 = Color.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();
}

  ChartData类

public 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;
    }
}

  生成结果

同时还可以生成饼图、线形图。

 

业精于勤,荒于嬉;行成于思,毁于随。

如果你觉得这篇文章不错或者对你有所帮助,可以通过右侧【打赏】功能,给予博主一点点鼓励和支持

posted @ 2017-03-27 14:22  二月羊  阅读(2774)  评论(0编辑  收藏  举报