文章出處

上一篇的文章中我們介紹了在不使用第三方組件的方式,多種數據輸出出到 word的方式,最后我們也提到了不使用組件的弊端,就是復雜的word我們要提前設置模板、編碼不易控制、循環輸出數據更是難以控制。接下來介紹用第三方組件Aspose.Words 的開發方式解決上面提到的問題。

[本次實例和上次實例的源代碼,點擊這里下載]

[Aspose.Words.dll 以及 使用手冊由于太大傳到csdn上了,點這里下載(免費)]

 

文章的梗概:

 ♦ Aspose.Words 的介紹

      ♦ 整體概括

      ♦ 支持的平臺

      ♦ 支持的文件格式

♦ Aspose.Words 的基本使用介紹

      ♦ 創建一個word文檔

♦ 加載一個已存在的word文檔

♦ 保存word文檔

♦ 控制word初始顯示形式

♦ 創建書簽

♦ 控制文字輸出樣式

♦ 利用標志位替換想要輸出的內容

♦ word文檔中添加水印

♦ 輸出表格

♦ 綜合實例介紹

♦ 運用書簽輸出表格

 

一、Aspose.Words 的介紹(更多介紹請到官網查看)

At a Glance

整體概括

 

An overview of the main conversion, rendering and reporting capabilities of Aspose.Words for .NET.

Aspose.Words在.NET版本下,其渲染和報告能力的主要轉換的概述。

Supported Platforms

支持的平臺

 

