In the current project development process, the customer needs to generate Word documents based on the database data, and found two solutions during the communication with colleagues.
1. use the Program to generate an HTML page of the report style, and then modify the HTML page suffix to Doc.
2. Customize the template file of the Word document, operate on 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. Now I will be in the development process of some understanding and experience to sum up:
In vs2008 platform, reference. net-Microsoft.Office.Interop.Word.12, so that you can operate the word object in the program.
after simple execution, the error 80070005 is reported. This error is caused by insufficient permissions and needs to be changed in DCOM configuration.. NET and IIS user permissions. 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 this code] Code:
// Generate WORD program objects and Word document objects
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 this code] Code:
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 this code] Code:
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 word
[Copy this code] Code:
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 this code] Code:
Object omissing = system. reflection. missing. value;
word. _ application oword;
word. _ document odoc;
oword = new word. application ();
oword. visible = true;
Object filename = @ "E: cccxxtestdoc.doc";
odoc = oword. documents. open (ref filename,
ref omissing, ref omissing,
ref omissing, ref omissing, ref omissing,
ref omissing, ref omissing);
Import template
[copy this code] Code:
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 this code] 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);
. Insert table rows
[copy this code] 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);
. cell merging
[copy this code] 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);
word. cell cell = newtable. cell (1, 1);
cell. merge (newtable. cell (1, 2);
. Cell Separation
[copy this code] Code:
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 Control
[Copy this code] Code:
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 ();