C # operations on Word documents

Source: Internet
Author: User

Today, I am developing a word report in the C # language. I saw some useful articles on the Internet, and posted them first.
Below from http://hi.baidu.com/showlong/blog/item/2198fdfab75a35d4b48f31c0.html

Reference: http://xb.hzu.edu.cn/qikan/manage/wenzhang/200906014.pdf

Http://kb.cnblogs.com/a/1698486/
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. 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. Solution 2 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. Despite the trouble, it is flexible customization, but it is only a word object operation.
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:


// Generate the word program object and Word Document Object <br/> Microsoft. office. interOP. word. application appword = new application (); <br/> Microsoft. office. interOP. word. document Doc = new document (); <br/> Object omissing = system. reflection. missing. value; // What is this? I have never understood it-_-<br/> // open the template document, and specify the doc document type <br/> Object objtemplate = server. mappath (p_templatepath); <br/> Object objdoctype = wddocumenttype. wdtypedocument; <br/> Doc = (document) Appword. documents. add (ref objtemplate, ref objfalse, ref objdoctype, ref objtrue); <br/> // obtain all bookmarks in the template <br/> bookmarks ODF = Doc. bookmarks; <br/> string [] testtableremarks = {"applyno", "auditingdate", "auditor", "checkdate", "checker "}; <br/> string [] testtablevalues = {"applyno", "auditingdate", "auditor", "checkdate", "checker ",}; <br/> // loop all bookmarks and assign a value to the bookmarks <br/> for (INT oindex = 0; oindex <testtabler Emarks. length; oindex ++) <br/>{< br/> obdd_name = WD + testtableremarks [oindex]; <br/> 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 <br/>}< br/> // Step 4 generates word, save the current document object as the specified path, and then close the doc object. Close the application <br/> Object filename = server. mappath (p_savepath) + "// testing _" + datetime. now. toshortdatestring () + ". doc "; <br/> Object Miss = system. reflection. missing. value; <br/> Doc. saveas (ref filename, ref miss, ref miss, ref miss, ref Miss); <br/> Object missingvalue = type. missing; <br/> objec T donotsavechanges = wdsaveoptions. wddonotsavechanges; <br/> Doc. close (ref donotsavechanges, ref missingvalue, ref missingvalue); <br/> appword. application. quit (ref miss, ref miss, ref Miss); <br/> Doc = NULL; <br/> appword = NULL; <br/> This. hid_showmessage.value = "generated successfully! "; </P> <p> 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. <Br/> some data is dynamically added during development. If I want to dynamically add several rows of data to a table, you cannot perform the operation by replacing the bookmarks. You need to add rows to the table on the document page by using a program. <Br/> Add rows to a table in two ways: one is that a table already exists in the Word template. One is to add a table object directly in the program. <Br/> In the first case, note that the tables to be operated in the Word template cannot contain vertically merged cells, otherwise, the program reports an error because the program cannot obtain the object to be operated. cell merging can be controlled in the program. <Br/> In the second case, we need to directly add tables through programs. <Br/> the code for generating a table is as follows: <br/> 1. obtain an existing table in the document: <br/> 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. <Br/> 2. to directly generate a table in the document, first obtain the location of the inserted table, and then add the table object: <br/> Object oendofdoc = "// endofdoc "; // There are many pre-defined bookmarks in word, which are not listed here. <Br/> Object omissing = system. reflection. missing. value; <br/> range wrdrng = Doc. bookmarks. get_item (ref oendofdoc ). range; // obtain the end position of the current document. <Br/> wrdrng. insertafter (""); // insert a row. wrdrng cannot be used here. insertafter (""). If this is used, the line feed is not allowed, and I don't know why. </P> <p> Object ocollapseend = Microsoft. office. interOP. word. wdcollapsedirection. wdcollapseend; <br/> Object opagebreak = Microsoft. office. interOP. word. wdbreaktype. wdpagebreak; // Page Break <br/> wrdrng. collapse (ref ocollapseend); <br/> wrdrng. insertbreak (ref opagebreak); // insert a page <br/> wrdrng. collapse (ref ocollapseend); <br/> wrdrng. insertafter ("image information"); <br/> wrdrng. font. size = 20; // specify the text size of the operation object <br/> wrdrng. font. bo LD = 1; // bold of the specified operation object: 1 is bold, 0 is normal <br/> wrdrng. paragraphformat. alignment = wdparagraphalignment. wdalignparagraphcenter; // specify the text layout of the operation area: center alignment <br/> // The preceding code indicates finding the current end position and inserting a paging character, it is equivalent to jumping to a new page, writing the text "Image Information" at the top of the new page, specifying the text size as 20, and centered in bold. <Br/> wrdrng = Doc. bookmarks. get_item (ref oendofdoc ). range; <br/> wrdrng. insertafter (""); <br/> wrdrng = Doc. bookmarks. get_item (ref oendofdoc ). range; <br/> wrdrng. insertparagraphafter (); // insert a paragraph into which a table with two rows and one column is inserted. <Br/> Microsoft. office. interOP. word. table newtable = Doc. tables. add (wrdrng, 2, 1, ref omissing, ref omissing); </P> <p> You can also set the format of the table, which is not listed here. <Br/> 3. Next we will analyze the operations on the cells in the Table: Merge and split. This requires us to perform operations based on the actual table: <br/> // obtain a specific cell ), obtain the cell in the first column of the First row <br/> cell = Doc. tables [1]. cell (1, 1); <br/> cell. range. TEXT = "text"; // specify the content of the current cell as text <br/> In the table operation, add a new row: <br/> Object beforerow = Doc. tables [1]. rows [2]; // This line first gets the second line <br/> 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. <Br/> // merge cells: it seems silly to merge cells here. You only need to specify the start and end cells to be merged, then you can perform the merge operation. <br/> cell = Doc. tables [1]. cell (irow, 2); // merge columns <br/> cell. merge (Doc. tables [1]. cell (irow, 6); <br/> cell cell1 = Doc. tables [1]. cell (irow-1, 1); // merge rows <br/> cell1.merge (Doc. tables [1]. cell (irow + 1, 1); <br/> the above operations are some of the knowledge points used in this program, and there are many things to be familiar with and understand. <Br/> additionally, the winword.exe process cannot be killed in the resource manager after the program is created. The solution is to directly kill the process, as shown in the following code: </P> <p> protected void killprocess () // kill all winword.exe processes <br/>{< br/> system. diagnostics. process [] myps; <br/> myps = system. diagnostics. process. getprocesses (); <br/> foreach (system. diagnostics. process P in myps) <br/>{< br/> If (P. ID! = 0) <br/>{< br/> string mys = "winword. EXE "+ P. processname + "ID:" + P. id. tostring (); <br/> try <br/>{< br/> If (P. modules! = NULL) <br/> If (P. modules. count> 0) <br/>{< br/> system. diagnostics. processmodule PM = P. modules [0]; <br/> mys + = "/n modules [0]. filename: "+ PM. filename; <br/> mys + = "/n modules [0]. modulename: "+ PM. modulename; <br/> mys + = "/n modules [0]. fileversioninfo:/N "+ PM. fileversioninfo. tostring (); <br/> If (PM. modulename. tolower () = "winword.exe") <br/> P. kill (); <br/>}< br/> catch <br/>{}< br/> Fina Lly <br/>{< br/>}</P> <p> 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! <Br/> The following is a good excerpt on the Internet: <br/> Create a new word </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (ref omissing, ref omissing, <br/> ref omissing, ref omissing); </P> <p> open the document: </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> Object filename = @ "E: cccxxtestdoc.doc"; <br/> odoc = oword. documents. open (ref filename, <br/> ref omissing, <br/> ref omissing, ref omissing, ref omissing, <br/> ref omissing, ref omissing ); </P> <p> Import template </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> Object filename = @ "E: xxxccxtest.doc"; <br/> odoc = oword. documents. add (ref filename, ref omissing, <br/> ref omissing, ref omissing); </P> <p>. add a new table </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (ref omissing, ref omissing, <br/> ref omissing, ref omissing); <br/> Object start = 0; <br/> Object end = 0; <br/> word. range tablelocation = odoc. range (ref start, ref end); <br/> odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing); </P> <p>. insert row into Table </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (ref omissing, ref omissing, <br/> ref omissing, ref omissing); <br/> Object start = 0; <br/> Object end = 0; <br/> word. range tablelocation = odoc. range (ref start, ref end); <br/> odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing); <br/> word. table newtable = odoc. tables [1]; <br/> Object beforerow = newtable. rows [1]; <br/> newtable. rows. add (ref beforerow); </P> <p>. merge cells </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (ref omissing, ref omissing, <br/> ref omissing, ref omissing); <br/> Object start = 0; <br/> Object end = 0; <br/> word. range tablelocation = odoc. range (ref start, ref end); <br/> odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing); <br/> word. table newtable = odoc. tables [1]; <br/> Object beforerow = newtable. rows [1]; <br/> newtable. rows. add (ref beforerow); <br/> word. cell cell = newtable. cell (1, 1); <br/> cell. merge (newtable. cell (1, 2); </P> <p>. cell Separation </P> <p> Object omissing = system. reflection. missing. value; <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (omissing, <br/> ref omissing, ref omissing); <br/> Object start = 0; <br/> Object end = 0; <br/> word. range tablelocation = odoc. range (ref start, ref end); <br/> odoc. tables. add (tablelocation, 3, 4, ref omissing, ref omissing); <br/> word. table newtable = odoc. tables [1]; <br/> Object beforerow = newtable. rows [1]; <br/> newtable. rows. add (ref beforerow); <br/> word. cell cell = newtable. cell (1, 1); <br/> cell. merge (newtable. cell (1, 2); <br/> Object rownum = 2; <br/> Object columnnum = 2; <br/> cell. split (ref rownum, ref columnnum); </P> <p> insert using paragraph Control </P> <p> Object omissing = system. reflection. missing. value; <br/> Object oendofdoc = "/endofdoc "; /** // * endofdoc is a predefined bookmark */<br/> // start WORD and create a new document. <br/> word. _ application oword; <br/> word. _ document odoc; <br/> oword = new word. application (); <br/> oword. visible = true; <br/> odoc = oword. documents. add (ref omissing, ref omissing, <br/> ref omissing, ref omissing); <br/> // insert a paragraph at the beginning of the document. <br/> word. paragraph opara1; <br/> opara1 = odoc. content. paragraphs. add (ref omissing); <br/> opara1.range. TEXT = "Heading 1"; <br/> opara1.range. font. bold = 1; <br/> opara1.format. spaceafter = 24; // 24 PT spacing after paragraph. <br/> opara1.range. insertparagraphafter (); <br/>

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.