Work with Aspose.word controls to implement Word documents

Source: Internet
Author: User

Aspose series of controls, the function is very good, has been in my WinForm development framework with Aspose.cell to do report output, can achieve a variety of report design and output, because the general output of the content is more formalized or most of the table is mostly, so the general use of Aspose.cell to achieve the various Excel report I want to output. Although it is always known that Aspose.word is used to generate Word documents, and convinced that it is also a very powerful control, but has been useless, so it is not very familiar.

Once in a while, the report function of an item specifies that it needs to be exported as a Word document, so a lot of articles are searched, but most of the introductions are relatively simple, so they also refer to the official Help introduction, which finally satisfies the customer's needs. Let me introduce the process of using this control in the actual business.

1. Word operations for two-dimensional tables

Daily, the common content output is the way of two-dimensional table, the table header is fixed, the content of each line, then in the actual use of the control we how to operate it, in fact, this control this aspect of the article a lot of information, reference can be made. In fact, this is to introduce the importance of the specification, this is also the case in the Aspose.cell control, bookmarks can be used in addition to replace the content, but also to mark the beginning of the content input and other functions.

First we draw a table header in a blank Word document, and then we insert a label reference at the beginning of the wrapping and insert a bookmark in two ways, one in Word (2007, 2010) in insert-bookmark, and a bookmark reference to the location, as shown below.

One is to add additional commands on the Custom Quick Access Toolbar in Word, as shown in the following steps

The former inserted bookmark is no text or special tags, but it does exist, the latter will insert a gray block as a placeholder, as shown below, I this two-dimensional table in the example of the use of the latter to test (both the same effect)

Now that you've designed your Word template, the next step is to create a two-dimensional table with code. First of all, I deliberately set the width of each table cell is different, so it is required to generate the row and the head corresponding, so the table generated each row, must be to get the corresponding column style properties, otherwise it will not correspond. See the code below.

try {Aspose.Words.Document doc = new Aspose.Words.Document (templatefile);                    Aspose.Words.DocumentBuilder builder = new Aspose.Words.DocumentBuilder (DOC);                    DataTable namelist = datatablehelper.createtable ("number, name, time");                    DataRow row = null;                        for (int i = 0; i < i++) {row = Namelist.newrow (); row["number"] = i.ToString ().                        PadLeft (4, ' 0 ');                        row["name"] = "Wu Huacong" + i.tostring ();                        row["Time"] = 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); Move cell double width = builder. CellfoRmat.                    width;//gets the cell width widthlist.add (width); } builder.        MoveToBookmark ("table"); Start adding values for (var i = 0; i < NameList.Rows.Count; i++) {fo R (var j = 0; J < NameList.Columns.Count; J + +) {Builder. InsertCell ();//Add a cell 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;//Vertical Center alignment builder. ParagraphFormat.Alignment = paragraphalignment.center;//Horizontal HabitatIn the Align Builder. Write (Namelist.rows[i][j].                        ToString ()); } builder.                    Endrow (); } doc. range.bookmarks["Table"].    Text = ""; Clear out the Mark Doc.                    Save (Savedocfile); if (Messageutil.showyesnoandtips ("Save succeeded, do you want to open the file?") ") = = System.Windows.Forms.DialogResult.Yes) {System.Diagnostics.Process.Start (                    Savedocfile);                    }} catch (Exception ex) {loghelper.error (ex); Messageutil.showerror (ex.                    Message);                Return }

The steps for the above code are

1) Create the Aspose.Words.Document and Aspose.Words.DocumentBuilder objects, and then generate the two-dimensional tabular contents of the data.

2) traverse the Template table, or the width of each column for later use.

3) move to the bookmark position of the table and start entering the data, each cell in the Word table requires a style and width to match the table head.

4) Save the file contents to the new file.

The effect of the output is as follows.

2. Operation of Cell merging

Common Word files, or Excel files, often see the contents of merged cells, so this section is also a very common operation that must be mastered.

Let's look at an example code and effect.

                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 was vertically merged to the cell above and should was 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 ("Save succeeded, do you want to open the file?") ") = = System.Windows.Forms.DialogResult.Yes) {System.Diagnostics.Process.Start (                    Savedocfile); }} catch (Exception ex) {LoghelpEr.                    Error (ex); Messageutil.showerror (ex.                    Message);                Return }

His effect is as follows

For the introduction of merged cells, you can also refer to the following official introduction: Http://www.aspose.com/docs/display/wordsnet/Working+with+Merged+Cells

If the above example is not clear enough, OK, I am introducing a practical example to illustrate the operation mode of the merged cell.

The actual document generation is as follows:

The template for the document is as follows:

In fact, this "test" content is written using code, is actually a line of business data, with two lines to show, some of the merged cells, which is a real project table Form. We note that there are 13 cells in each row, where the first, second, and 13th columns are merged columns. and side-by-side feature is that its two indexes are valid, but only can use the first index to manipulate it to copy, take advantage of the second useless.

such as the first column is and side by side, it should have 0, 13 such index, the second column is also and side by side, it also has 1, 14 index, other analogy.

After understanding such a logical relationship, we look at the actual operation code as shown below.

                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 <; i++) {Builder. Movetocell (0, 2, I, 0); Move cell double width = builder.                    cellformat.width;//gets the cell width widthlist.add (width); } builder.        MoveToBookmark ("table"); Start adding values to table table = Builder.                    Starttable (); Builder.                    Rowformat.headingformat = true; Builder.                    ParagraphFormat.Alignment = Paragraphalignment.center; for (int j = 0; J <; J + +) {Builder.                   InsertCell ();//Add a cell                         Builder.                        CellFormat.Borders.LineStyle = Linestyle.single; Builder.                        CellFormat.Borders.Color = System.Drawing.Color.Black; int cellindex = (J > 12)? (J-13): J; Located in the first few cell builder.                        Cellformat.width = Widthlist[cellindex]; Builder. cellformat.verticalalignment = cellverticalalignment.center;//Vertical Center alignment builder. ParagraphFormat.Alignment = paragraphalignment.center;//Horizontal Center aligns the builder.                        Cellformat.verticalmerge = Aspose.Words.Tables.CellMerge.None; if (CellIndex = = 0 | | cellindex = = 1 | | cellindex = =) {if (J > 12 ) {Builder.                            Cellformat.verticalmerge = cellmerge.previous; } else {Builder. CellfOrmat.                            Verticalmerge = Cellmerge.first; }} builder.                        Write ("Test" + j.tostring ()); if (CellIndex = =) {Builder.                        Endrow (); }} builder.                    Endtable (); Doc.                    Save (Savedocfile); if (Messageutil.showyesnoandtips ("Save succeeded, do you want to open the file?") ") = = System.Windows.Forms.DialogResult.Yes) {System.Diagnostics.Process.Start (                    Savedocfile);                    }} catch (Exception ex) {loghelper.error (ex); Messageutil.showerror (ex.                    Message);                Return }

Work with Aspose.word controls to implement Word documents

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.