利用Aspose.Word控件實現Word文檔的操作


Aspose系列的控件,功能都挺好,之前一直在我的Winform開發框架中用Aspose.Cell來做報表輸出,可以實現多樣化的報表設計及輸出,由於一般輸出的內容比較正規化或者多數是表格居多,所以一般使用Aspose.Cell來實現我想要的各種Excel報表輸出。雖然一直也知道Aspose.Word是用來生成Word文檔的,而且深信其也是一個很強大的控件,但一直沒用用到,所以就不是很熟悉。

偶然一次機會,一個項目的報表功能指定需要導出為Word文檔,因此尋找了很多篇文章,不過多數介紹的比較簡單一點,於是也參考了官方的幫助介紹,終於滿足了客戶的需求。下面我由淺入深來介紹這個控件在實際業務中的使用過程吧。

1、二維表格的Word操作

日常中,常見的內容輸出就是二維表格的方式,表頭比較固定,內容每行一條,那么在實際的使用控件我們該如何操作呢,其實這個控件這方面介紹的文章很多,參考一下就能做出來了。其實介紹這個就是要說明書簽的重要性,這個在Aspose.Cell控件也是如此,書簽除了可以用來替換內容,還可以用來標記內容輸入的開始位置等等功能。

首先我們在一個空白的Word文檔中繪制一個表格頭,然后再換行的開始插入一個標簽引用,插入書簽有兩種方式,一種是在Word(2007、2010)的【插入】-【書簽】中插入制定位置的書簽引用,如下所示。

一種是在Word的自定義快速訪問工具欄上添加其他命令,如下步驟所示

前者插入的書簽是沒有文字或者特別的標記,但是確實存在,后者會插入一個灰色塊作為占位符,如下所示,我這這個二維表格的例子里面使用后者進行測試(兩者同等效果的)

這樣設計好Word模板后,下一步就是如何利用代碼生成二維表格了。首先這里提示一下,就是我故意設置了每個表格單元格的寬度不同,所以也就要求生成的行要和頭部對應,所以表格生成每行之前,肯定要獲得對應列的樣式屬性的,否則就會對應不上了。下面看代碼。

復制代碼
try
                {
                    Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                    Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);

                    DataTable nameList = DataTableHelper.CreateTable("編號,姓名,時間");
                    DataRow row = null;
                    for (int i = 0; i < 50; i++)
                    {
                        row = nameList.NewRow();
                        row["編號"] = i.ToString().PadLeft(4, '0');
                        row["姓名"] = "伍華聰 " + i.ToString();
                        row["時間"] = DateTime.Now.ToString();
                        nameList.Rows.Add(row);
                    }
                    
                    List<double> widthList = new List<double>();
                    for (int i = 0; i < nameList.Columns.Count; i++)
                    {
                        builder.MoveToCell(0, 0, i, 0); //移動單元格
                        double width = builder.CellFormat.Width;//獲取單元格寬度
                        widthList.Add(width);
                    }                    
                    
                    builder.MoveToBookmark("table");        //開始添加值
                    for (var i = 0; i < nameList.Rows.Count; i++)
                    {
                        for (var j = 0; j < nameList.Columns.Count; j++)
                        {
                            builder.InsertCell();// 添加一個單元格                    
                            builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                            builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                            builder.CellFormat.Width = widthList[j];
                            builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                            builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中對齊
                            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中對齊
                            builder.Write(nameList.Rows[i][j].ToString());
                        }
                        builder.EndRow();
                    }
                    doc.Range.Bookmarks["table"].Text = "";    // 清掉標示  

                    doc.Save(saveDocFile);
                    if (MessageUtil.ShowYesNoAndTips("保存成功,是否打開文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDocFile);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                    return;
                }
復制代碼

以上代碼的步驟就是

1)創建Aspose.Words.Document 和 Aspose.Words.DocumentBuilder對象,然后生成數據的二維表格內容。

2)遍歷模板表格,或者每一列的寬度,以備后用。

3)移動到表格的書簽位置,然后開始錄入數據,Word表格的每個Cell都要求制定樣式和寬度,這樣才能和表格頭部吻合。

4)保存文件內容到新的文件里面即可。

輸出的效果如下所示。

2、單元格合並的操作