Aspose.Words for .NET supports the .NET framework (including C#, VB.NET, ASP.NET etc.), ASP, ColdFusion, Perl, Power Builder, PHP, Python and Mono.

Aspose.Words 在 .NET的版本支持.NET framework(包括C#, VB.NET, ASP.NET 等), ASP, ColdFusion, Perl, Power Builder, PHP, Python and Mono.

Supported File Formats

支持的文件格式

 

Aspose.Words for .NET supports the popular word (DOC, DOT, DOCM, DOTM, DOCX, DOTX, FlatOpc, FlatOpcMacroEnabled, FlatOpcTemplate, FlatOpcTemplateMacroEnabled, XML, ODT, OTT, OOXML, WordML, RTF, HTML, XHTML, MHTML & TXT) file formats that your business depend on. It also allows exporting or converting word documents to PDF, XPS, XamlFixed, XamlFlow, XamlFlowPack, EPUB, HTML, HtmlFixed, OpenXPS, PostScript, TXT and popular image/multimedia file formats including TIFF, JPG, PNG, BMP, SVG, EMF, SVG and SWF.

Aspose.Words 在 .NET的版本 支持主流的 word文件格式(DOC, DOT, DOCM, DOTM, DOCX, DOTX, FlatOpc, FlatOpcMacroEnabled, FlatOpcTemplate, FlatOpcTemplateMacroEnabled, XML, ODT, OTT, OOXML, WordML, RTF, HTML, XHTML, MHTML & TXT)。它也允許導出或者轉換word文檔到PDF, XPS, XamlFixed, XamlFlow, XamlFlowPack, EPUB, HTML, HtmlFixed, OpenXPS, PostScript, TXT和主流的文件或TIFF, JPG, PNG, BMP, SVG, EMF, SVG and SWF多媒體格式。

 

二、Aspose.Words 的基本使用介紹(更多的使用介紹請下載實例,參考使用說明文檔或者點這里參考在線版使用文檔)

下面的內容是介紹把數據輸出到word的常用用法,而word怎么轉換成pdf或者其他功能這篇文章將不做介紹,感興趣可以參考使用文檔。

首先我們要添加引用,找到"Aspose.Words.dll"組件的路徑,添加此引用到項目中。

創建一個word文檔

其中兩個非常重要的對象,Document是文檔對象,一切的word控制Document對象時最基礎的。另一個就是DocumentBuilder對象,幾乎所有的輸出類型都是和它有關聯。

 1  protected void CreateWord_Click(object sender, EventArgs e)
 2         {
 3             // 實例化 Aspose.Words.Document 對象
 4             Document doc = new Document();
 5 
 6             // 實例化 Aspose.Words.DocumentBuilder 對象 (后面幾乎都是通過操作DocumentBuilder實現輸出word內容的
 7             DocumentBuilder builder = new DocumentBuilder(doc);
 8 
 9             // 往word中輸入內容
10             builder.Writeln("這是創建的一個word文檔");
11 
12             // 保存到指定的路徑
13             doc.Save("G:/CreateWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc");
14         }

 

加載一個已存在的word文檔

可以直接加載項目中對應的word文件

 1 protected void LoadWord_Click(object sender, EventArgs e)
 2         {
 3             // 找到項目中的word模板 并轉換成物理路徑
 4             var path = Server.MapPath("../Document/AsposeWord.doc");
 5 
 6             // 實例化 Aspose.Words.Document 對象
 7             Document doc = new Document(path);
 8 
 9             // 實例化 Aspose.Words.DocumentBuilder 對象 (后面幾乎都是通過操作DocumentBuilder實現輸出word內容的
10             DocumentBuilder builder = new DocumentBuilder(doc);
11 
12             // 往word中輸入內容
13             builder.Writeln("這是加載的word文檔");
14 
15             // 保存到指定的路徑
16             doc.Save("G:/LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc");
17         }

或者把word文件轉換成流的形式加載(相比之下上面那種形式用的更多)

 1 protected void LoadWord_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/AsposeWord.doc");
 4 
 5             // 把文件轉換成流的形式
 6             Stream stream = File.OpenRead(path);
 7            
 8             Document doc = new Document(stream);
 9 
10             // 用完關閉
11             stream.Close();
12 
13             DocumentBuilder builder = new DocumentBuilder(doc);
14 
15             // 往word中輸入內容
16             builder.Writeln("這是加載的word文檔");
17 
18             // 保存到指定的路徑
19             doc.Save("G:/LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc");
20         }

 

保存word文檔

上面的word示例保存是服務器端指定的路徑,其實不一定把word保存到指定的路徑上,也可以直接把文件保存到客戶端,即用戶通過類似下載的形式保存。

參數中SaveFormat枚舉是指保存的格式,有很多種,這里指定為word的doc格式;SaveType枚舉指定保存類型,有SaveType.OpenInWord和OpenInBrowser兩種,

如果保存方式指定為OpenInWord會在瀏覽器左下角提示word文檔,而如果是OpenInBrowser會提示打來word文檔。當然瀏覽器的不同,提示的信息也不一樣。

 1 protected void LoadWord_Click(object sender, EventArgs e)
 2         {
 3             // 找到項目中的word模板 并轉換成物理路徑
 4             var path = Server.MapPath("../Document/AsposeWord.doc");
 5 
 6             // 實例化 Aspose.Words.Document 對象
 7             Document doc = new Document(path);
 8 
 9             // 實例化 Aspose.Words.DocumentBuilder 對象 (后面幾乎都是通過操作DocumentBuilder實現輸出word內容的
10             DocumentBuilder builder = new DocumentBuilder(doc);
11 
12             // 往word中輸入內容
13             builder.Writeln("這是加載的word文檔");
14 
15             // 文件保存到客戶端
16             var fileName = "LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
17 
18             // 保存到客戶端(保存的路徑默認是客戶端自己設置的下載路徑,與服務器端無關)
19             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInWord, Response);
20             //doc.Save("G:/LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc");
21         }

 

控制word初始顯示形式

可以控制初始顯示的大小比例或者打開呈現的形式。

 1 protected void LoadWord_Click(object sender, EventArgs e)
 2         {
 3             // 找到項目中的word模板 并轉換成物理路徑
 4             var path = Server.MapPath("../Document/AsposeWord.doc");
 5 
 6             // 實例化 Aspose.Words.Document 對象
 7             Document doc = new Document(path);
 8 
 9             // 實例化 Aspose.Words.DocumentBuilder 對象 (后面幾乎都是通過操作DocumentBuilder實現輸出word內容的
10             DocumentBuilder builder = new DocumentBuilder(doc);
11 
12             // 控制顯示的形式
13             doc.ViewOptions.ViewType = ViewType.PageLayout;
14            
15             // 控制顯示的大小比例此處為百分比,范圍是0~100
16             doc.ViewOptions.ZoomPercent = 100;
17 
18 
19             // 往word中輸入內容
20             builder.Writeln("這是加載的word文檔");
21 
22             // 文件保存到客戶端
23             var fileName = "LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
24 
25             // 保存到客戶端
26             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
27             //doc.Save("G:/LoadWord(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc");
28         }
View Code

 

創建書簽

創建書簽的含義,就和通過我的創建書簽一樣,到時候就可以快速的定位了。不過一般都是先通過word創建好書簽,程序中就可以直接定位到書簽的位置,并輸出內容。

通過word創建書簽:

用程序創建書簽(一般都是先通過word創建書簽,此處只是演示程序如何創建書簽)

1             Document doc = new Document();
2             DocumentBuilder builder = new DocumentBuilder(doc);
3             // 創建書簽
4             builder.StartBookmark("MyBookmark");
5 
6             builder.Writeln("Text inside a bookmark.");
7             // 結束書簽
8             builder.EndBookmark("MyBookmark");

 

控制文字輸出樣式

前面也說了DocumentBuilder對象,非常強大。原文是這樣說的:

DocumentBuilder is a powerful class that is associated with a Document and allows dynamic document building from scratch or the addition of new elements to an existing document. It provides methods to insert text, paragraphs, lists, tables, images and other contents, specification of font, paragraph, and section formatting, and other things. Using DocumentBuilder is somewhat similar in concept to using the StringBuilder class of the .NET Framework.

DocumentBuilder是一個功能強大的類,與文檔相關聯的,允許動態文檔建設從無到有或新的元素到一個現有的文件添加。它提供了方法來插入文字,段落,列表,表格,圖片和其他內容,字體,段落格式規范,節,和其他的東西。使用DocumentBuilder有些類似的概念使用的StringBuilder類。NET框架。

當然了由于篇幅問題DocumentBuilder不能詳細介紹了,更多細節還是參考說明文檔吧。下面回歸到文字輸出控制的介紹:

 1 protected void CreateWordContainFontStyle_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/AsposeWord.doc");
 4             Document doc = new Document(path);
 5             DocumentBuilder builder = new DocumentBuilder(doc);
 6 
 7             Aspose.Words.Font font = builder.Font;
 8             font.Size = 16;
 9             font.Bold = true;
10             font.Color = Color.Blue;
11             font.Name = "Arial";
12             font.Underline = Underline.Dash;
13             builder.Write("文字樣式控制");
14 
15             var fileName = "CreateWordContainFontStyle(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
16             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
17         }

效果如下:

 

利用標志位替換想要輸出的內容

就和上篇文章差不多,利用占位符將我們要輸出的內容替換掉。

下面演示中,定義了兩個占位符 {name} 和{city}。當然不一定都是用'{}'符號包裹,只要不影響到word中其他內容用什么都可以,最好用特殊點的符號。

word如下:

 1 protected void ReplaceFlag_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/AsposeWord2.doc");
 4             Document doc = new Document(path);
 5             DocumentBuilder builder = new DocumentBuilder(doc);
 6 
 7             doc.Range.Replace("{name}", "Little-Ant", false, false);
 8             doc.Range.Replace("{city}", "上海,徐匯", false, false);
 9 
10             var fileName = "ReplaceFlag(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
11             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
12         }

效果如下:

 

word文檔中添加水印

在Aspose.Words.Drawing命名空間下有一個Shape對象,通過控制這個對象可以輸出類似水印的效果。

 1 protected void WaterMark_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/AsposeWord2.doc");
 4             Document doc = new Document(path);
 5             DocumentBuilder builder = new DocumentBuilder(doc);
 6 
 7             doc.Range.Replace("{name}", "Little-Ant", false, false);
 8             doc.Range.Replace("{city}", "上海,徐匯", false, false);
 9 
10             // 添加水印
11             InsertWatermarkText(doc, "http://www.cnblogs.com/littleAnt-strongPower/");
12 
13             var fileName = "WaterMark(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
14             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
15         }
16         #region 1.5.1 添加水印
17 
18         public void InsertWatermarkText(Document doc, string watermarkText)
19         {
20             // Create a watermark shape. This will be a WordArt shape. 
21             // You are free to try other shape types as watermarks.
22             Shape watermark = new Shape(doc, ShapeType.TextPlainText);
23             // Set up the text of the watermark.
24             watermark.TextPath.Text = watermarkText;
25             watermark.TextPath.FontFamily = "Arial";
26 
27             // 控制水印的大小
28             watermark.Width = 500;
29             watermark.Height = 60;
30 
31             // 傾斜度
32             watermark.Rotation = -15;
33 
34             // Remove the following two lines if you need a solid black text.
35             // 控制水印的顏色
36             watermark.Fill.Color = Color.Gray; // Try LightGray to get more Word-style watermark
37             watermark.StrokeColor = Color.Gray; // Try LightGray to get more Word-style watermark
38 
39             // 水平居中
40             watermark.RelativeHorizontalPosition = RelativeHorizontalPosition.Page;
41 
42             // 垂直居中 注釋后會在word正文的頭部顯示
43             //watermark.RelativeVerticalPosition = RelativeVerticalPosition.Page;
44 
45             watermark.WrapType = WrapType.None;
46 
47             // 文字的居中方式
48             watermark.VerticalAlignment = VerticalAlignment.Center;
49             watermark.HorizontalAlignment = HorizontalAlignment.Center;
50 
51             // Create a new paragraph and append the watermark to this paragraph.
52 
53             Paragraph watermarkPara = new Paragraph(doc);
54 
55             watermarkPara.AppendChild(watermark);
56 
57             // Insert the watermark into all headers of each document section.
58 
59             foreach (Section sect in doc.Sections)
60             {
61                 // There could be up to three different headers in each section, since we want
62                 // the watermark to appear on all pages, insert into all headers.
63                 InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderPrimary);
64                 InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderFirst);
65                 InsertWatermarkIntoHeader(watermarkPara, sect, HeaderFooterType.HeaderEven);
66             }
67         }
68 
69         public void InsertWatermarkIntoHeader(Paragraph watermarkPara, Section sect, HeaderFooterType headerType)
70         {
71             HeaderFooter header = sect.HeadersFooters[headerType];
72             if (header == null)
73             {
74                 // There is no header of the specified type in the current section, create it.
75                 header = new HeaderFooter(sect.Document, headerType);
76                 sect.HeadersFooters.Add(header);
77             }
78             // Insert a clone of the watermark into the header.
79             header.AppendChild(watermarkPara.Clone(true));
80         }
81         
82         #endregion
View Code

 效果如下:

 

輸出表格

這部分是重點,因為需求中經常會牽扯到輸出表格的需求。輸出表格的原理,就是先設置好表格的樣式,然后"畫"出來。實例中演示畫一個含有表頭5行4列的表格。

 1 protected void OutPutTable_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/AsposeWord.doc");
 4             Document doc = new Document(path);
 5             DocumentBuilder builder = new DocumentBuilder(doc);
 6 
 7             Aspose.Words.Font font = builder.Font;
 8             font.Bold = false;
 9             font.Size = 12;
10 
11             // 設置表格的樣式
12             builder.RowFormat.Borders.LineStyle = LineStyle.Single;
13             builder.RowFormat.HeightRule = HeightRule.Exactly;
14             builder.RowFormat.Alignment = RowAlignment.Center;
15             // 設置行高
16             builder.RowFormat.Height = 24; // 設置單元格的高度
17 
18             // 表格設置為4列 總寬度為492.7
19             double width1 = 92.7;
20             double width2 = 100;
21             double width3 = 150;
22             double width4 = 150;
23 
24             // 設置每個單元格內的樣式
25             builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
26             builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
27             builder.CellFormat.VerticalMerge = CellMerge.First;
28             builder.CellFormat.HorizontalMerge = CellMerge.None;
29 
30             // 開始畫單元格
31             builder.InsertCell();
32             // 設置單元格的寬度
33             builder.CellFormat.Width = width1;
34             // 單元格中的內容
35             builder.Write("姓名");
36 
37             builder.InsertCell();
38             builder.CellFormat.Width = width2;
39             builder.Write("證件類型");
40 
41             builder.InsertCell();
42             builder.CellFormat.Width = width3;
43             builder.Write("證件號碼");
44 
45             builder.InsertCell();
46             builder.CellFormat.Width = width4;
47             builder.Write("聯系方式");
48 
49             // 每一行結束一定要EndRow() 不然每一行的樣式會受到影響
50             builder.EndRow();
51 
52             // 輸出4行空表格
53             for (var i = 0; i < 4; i++)
54             {
55                 builder.InsertCell();
56                 builder.CellFormat.Width = width1;
57 
58                 builder.InsertCell();
59                 builder.CellFormat.Width = width2;
60 
61                 builder.InsertCell();
62                 builder.CellFormat.Width = width3;
63 
64                 builder.InsertCell();
65                 builder.CellFormat.Width = width4;
66 
67                 builder.EndRow();
68             }
69 
70             var fileName = "WaterMark(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
71             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
72         }
View Code

