C # export Word [irregular table structure + template]

Source: Internet
Author: User
Tags httpcontext

1) Of course you can consider using Aspose.word. Replaces the bookmark value in the template with a schema replaced by a bookmark.

2) But I used the Interop.word, the following record uses the class and the place to notice

3) Use class

Report.cs from the Web modified the focus moves to the end and creates a new page when adding a table
Using system;using system.collections.generic;using system.text;using microsoft.office.interop.word;namespace Song_        Public//This side needs to be replaced by its own namespace name {public class Report {private _application WordApp = null;        Private _document worddoc = null;            Public _application Application {get {return wordapp;            } set {WordApp = value;            }} public _document Document {get {return worddoc;            } set {WordDoc = value; }//Create new document from template public void CreateNewDocument (string filePath) {killwinwordprocess            ();            WordApp = new ApplicationClass ();            Wordapp.displayalerts = Wdalertlevel.wdalertsnone;            Wordapp.visible = false;            Object missing = System.Reflection.Missing.Value; Object templatename = FilePath; WordDoc = WordApp.Documents.Open (ref templatename, ref missing, ref missing, ref missing, ref missing, ref mi Ssing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing        , ref missing, ref missing, ref missing);            }//Save new file public void SaveDocument (string filePath) {Object fileName = FilePath;            Object format = wdsaveformat.wdformatdocument;//Save Format Object miss = System.Reflection.Missing.Value;              Worddoc.saveas (ref fileName, ref format, ref miss, ref miss, ref miss, ref miss, ref miss,            Ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);            Close Worddoc,wordapp Object SaveChanges = wdsaveoptions.wdsavechanges;            Object originalformat = Wdoriginalformat.wdoriginaldocumentformat; Object RoutedocumenT = false;            Worddoc.close (ref SaveChanges, ref originalformat, ref routedocument);        Wordapp.quit (ref SaveChanges, ref originalformat, ref routedocument); }//Insert value at Bookmark public bool Insertvalue (string bookmark, String value) {Object bkobj = Bookma            Rk if (wordApp.ActiveDocument.Bookmarks.Exists (bookmark)) {wordApp.ActiveDocument.Bookmarks.get_It EM (ref bkobj).                Select ();                WordApp.Selection.TypeText (value);            return true;        } return false;            }//Insert table, bookmark Public table inserttable (string bookmark, int rows, int columns, float width) {            Object miss = System.Reflection.Missing.Value;            Object ostart = Bookmark; Range range = WordDoc.Bookmarks.get_Item (ref Ostart). range;//Table Insert position//Range range = WordDoc.Bookmarks.get_Item (ref Ostart). range;//Table Insert position//WordApp.Selection.EnDkey (6, 0);            WordApp.Selection.EndKey (wdunits.wdstory);            WordApp.Selection.InsertNewPage ();            Object start = 0;            Object end = 0;            Range tablelocation = Worddoc.range (ref start, ref end);            Table newtable = WORDDOC.TABLES.ADD (wordApp.Selection.Range, rows, columns, ref miss, ref miss); Format the table newTable.Borders.Enable = 1; Allow border, default no border (for 0 times wrong, 1 is a solid border, 2, 3 is a dashed border, after the number has not been tried) NewTable.Borders.OutsideLineWidth = wdlinewidth.wdlinewidth050pt            ;//Border Width if (width! = 0) {newtable.preferredwidth = width;//table Width}            Newtable.allowpagebreaks = false;            object omissing = System.Reflection.Missing.Value;            Wordapp.visible = true;            WordDoc = WORDAPP.DOCUMENTS.ADD (ref omissing, ref omissing, ref omissing, ref omissing);            Object start = 0;            Object end = 0; Microsoft.Office.Interop.Word.RaNge tablelocation = Worddoc.range (ref start, ref end);            Table newtable = WORDDOC.TABLES.ADD (tablelocation, rows, columns, ref omissing, ref omissing);        return newtable; }///<summary>///Add a new Table reference///</summary> public table addtable (int rows, int            Columns) {object omissing = System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Application WordApp;            Microsoft.Office.Interop.Word.Document WordDoc;            WordApp = new Microsoft.Office.Interop.Word.ApplicationClass ();            Wordapp.visible = true;            WordDoc = WORDAPP.DOCUMENTS.ADD (ref omissing, ref omissing, ref omissing, ref omissing);            Object start = 0;            Object end = 0;            Microsoft.Office.Interop.Word.Range tablelocation = Worddoc.range (ref start, ref end);  Table newtable = WORDDOC.TABLES.ADD (tablelocation, rows, columns, ref omissing, ref omissing),//3 row 4 columns                                                                                                        Format a table newTable.Borders.Enable = 1; Allow border, default no border (for 0 times wrong, 1 is a solid border, 2, 3 is a dashed border, after the number has not been tried) NewTable.Borders.OutsideLineWidth = wdlinewidth.wdlinewidth050pt            ;//Border Width Newtable.allowpagebreaks = false;        return newtable; }//Merge cell table name, start line number, start column number, end line number, end column number public void Mergecell (Microsoft.Office.Interop.Word.Table table, int row1, int column1, int row2, int column2) {table. Cell (Row1, Column1). Merge (table.        Cell (Row2, column2)); }//Set table content alignment align Horizontal, vertical vertical (left, center, right, respectively align and vertical values are -1,0,1) public void setparagraph_table        (Microsoft.Office.Interop.Word.Table Table, int Align, int Vertical) {switch (Align) {case-1: table. Range.ParagraphFormat.Alignment = Wdparagraphalignment.wdalignparagraphleft; break;//left-justified case 0:table. Range. ParagraphFormat.Alignment = Wdparagraphalignment.wdalignparagraphcenter; break;//Horizontal Center Case 1:table. Range.ParagraphFormat.Alignment = Wdparagraphalignment.wdalignparagraphright; break;//right-justified} switch (Vertical) {case-1: table. Range.Cells.VerticalAlignment = Wdcellverticalalignment.wdcellalignverticaltop; break;//top-aligned case 0:table. Range.Cells.VerticalAlignment = Wdcellverticalalignment.wdcellalignverticalcenter; break;//Vertical Center Case 1:table. Range.Cells.VerticalAlignment = Wdcellverticalalignment.wdcellalignverticalbottom; break;//Bottom Alignment}}//Set table font public void setfont_table (Microsoft.Office.Interop.Word.Table ta BLE, string fontname, double size) {if (size! = 0) {table.            Range.Font.Size = Convert.tosingle (Size); } if (FontName! = "") {table.      Range.Font.Name = FontName;      }}//whether to use a border, n the ordinal of the table, using Yes or no public void useborder (int n, bool use) {if (use) {Worddoc.content.tables[n]. Borders.Enable = 1; Allow borders, default no border (0 o'clock no border, 1 is a solid border, 2, 3 is a dashed border, the subsequent number has not been tried)} else {worddoc.content.t Ables[n]. Borders.Enable = 2; Allow a border, the default is no border (0 o'clock no border, 1 is a solid border, 2, 3 is a dashed border, the subsequent number has not been tried)}//Insert a row for the table, n table ordinal starting from 1 public void AddR            ow (int n) {object miss = System.Reflection.Missing.Value; Worddoc.content.tables[n].            Rows.Add (ref miss); Worddoc.content.tables[n]. Rows.height = 100;//Sets the height of the newly added line of the table}//Adds a row to the table public void AddRow (Microsoft.Office.Interop.Word.Table            Table) {Object miss = System.Reflection.Missing.Value; Table.            Rows.height = 40; Table.        Rows.Add (ref miss);    }//Insert rows to table, n is the ordinal of the table public void AddRow (int n, int rows) {        Object miss = System.Reflection.Missing.Value;            Microsoft.Office.Interop.Word.Table Table = Worddoc.content.tables[n]; for (int i = 0; i < rows; i++) {table.            Rows.Add (ref miss); }}//For cells inserted in table, table, row row number, column number, value insert element public void InsertCell (Microsoft.Office.Interop . word.table table, int row, int column, string value) {table. Cell (row, column).        Range.Text = value; }//Insert elements into table cells, n table ordinal starting from 1, row line number, column column number, value inserted element public void InsertCell (int n, int row, int column, str ing value) {Worddoc.content.tables[n]. Cell (row, column).        Range.Text = value; }//Insert a row of data into the table, n is the ordinal of the table, row row number, columns column number, values insert the value of public void InsertCell (int n, int row, int columns, string[            ] values) {Microsoft.Office.Interop.Word.Table Table = worddoc.content.tables[n];            for (int i = 0; i < columns; i++){table. Cell (row, i + 1).            Range.Text = Values[i];        }}//Insert Picture public void InsertPicture (string bookmark, string picturepath, float width, float hight)            {Object miss = System.Reflection.Missing.Value;            Object ostart = Bookmark;    Object LinkToFile = false; Whether the picture is an external link Object savewithdocument = true; Whether the picture is saved with the Document Object range = WordDoc.Bookmarks.get_Item (ref Ostart).            range;//Picture insertion position wordDoc.InlineShapes.AddPicture (PicturePath, ref linktofile, ref savewithdocument, ref range); WORDDOC.APPLICATION.ACTIVEDOCUMENT.INLINESHAPES[1]. width = width; Set picture width worddoc.application.activedocument.inlineshapes[1]. Height = hight;            Set picture Height}//Insert a paragraph of text, text content public void InsertText (string bookmark, string text) {            Object ostart = Bookmark; Object range = WordDoc.Bookmarks.get_Item (ref Ostart).            Range; Paragraph WP = WORDDOC.CONTENT.PARAGRAPHS.ADD (ref range); Wp.            Format.spacebefore = 6; Wp.            Range.Text = Text; Wp.            Format.spaceafter = 24; Wp.            Range.insertparagraphafter ();        WordDoc.Paragraphs.Last.Range.Text = "\ n"; }//Kill Winword.exe process public void killwinwordprocess () {system.diagnostics.process[] Proces            SES = System.Diagnostics.Process.GetProcessesByName ("Winword"); foreach (System.Diagnostics.Process process in processes) {bool b = Process.                MainWindowTitle = = ""; if (process. MainWindowTitle = = "") {process.                Kill (); }            }        }    }}