常見的Word文件或者Excel文件中,都經常看到合並單元格的內容,因此這個部分也是非常常見的操作,必須掌握。

我們先看一個例子代碼及效果。

復制代碼
                try
                {
                    Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                    Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);

                    builder.InsertCell();
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                    builder.CellFormat.VerticalMerge = CellMerge.First;
                    builder.Write("Text in merged cells.");

                    builder.InsertCell();
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                    builder.CellFormat.VerticalMerge = CellMerge.None;
                    builder.Write("Text in one cell");
                    builder.EndRow();

                    builder.InsertCell();
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                    // This cell is vertically merged to the cell above and should be empty.
                    builder.CellFormat.VerticalMerge = CellMerge.Previous;

                    builder.InsertCell();
                    builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                    builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                    builder.CellFormat.VerticalMerge = CellMerge.None;
                    builder.Write("Text in another cell");
                    builder.EndRow();

                    doc.Save(saveDocFile);
                    if (MessageUtil.ShowYesNoAndTips("保存成功,是否打開文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDocFile);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                    return;
                }
復制代碼

他的效果如下

關於合並單元格的介紹,你還可以參考下這篇官方介紹:http://www.aspose.com/docs/display/wordsnet/Working+with+Merged+Cells

如果上面的例子還不夠明白,OK,我在介紹一個實際的例子,來說明合並單元格的操作模式。

實際文檔生成如下所示:

文檔的模板如下所示:

其實這個里面的“測試”內容是使用代碼寫入的,其實就是一行業務數據,用兩行來展示,其中有些合並的單元格,這是一個實際項目的表格形式。我們注意到,每行有13個單元格,其中第一、第二、第十三列是合並列。和並列有一個特點,就是它的兩個索引都有效,不過只是能使用第一個索引來對它進行操作復制,利用第二個沒有用處的。

如第一個列是和並列,它應該有0、13這樣的索引,第二列也是和並列,它也有1、14的索引,其他的類推。

了解這樣的邏輯關系后,我們看實際操作的代碼如下所示。

復制代碼
                try
                {
                    Aspose.Words.Document doc = new Aspose.Words.Document(templateFile);
                    Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder(doc);
                    
                    List<double> widthList = new List<double>();
                    for (int i = 0; i < 13; i++)
                    {
                        builder.MoveToCell(0, 2, i, 0); //移動單元格
                        double width = builder.CellFormat.Width;//獲取單元格寬度
                        widthList.Add(width);
                    }

                    builder.MoveToBookmark("table");        //開始添加值

                    Table table = builder.StartTable();
                    builder.RowFormat.HeadingFormat = true;
                    builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;

                    for (int j = 0; j < 26; j++)
                    {
                        builder.InsertCell();// 添加一個單元格                    
                        builder.CellFormat.Borders.LineStyle = LineStyle.Single;
                        builder.CellFormat.Borders.Color = System.Drawing.Color.Black;
                        int cellIndex = (j > 12) ? (j-13) : j; //位於第幾個單元格
                        builder.CellFormat.Width = widthList[cellIndex];
                        builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;//垂直居中對齊
                        builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;//水平居中對齊

                        builder.CellFormat.VerticalMerge = Aspose.Words.Tables.CellMerge.None;
                        if (cellIndex == 0 || cellIndex == 1 || cellIndex == 12)
                        {
                            if (j > 12)
                            {
                                builder.CellFormat.VerticalMerge = CellMerge.Previous;
                            }
                            else
                            {
                                builder.CellFormat.VerticalMerge = CellMerge.First;
                            }
                        }
 
                        builder.Write("測試" + j.ToString());
                        if (cellIndex == 12 )
                        {
                            builder.EndRow();
                        }
                    }
                    builder.EndTable();

                    doc.Save(saveDocFile);
                    if (MessageUtil.ShowYesNoAndTips("保存成功,是否打開文件?") == System.Windows.Forms.DialogResult.Yes)
                    {
                        System.Diagnostics.Process.Start(saveDocFile);
                    }
                }
                catch (Exception ex)
                {
                    LogHelper.Error(ex);
                    MessageUtil.ShowError(ex.Message);
                    return;
                }
復制代碼

 

 


免責聲明!

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



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