效果如下:

 

三、綜合實例介紹

其實還有很多的東西需要演示,比如程序輸出頁眉、頁尾等。但是篇幅實在是太大了,而且接下來還有內容。還是那句話,更多內容查看幫助文檔,我在這里就是引導

大家怎么做,上面那幾個實例掌握后,幾乎就差不多了。下面是結合上面的實例進行演示。因為實際的業務需求并沒有那么單一。

 

運用書簽輸出表格

 書簽很有用,可以讓我們在程序中通過提前設置好的書簽快速定位到要輸出的位置。

下面是一個word文檔,先設置好書簽(直接在word文檔上設置,前面已經說過說過如何設置輸錢了書簽),書簽名為"UserInfoTable",具體如下:

 1 protected void OutPutTableWidthBookMark_Click(object sender, EventArgs e)
 2         {
 3             var path = Server.MapPath("../Document/Aspose.WordBookMark.doc");
 4             Document doc = new Document(path);
 5             DocumentBuilder builder = new DocumentBuilder(doc);
 6 
 7             Aspose.Words.Font font = builder.Font;
 8             font.Bold = false;
 9             font.Size = 12;
10 
11             // 設置表格的樣式
12             builder.RowFormat.Borders.LineStyle = LineStyle.Single;
13             builder.RowFormat.HeightRule = HeightRule.Exactly;
14             builder.RowFormat.Alignment = RowAlignment.Center;
15             // 設置行高
16             builder.RowFormat.Height = 24; // 設置單元格的高度
17 
18             // 設置每個單元格內的樣式
19             builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
20             builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
21             builder.CellFormat.VerticalMerge = CellMerge.First;
22             builder.CellFormat.HorizontalMerge = CellMerge.None;
23 
24             // 定義一個存儲模板表頭每個單元格寬度的集合
25             List<double> cellWidths = new List<double>(); 
26             // 根據集合列數
27             for (int i = 0; i < 4; i++)
28             {
29                 // 參數依次是: "表格的索引"、"行的索引"、"列的索引"、"單元格內部索引"
30                 builder.MoveToCell(0, 0, i, 0); //移動單元格 (代表著表頭的cell依次移動)
31                 double width = builder.CellFormat.Width;//獲取單元格寬度
32                 cellWidths.Add(width);
33             }
34 
35             // 直接定位到書簽的位置 (根據書簽名定位的)
36             builder.MoveToBookmark("UserInfoTable");
37             // 輸出表格
38             for (var i = 0; i < 6; i++)
39             {
40                 builder.InsertCell();
41                 // 設置單元格寬度
42                 builder.CellFormat.Width = cellWidths[0];
43                 builder.Write("張三"+i);
44 
45                 builder.InsertCell();
46                 builder.CellFormat.Width = cellWidths[1];
47                 builder.Write("身份證" + i);
48 
49                 builder.InsertCell();
50                 builder.CellFormat.Width = cellWidths[2];
51                 builder.Write("ABC" + i);
52 
53                 builder.InsertCell();
54                 builder.CellFormat.Width = cellWidths[3];
55                 builder.Write("888" + i);
56 
57                 builder.EndRow();
58             }
59             // 結束表格
60             builder.EndTable();
61             // 結束書簽
62             builder.EndBookmark("UserInfoTable"); 
63 
64             var fileName = "OutPutTableWidthBookMark(" + DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ").doc";
65             doc.Save(fileName, SaveFormat.Doc, SaveType.OpenInBrowser, Response);
66         }
View Code

效果如下:

 

總結

Aspose.Word 幾乎可以解決我們各種復雜word文檔的輸出問題,以上的內容只是它的冰山一角,如果上面概括的內容滿足不了你的需求,那么就看看幫助文檔吧,或者聯系我。

這部分代碼你也可以通過開篇去下載。覺得有幫助就點擊右下角"推薦"一個。

 


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()