C # WORD operation implementation code

Source: Internet
Author: User

1. Generate the HTML page of the report style through the program, and then 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 solution 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 Document Object → get all the bookmarks of the document → assign the database data to the corresponding bookmarks → Save the document as a specified folder.
The following describes the specific code implementation of the agricultural plant test report: Copy codeThe 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 codeThe 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 codeThe 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 );

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 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 );
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 );

Insert rows into tableCopy 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 );
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 );

. Cell mergeCopy 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 );
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 ENTs. 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.