4) How to use

1) Import values by bookmark bookmark settings See below

            Report report = new report ();            var path = System.Web.HttpContext.Current.Server.MapPath ("/files/word/2.doc");            var Savapath = System.Web.HttpContext.Current.Server.MapPath ("/files/word/" + randomstr.getserialnumber (4) + ". Doc"); Report            . CreateNewDocument (path); Template path Report            . Insertvalue ("Name", "World Cup");//Insert a value at the bookmark "name"

2) Import Table

Table table2 = report. Inserttable ("Table2", 4, 4, 0); Insert 2 rows 3 Lexian at the bookmark "Table2"

3) Import Tabular data

Report. InsertCell (Table2, 1, 1, "project name");//table name, line number, column number, value

4) Merging cells

5) Set the font size

Report. Setfont_table (Table2, "Song Body", 11);//Arial 14 lbs

6) Document saving

Report. SaveDocument (Savapath);

7) can be modified in the class jingle

  Table. Rows.height = 40; To modify the height of the current row when adding rows AddRow method
Inserttable method to change the location of a bookmark back to add a table this method does not apply to export of multiple tables
Public Table inserttable (string bookmark, int rows, int columns, float width)        {            object miss = System.Reflection.Mi Ssing. Value;            Object ostart = bookmark;            Range range = WordDoc.Bookmarks.get_Item (ref Ostart). range;//table insertion Position            Table newtable = WORDDOC.TABLES.ADD (range, rows, columns, ref miss, ref miss);            Format table            newTable.Borders.Enable = 1;//allow border, default no border (0 times wrong, 1 is a solid line border, 2, 3 is a dashed border, the future number has not been tried)            NewTable.Borders.OutsideLineWidth = wdlinewidth.wdlinewidth050pt;//Border Width            if (width! = 0)            {                Newtable.preferredwidth = width;//table width            }            newtable.allowpagebreaks = false;            return newtable;        }

  

WordApp.Selection.EndKey (wdunits.wdstory); // focus on the end of the document

5) Attention points

1) Table is nested when the table is exported

Cause: The location of the focus after the table import is done by default will be inserted in the table in the secondary insert will result in nested

Solution: Focus on the end of the document WordApp.Selection.EndKey (wdunits.wdstory);

2) The requested member does not exist at the time of the merger

Cause: The previous item in the table is merged with the column values before merging the multicolumn columns. I'm sure I can't find them

Workaround: Output the corresponding column and value first, and finally the merge process. Each merge is recorded, and the number of merge columns for the current row is as follows

                    Handle Merge                    var pans = 0;//Combined number of                    foreach (Var o in lo)   //lo as a list<other>                        {report                        . Mergecell (Table2, O.row, O.col1-pans, O.row, O.col2-pans);                        pans++;                    }

3) Insertion of bookmarks

word-> Insert, bookmark, enter bookmark name, add

C # export Word [irregular table structure + template]

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.