把數據輸出到Word (組件形式)

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

[本次實例和上次實例的源代碼,點擊這裏下載]瀏覽器

[Aspose.Words.dll 以及 使用手冊因爲太大傳到csdn上了,點這裏下載(免費)]服務器

 

文章的梗概:app

 ♦ Aspose.Words 的介紹框架

      ♦ 總體歸納ide

      ♦ 支持的平臺字體

      ♦ 支持的文件格式ui

♦ Aspose.Words 的基本使用介紹this

      ♦ 建立一個word文檔編碼

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

♦ 保存word文檔

♦ 控制word初始顯示形式

♦ 建立書籤

♦ 控制文字輸出樣式

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

♦ word文檔中添加水印

♦ 輸出表格

♦ 綜合實例介紹

♦ 運用書籤輸出表格

 

1、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多媒體格式。

 

2、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

效果以下:

 

3、綜合實例介紹

其實還有不少的東西須要演示,好比程序輸出頁眉、頁尾等。可是篇幅實在是太大了,並且接下來還有內容。仍是那句話,更多內容查看幫助文檔,我在這裏就是引導

你們怎麼作,上面那幾個實例掌握後,幾乎就差很少了。下面是結合上面的實例進行演示。由於實際的業務需求並無那麼單一。

 

運用書籤輸出表格

 書籤頗有用,可讓咱們在程序中經過提早設置好的書籤快速定位到要輸出的位置。

下面是一個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文檔的輸出問題,以上的內容只是它的冰山一角,若是上面歸納的內容知足不了你的需求,那麼就看看幫助文檔吧,或者聯繫我。

這部分代碼你也能夠經過開篇去下載。以爲有幫助就點擊右下角"推薦"一個。

相關文章
相關標籤/搜索