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

  生成結果

同時還可以生成餅圖、線形圖。

 

業精於勤,荒於嬉;行成於思,毀於隨。

如果你覺得這篇文章不錯或者對你有所幫助,可以通過右側【打賞】功能,給予博主一點點鼓勵和支持


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM