C # operate Word documents

Source: Internet
Author: User
1. First pass Program Generate the HTML page of the report style, and modify the HTML page suffix to Doc.
2. Customize the template file of the Word document, operate the Word template in C #, and generate a new word document.
The first scheme is simple. You only need to modify the file extension, but there are also some problems, such as the loss of the generated Word Document Style. This may be an insurmountable solution for the customer. The second solution is complicated. You need to call the word component of the Office to operate the word through C #, and then generate the word. This method is similar to splicing data in the C # background. Although difficult, it is only a word object that can be customized flexibly.
After repeated consideration, we decided to use the second method to generate a word report document.
Through our own practice, this demand is finally settled. In the actual development process, we encountered such a problem. Fortunately, by constantly searching for network resources, the problem was solved based on actual development conditions. I will summarize some of my understanding and experience in the development process:
In vs2008 platform, reference. net-Microsoft.Office.Interop.Word.12, so that you can operate the word object in the program.
After simple execution, error 80070005 is reported. This error is due to insufficient permissions. You need to change the operation permissions of. NET and IIS users in DCOM configuration. The specific modification process is as follows: solution 1:
1. choose Control Panel> Administrative Tools> component service> Computer> my computer> DCOM configuration> Microsoft Word documents, and click Properties to open the Properties dialog box for this application.
2. Click the ID tab and select an interactive user.
3. click the "Security" tab, select "Custom" in the "Start and activate Permissions" and "Access Permissions" groups, and then click "edit"> Add ASP. net account and iuser_computer name.
4. Make sure that each user is allowed to access the service and click OK.
5. Click OK to disable dcomcnfg.
If the above method cannot solve the problem, it should be a permission problem. Please try the following method:
Use identity simulation in Web. config and add <identity impersonate = "true" username = "your username" Password = "password"/> In the <system. Web> section.
</System. Web>
After solving the above problems, we began to consider how to create a Word template file. The Word template file actually uses bookmarks to add content. That is, by creating bookmarks in the Word document, and then getting all bookmarks in the template file in the program, the document is generated by assigning values to the bookmarks.
The procedure in the program is as follows:
Declare the object of the Word program → declare a Word document object → get the current operation Composition Object → get all the bookmarks of the document → assign database data to the corresponding bookmarks → Save the document as a specified folder.
The following is a detailed analysis of the agricultural plant test report. Code Implementation: Copy code The Code is as follows: // generate a Word program object and a Word Document Object
Microsoft. Office. InterOP. Word. Application appword = new application ();
Microsoft. Office. InterOP. Word. Document Doc = new document ();
Object omissing = system. reflection. Missing. value; // What is this? I have never understood -_-
// Open the template document and specify the doc document type
Object objtemplate = server. mappath (p_templatepath );
Object objdoctype = wddocumenttype. wdtypedocument;
Doc = (document) appword. Documents. Add (ref objtemplate, ref objfalse, ref objdoctype, ref objtrue );
// Obtain all bookmarks in the template
Bookmarks ODF = Doc. bookmarks;
String [] testtableremarks = {"applyno", "auditingdate", "auditor", "checkdate", "checker "};
String [] testtablevalues = {"applyno", "auditingdate", "auditor", "checkdate", "checker ",};
// Loop all bookmarks and assign values to the bookmarks
For (INT oindex = 0; oindex <testtableremarks. length; oindex ++)
{
Obdd_name = WD + testtableremarks [oindex];
Doc. bookmarks. get_item (ref obdd_name ). range. TEXT = p_testreporttable.rows [0] [testtablevalues [oindex]. tostring (); // here, range is an important object in word, that is, the region where the current operation parameter is located.
}
// Generate the word in Step 4, save the current document object as the specified path, and then close the doc object. Close the application
Object filename = server. mappath (p_savepath) + "\ Testing _" + datetime. Now. tow.datestring () + ". Doc ";
Object Miss = system. reflection. Missing. value;
Doc. saveas (ref filename, ref miss, ref miss, ref miss, ref Miss );
Object missingvalue = type. missing;
Object donotsavechanges = wdsaveoptions. wddonotsavechanges;
Doc. Close (ref donotsavechanges, ref missingvalue, ref missingvalue );
Appword. application. Quit (ref miss, ref miss, ref Miss );
Doc = NULL;
Appword = NULL;
This. hid_showmessage.value = "generated successfully! ";

The above code is a process of generating word through the template file. It is actually a process of replacing the content of the bookmarks.
During the development process, some data is dynamically added. If I want to dynamically add several rows of data to a table, I cannot use the bookmark replacement method for operations, you need to add rows in the table on the document page through the program.
You can add rows to a table in either of the following ways: A table already exists in the Word template. One is to add a table object directly in the program.
In the first case, note that the tables to be operated in the Word template cannot have vertically merged cells. Otherwise, the program cannot obtain the objects to be operated, causing an error in the program. cell merging can be controlled in the program.
In the second case, we need to add tables directly through the program.
The code for generating a table is as follows:
1. Obtain an existing table in the document:
Microsoft. office. interOP. word. table charactertable = Doc. tables [2]; // In the document object set operation, the starting point is from 1, not from 0. note this.
2. Generate a table directly in the Document. first obtain the location of the inserted table, and then add the table object:
Object oendofdoc = "\ endofdoc"; // There are many pre-defined bookmarks in word, which are not listed here.
Object omissing = system. reflection. Missing. value;
Range wrdrng = Doc. bookmarks. get_item (ref oendofdoc). range; // obtain the end position of the current document.
Wrdrng. insertafter (""); // insert a row. wrdrng. insertafter ("") cannot be used here. If this is used, the line feed cannot be used, and I don't know why.Copy code The Code is as follows: Object ocollapseend = Microsoft. Office. InterOP. Word. wdcollapsedirection. wdcollapseend;
Object opagebreak = Microsoft. Office. InterOP. Word. wdbreaktype. wdpagebreak; // a paging character
Wrdrng. Collapse (ref ocollapseend );
Wrdrng. insertbreak (ref opagebreak); // insert a page
Wrdrng. Collapse (ref ocollapseend );
Wrdrng. insertafter ("image information ");
Wrdrng. Font. size = 20; // specify the text size of the operation object
Wrdrng. Font. Bold = 1; // specifies the bold type of the operation object: 1 is bold, 0 is normal
Wrdrng. paragraphformat. Alignment = wdparagraphalignment. wdalignparagraphcenter; // specify the text layout of the operation area: Center-aligned
// The code above indicates: locate the current end position and insert a paging character, which is equivalent to jumping to a new page and writing the text "Image Information" at the top of the new page ", specify the text size to 20 and center the text in bold.
Wrdrng = Doc. bookmarks. get_item (ref oendofdoc). range;
Wrdrng. insertafter ("");
Wrdrng = Doc. bookmarks. get_item (ref oendofdoc). range;
Wrdrng. insertparagraphafter (); // insert a paragraph to insert a table with two rows and one column.
Microsoft. Office. InterOP. Word. Table newtable = Doc. Tables. Add (wrdrng, 2, 1, ref omissing, ref omissing );

We can also set the format of the table, which is not listed here.
3. Next we will analyze the operations on the cells in the Table: Merge and split. This requires us to operate based on the actual table:
// Obtain a specific cell () and obtain the cell in the first column of the First row
Cell cell = Doc. Tables [1]. Cell (1, 1 );
Cell. range. Text = "text"; // specify the content of the current cell as text
In the table operation, add a new row:
Object beforerow = Doc. Tables [1]. Rows [2]; // This row is obtained first to the second row.
Doc. tables [1]. rows. add (ref beforerow); // The effect is similar to the insert row operation on the second row of the table in word. The new row is inserted into the previous row of the current row, the format is the same as that of this line.
// Merge cells: it seems silly to merge cells here. You only need to specify the start and end cells to be merged, and then perform the merge operation.
Cell cell = Doc. Tables [1]. Cell (irow, 2); // column merge
Cell. Merge (Doc. Tables [1]. Cell (irow, 6 ));
Cell cell1 = Doc. Tables [1]. Cell (irow-1, 1); // merge rows
Cell1.merge (Doc. Tables [1]. Cell (irow + 1, 1 ));
The above operations are some of the knowledge points used in this program, and there are many things to be familiar with and understand.
In addition, it is found in the program test process that the winword.exe process cannot be killed in the resource manager after the execution of the audit file is generated. The current solution is to directly kill the process. The Code is as follows: Copy code The Code is as follows: protected void killallprocess () // kill all winword.exe Processes
{
System. Diagnostics. Process [] myps;
Myps = system. Diagnostics. process. getprocesses ();
Foreach (system. Diagnostics. Process P in myps)
{
If (P. ID! = 0)
{
String mys = "winword. EXE" + P. processname + "ID:" + P. Id. tostring ();
Try
{
If (P. Modules! = NULL)
If (P. modules. Count> 0)
{
System. Diagnostics. processmodule PM = P. modules [0];
MYS + = "\ n modules [0]. filename:" + Pm. filename;
MYS + = "\ n modules [0]. modulename:" + Pm. modulename;
MYS + = "\ n modules [0]. fileversioninfo: \ n" + Pm. fileversioninfo. tostring ();
If (PM. modulename. tolower () = "winword.exe ")
P. Kill ();
}
}
Catch
{}
Finally
{
}
}
}
}

So far, a Word document is generated. The above problems and solutions I encountered in this program development may be incomplete in many aspects. If you have a new understanding of word operations in program development, welcome to communicate with me and improve each other!
Below are some good excerpts on the Internet:
Create a new wordCopy codeThe Code is as follows: Object omissing = system. reflection. Missing. value;
Word. _ application oword;
Word. _ document odoc;
Oword = new word. Application ();
Oword. Visible = true;
Odoc = oword. Documents ENTs. Add (ref omissing, ref omissing,
Ref omissing, ref omissing );

Open the document:Copy codeThe Code is as follows: Object omissing = system. reflection. Missing. value;
Word. _ application oword;
Word. _ document odoc;
Oword = new word. Application ();
Oword. Visible = true;
Object filename = @ "E: cccxcxxtestdoc.doc ";
Odoc = oword. Documents. Open (ref filename,
Ref omissing, ref omissing,
Ref omissing, ref omissing,
Ref omissing, ref omissing, ref omissing );

Import TemplateCopy codeThe Code is as follows: Object omissing = system. reflection. Missing. value;
Word. _ application oword;
Word. _ document odoc;
Oword = new word. Application ();
Oword. Visible = true;
Object filename = @ "E: xxxccxtest.doc ";
Odoc = oword. Documents. Add (ref filename, ref omissing,
Ref omissing, ref omissing );

. add a new table
copy Code the code is as follows: Object omissing = system. reflection. missing. value;
word. _ application oword;
word. _ document odoc;
oword = new word. application ();
oword. visible = true;
odoc = oword. documents. add (ref omissing, ref omissing,
ref omissing, ref omissing);
Object start = 0;
Object end = 0;
word. range tablelocation = odoc. range (ref start, ref end);
odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing);

