Example and summary of automatic calling of word in C # Under Asp.net

Source: Internet
Author: User

Abstract: This article uses a practical example to demonstrate how to use C # In ASP. net, and summarizes the problems found in practical applications. Finally, an effective solution is proposed.
Keywords: ASP. NET; C #; word; automation; VBA; com; dead process;

1. Create a project
The first step to operate word in ASP. NET is to add com reference to your project, right-click "Reference" in "solution Resource Manager", and add reference. Select the com tab and add the Microsoft Word 12.0 Object Library (where 12.0 is the word version number, which is determined based on the Word version installed on the current computer ). ASP. NET will automatically generate the word com package classProgramAdd the set to the application directory.

2.CodeLogic
Access a local Word file on the server, create a file based on the file, and use the word tag to locate the assignment. The client browser accesses the New Word file through the file link.
The Code is as follows:
Private void page_load (Object sender, system. eventargs E)
{
// Place user code here to initialize the page
Object missing = type. missing;
// Obtain the Word file path
String strtemp = "DOC/test.doc ";
// Path for saving the New Word file
String newfilename = "DOC/test2.doc ";
// Create a component object named wordapp
Application wordapp = new applicationclass ();
// Must be set to invisible
Wordapp. Visible = false;

Try
{
// Create a document with strtemp as the template
Object otemplate = server. mappath (strtemp );
Document worddoc = wordapp. Documents. Add (ref otemplate, ref missing );
Worddoc. Activate ();

// Fill in the label "title"
String strbm = "title ";
Object objbm = strbm;
If (wordapp. activedocument. bookmarks. exists (strbm) = true)
{
Wordapp. activedocument. bookmarks. get_item (ref objbm). Select ();
Wordapp. selection. typetext ("document title ");
}

// Save as a new file
Object onewfilename = server. mappath (newfilename );
Worddoc. saveas (ref onewfilename, ref missing,
Ref missing, ref missing, ref missing );
Worddoc. Close (ref missing, ref missing, ref missing );

Wordapp. Quit (ref missing, ref missing, ref missing );
}
Catch (exception ex)
{
Throw new exception (ex. Message );
}

// The download box is displayed in the browser.
Page. registerstartupscript ("", "<SCRIPT> window. Open ('" + newfilename + "') </SCRIPT> ");
}
Before running, create a folder Doc under the project directory, and create a new test.doc in doc2. set the content and manually insert a tag named "title.
This code runs in vs. net2003 + WINXP + office2007.

If the following debugging error occurs during running:

Access denied.
Note: An unhandled exception occurs during the execution of the current Web request. Check the stack trace information for details about the error and the source of the error in the code.
Exception details: system. unauthorizedaccessexception: Access denied.
ASP. NET is not authorized to access the requested resources. Consider granting the ASP. NET Request identity the permission to access this resource. ASP. NET has a base process ID used when the application is not simulated (typically, {MACHINE} \ ASPnet on IIS 5 and Network Service on IIS 6 ). If the application is simulating through <identity impersonate = "true"/>, the identity will be an anonymous user (usually IUSR_machinename) or an authenticated user.
To grant ASP. NET write access to a file, right-click the file in resource manager, select "properties", and select the "Security" tab. Click Add to add an appropriate user or group. Highlight the ASP. NET account and select the corresponding access permission box.

When the preceding error occurs, it indicates that the ASP. NET process cannot automatically call a word with a user interface. Therefore, an ASP. Net Process must be started by a desktop user role. Solution: in the web. the system. in the web section, add <identity impersonate = "true" username = "*" Password = "*"/>. username and password are the Windows logon accounts on your computer.

3. Summary
Problems found in the actual application of word automatically called by the Web server:
I. Difficulty in development: the calls in Word automation are based on VBA syntax and developers need to be familiar with VBA. In VBA, there are many word objects and the logic is complex. It is difficult to understand the com call method. Generally, developers seldom access VBA and COM, so it is troublesome to develop.
Ii. Code security: the best solution to the above running error "Access Denied" is to add <identity impersonate = "true" username = "*" Password = "*"/>, however, the disadvantage is that. in config, you can see your account password, even though the web. config is not easily downloaded, but it is still dangerous. In addition, you can run the dcomcnfg.exe tool to upgrade the ASPNET account permission to an interactive user, which also increases the server risk. Some netizens found the solution on the Internet: Find the machine. config file in the config folder under the. net installation root directory and change the username attribute in processmodel to system. Another solution is to change the default IIS account to the administrator account. These two methods are even more dangerous. Once a hacker gains the permissions of the ASP. NET process, he can fully control your server.
Iii. operational stability: Microsoft Office is a desktop office application software developed for common users. It has rich UI (User Interface) elements, is a set of pure local running software or client software. The word automation interface is designed to facilitate the calling of window applications. For example, local applications developed by Delphi, VB, and C # winform. Although it can be forced to set visible to false, word can run in server-side code, but after all, it still brings a lot of tricky problems. 1. ASP. NET is based on the B/S architecture. In B/S architecture, user access is concurrent. That is to say, N users send requests to one server page at the same time. In this case, word automatic calls often lead to dead processes. 2. because the interface is hidden, some interfaces that can be successfully called in the window program involving the interface will fail or even crash on the server side, which will often lead to dead processes. 3. because word is a complex desktop program and does not meet the simple and efficient standards of general web service programs, it is slow to run on the server and consumes a lot of resources (CPU and memory ), in particular, it cannot support simultaneous access by a large number of users, and the resources will soon be exhausted. 4. The vast majority of developers are unfamiliar with the COM technology. when calling the word interface programmatically, some code Errors often exist, and it is difficult to check the problem, which is a frequent cause of dead processes. The word dead process not only consumes server resources, but also often causes the server page to fail to create new word automation objects and to continue working. Some netizens proposed a solution to the dead process: programming kill the dead process of word. This is a temporary solution, and the dead process of word is gone, however, if the word is not properly closed, many resources cannot be released in time. It is hard to say how long the Web server can continue to work.
Since there are so many problems with the automatic call of Word on the Web server, can we call word in the client browser? Javascript can be used, but to run it, you have to minimize the security of your browser. I'm afraid few users are willing to do this. Even if there is no security problem, the logic of the Code originally written on the server must be written in Javascript, which makes it difficult to open, pass the value, set the value, and save it to the server.

4. Solution
In order to solve these problems, after comprehensive research and comparison, I found that there is a software soaoffice (Web middleware dedicated to Microsoft Office) on the Internet, which completely eliminates the above problems. I suggest you share it with us.
Soaoffice is a middleware system composed of server components and client controls. The server component is a standard. NET component that provides simple and efficient Word and Excel simplified interfaces. Client controls run on browser web pages. After the server calls soaword. webopen to open the document, the client control on the browser page starts the word on the client and runs on the webpage instead of opening it locally. No installation required on the serverOfficeSoftware.
The soaoffice architecture is clever. Developers only need to focus on the programming logic on the server side, and the work on the client side is automatically completed by the control. Soaoffice makes full use of the concept of distributed computing and handed over the word computing workload originally intended to run on the server to the client. That is to say, web pages using server-side automation technology have to process N word tasks at the same time, and now they are handed over to N clients. Each client runs a word. The server only needs to process the business logic that needs to be processed by the server. all work related to the interface and the word program itself is run by the client. Of course, this is also the strength of the client.
Soaoffice architecture eliminates the risks of running Word and Excel on the server, and makes full use of idle computing resources on the client. This architecture not only solves ASP and ASP. net and other Windows Web services call Word and Excel, and also provide a solution for Java-written web services to call Word and Excel (such as UNIX and Linux cannot automate Word and Excel ).
Soaoffice allows users to directly view the Word file content on the webpage, and can directly edit and save it back to the Web server, saving users the trouble of downloading it first and uploading it after modification.
Soaoffice also has more powerful functions that cannot be achieved by automatically calling word, such as read-only, anti-download, anti-copy, etc. You just need to download it.

Attached ExploitationSoaofficeComplete the same functions of this instance+Code for the read-only anti-download function:
Private void page_load (Object sender, system. eventargs E)
{
// Place user code here to initialize the page
Soaofficex. wordresponse soaword = new soaofficex. wordresponse ();
// Fill in the data area "title"
Soaword. opendataregion ("title"). value = "document title ";

Soaofficex. soaofficectrl soactrl = new soaofficex. soaofficectrl ();
// Set the interface style
Soactrl. mainstyle = soaofficex. soamainstyle. vistablue;
Soactrl. Caption = "dynamic document generation ";
Soactrl. menubar = false;
Soactrl. toolbars = false;
Soactrl. cancopy = false; // download prohibited, copy and paste prohibited
Soactrl. Assign (soaword); // bind data
// Read-only open the generated document
Soactrl. webopen ("DOC/test.doc", soaofficex.soaworkmode.doc readonly, "somebody", "word. Document ");
}

 

 

 

Http://hi.baidu.com/officeworkspace

 

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.