. copy Code : object omissing = system. reflection. missing. value;
word. _ application oword;
word. _ document odoc;
oword = new word. application ();
oword. visible = true;
odoc = oword. documents. add (ref omissing, ref omissing,
ref omissing, ref omissing);
Object start = 0;
Object end = 0;
word. range tablelocation = odoc. range (ref start, ref end);
odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing);
word. table newtable = odoc. tables [1];
Object beforerow = newtable. rows [1];
newtable. rows. add (ref beforerow);

. copy Code the code is as follows: object omissing = system. reflection. missing. value;
word. _ application oword;
word. _ document odoc;
oword = new word. application ();
oword. visible = true;
odoc = oword. documents. add (ref omissing, ref omissing,
ref omissing, ref omissing);
Object start = 0;
Object end = 0;
word. range tablelocation = odoc. range (ref start, ref end);
odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing);
word. table newtable = odoc. tables [1];
Object beforerow = newtable. rows [1];
newtable. rows. add (ref beforerow);
word. cell cell = newtable. cell (1, 1);
cell. merge (newtable. cell (1, 2);

. Cell SeparationCopy codeThe Code is as follows: Object omissing = system. reflection. Missing. value;
Word. _ application oword;
Word. _ document odoc;
Oword = new word. Application ();
Oword. Visible = true;
Odoc = oword. Documents. Add (omissing,
Ref omissing, ref omissing );
Object start = 0;
Object end = 0;
Word. Range tablelocation = odoc. Range (ref start, ref end );
Odoc. Tables. Add (tablelocation, 3, 4, ref omissing, ref omissing );
Word. Table newtable = odoc. Tables [1];
Object beforerow = newtable. Rows [1];
Newtable. Rows. Add (ref beforerow );
Word. Cell cell = newtable. Cell (1, 1 );
Cell. Merge (newtable. Cell (1, 2 ));
Object rownum = 2;
Object columnnum = 2;
Cell. Split (ref rownum, ref columnnum );

Insert with paragraph ControlCopy codeThe Code is as follows:

Object omissing = system. reflection. missing. value;
Object oendofdoc = "\ endofdoc";/** // * endofdoc is a predefined bookmark */
// start WORD and create a new document.
word. _ application oword;
word. _ document odoc;
oword = new word. application ();
oword. visible = true;
odoc = oword. documents. add (ref omissing, ref omissing,
ref omissing, ref omissing);
// insert a paragraph at the beginning of the document.
word. paragraph opara1;
opara1 = odoc. content. paragraphs. add (ref omissing);
opara1.range. TEXT = "Heading 1";
opara1.range. font. bold = 1;
opara1.format. spaceafter = 24; // 24 PT spacing after paragraph.
opara1.range. insertparagraphafter ();

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.