Export word/Excel according to the word/excel template

Source: Internet
Author: User

 

Recently, the project needs to implement the download and print function. I thought it would be a little practical to use Crystal Reports. This function can be directly implemented using office components.

Reference class using Microsoft. Office. Interop. Word;

Create two entity classes. One is the configuration for exporting the content to be replaced by word, and the other is the object for replacing the content.

Public class AgentInfoEntity
{

Private string comname;

Public string ComName
{
Get {return comname ;}
Set {comname = value ;}
}

Private string linkname;

Public string LinkName
{
Get {return linkname ;}
Set {linkname = value ;}
}

Private string comemail;

Public string ComEmail
{
Get {return comemail ;}
Set {comemail = value ;}
}

Private string Sn;

Public String Sn
{
Get {return Sn ;}
Set {sn = value ;}
}


Private string Comtel;

Public String Comtel
{
Get {return Comtel ;}
Set {Comtel = value ;}
}

Private string comcontact;

Public String comcontact
{
Get {return comcontact ;}
Set {comcontact = value ;}
}
Private string registercomname;

Public String registercomname
{
Get {return registercomname ;}
Set {registercomname = value ;}
}

Private string regaddresstel;

Public string RegAddressTel
{
Get {return regaddresstel ;}
Set {regaddresstel = value ;}
}

Private string bank;

Public string Bank
{
Get {return bank ;}
Set {bank = value ;}
}
Private string tax;

Public string Tax
{
Get {return tax ;}
Set {tax = value ;}
}

Private string regtel;

Public String regtel
{
Get {return regtel ;}
Set {regtel = value ;}
}

Private string sendaddress;
Public String sendaddress
{
Get {return sendaddress ;}
Set {sendaddress = value ;}
}

Private string postaddress;

Public string PostAddress
{
Get {return postaddress ;}
Set {postaddress = value ;}
}

Private string agentaccount;

Public String agentaccount
{
Get {return agentaccount ;}
Set {agentaccount = value ;}
}


Private string postcontact;

Public String postcontact
{
Get {return postcontact ;}
Set {postcontact = value ;}
}


Private string invoicetel;

Public string InvoiceTel
{
Get {return invoicetel ;}
Set {invoicetel = value ;}
}

Private string financecontact;

Public string FinanceContact
{
Get {return financecontact ;}
Set {financecontact = value ;}
}
Private string financetel;

Public String financetel
{
Get {return financetel ;}
Set {financetel = value ;}
}

Private string financefax;

Public String financefax
{
Get {return financefax ;}
Set {financefax = value ;}
}

Private string financepost;

Public String financepost
{
Get {return financepost ;}
Set {financepost = value ;}
}

Private string deliveryarea;

Public string DeliveryArea
{
Get {return deliveryarea ;}
Set {deliveryarea = value ;}
}

Private string deliverypost;

Public string DeliveryPost
{
Get {return deliverypost ;}
Set {deliverypost = value ;}
}
}

Public class agentinfoentity
{
Private string comname;

Public String comname
{
Get {return comname ;}
Set {comname = value ;}
}
Private string linkname;

Public string LinkName
{
Get {return linkname ;}
Set {linkname = value ;}
}

Private string comemail;

Public string ComEmail
{
Get {return comemail ;}
Set {comemail = value ;}
}
Private string sn;

Public string SN
{
Get {return sn ;}
Set {sn = value ;}
}

Private string comtel;

Public string ComTel
{
Get {return comtel ;}
Set {comtel = value ;}
}
Private string comcontact;

Public string ComContact
{
Get {return comcontact ;}
Set {comcontact = value ;}
}

Private string registercomname;

Public string RegisterComName
{
Get {return registercomname ;}
Set {registercomname = value ;}
}

Private string regaddresstel;

Public string RegAddressTel
{
Get {return regaddresstel ;}
Set {regaddresstel = value ;}
}
Private string bank;

Public string Bank
{
Get {return bank ;}
Set {bank = value ;}
}
Private string tax;

Public string Tax
{
Get {return tax ;}
Set {tax = value ;}
}
Private string regtel;

Public string Regtel
{
Get {return regtel ;}
Set {regtel = value ;}
}
Private string sendaddress;
Public string SendAddress
{
Get {return sendaddress ;}
Set {sendaddress = value ;}
}

Private string postaddress;

Public string PostAddress
{
Get {return postaddress ;}
Set {postaddress = value ;}
}

Private string agentaccount;

Public string AgentAccount
{
Get {return agentaccount ;}
Set {agentaccount = value ;}
}

Private string postcontact;

Public string PostContact
{
Get {return postcontact ;}
Set {postcontact = value ;}
}

Private string invoicetel;

Public string InvoiceTel
{
Get {return invoicetel ;}
Set {invoicetel = value ;}
}
Private string financecontact;

Public string FinanceContact
{
Get {return financecontact ;}
Set {financecontact = value ;}
}
Private string financetel;

Public string FinanceTel
{
Get {return financetel ;}
Set {financetel = value ;}
}
Private string financefax;

Public string FinanceFax
{
Get {return financefax ;}
Set {financefax = value ;}
}
Private string financepost;

Public String financepost
{
Get {return financepost ;}
Set {financepost = value ;}
}
Private string deliveryarea;

Public String deliveryarea
{
Get {return deliveryarea ;}
Set {deliveryarea = value ;}
}
Private string deliverypost;

Public String deliverypost
{
Get {return deliverypost ;}
Set {deliverypost = value ;}
}
}

/// <Summary>
/// L obtain the attribute value based on the object.
/// </Summary>
/// <Param name = "ainfo"> </param>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public string getProperties (AgentInfoEntity ainfo, string key)
{
String tStr = string. Empty;
If (ainfo = null)
{
Return tStr;
}
System. Reflection. PropertyInfo [] properties = ainfo. GetType (). GetProperties (System. Reflection. BindingFlags. Instance | System. Reflection. BindingFlags. Public );

If (properties. Length <= 0)
{
Return tStr;
}
Foreach (System. Reflection. PropertyInfo item in properties)
{
String name = item. Name;
Object value = item. getvalue (ainfo, null );
If (item. propertytype. isvaluetype | item. propertytype. Name. startswith ("string "))
{
// Tstr + = string. Format ("{0 }:{ 1},", name, value );
If (name. tolower () = key)
{
TStr = (string) value;
Break;
}
}
}
Return tStr;
}

/// <Summary>
/// Replace and export the content
/// </Summary>
/// <Param name = "templetePathandName"> </param>
/// <Param name = "saasPathandFile"> </param>

/// <Param name = "eword"> </param>

/// <Param name = "agentinfo"> </param>
/// <Returns> </returns>

Public void ExportWordForTemplete (string templetePathandName, string saasPathandFile, ExWordValue eword, AgentInfoEntity agentinfo)
{
// Generate WORD program objects and WORD document objects
String p_TemplatePath = templetePathandName; // For example, "/templete.doc ";
String p_SavePath = saasPathandFile;
Application appWord = new Application ();
Document doc = new Document ();

Object oMissing = System. Reflection. Missing. Value; // This is a question

// Open the template document and specify the doc document type
Object filename = "";
Try
{
Object objtemplate = server. mappath (p_templatepath );
Object objdoctype = wddocumenttype. wdtypedocument;
Object objfalse = false, objtrue = true;
Doc = (document) appword. Documents. Add (ref objtemplate, ref objfalse, ref objdoctype, ref objtrue );
// Obtain all bookmarks in the template
Bookmarks ODF = Doc. bookmarks;
// Loop all bookmarks and assign values to the bookmarks
For (int oIndex = 0; oIndex <eword. ItemValue. Count; oIndex ++)
{
Object obDD_Name = eword. ItemValue [oIndex];
Doc. Bookmarks. get_Item (ref obDD_Name). Range. Text = getProperties (agentinfo, (string) obDD_Name );
// P_TestReportTable.Rows [0] [testTablevalues [oIndex]. ToString (); // Range is an important object in WORD, that is, the region of the current operation parameter.
}
// Generate the word in Step 4, save the current document object as the specified path, and then close the doc object. Close the application
Filename = Server. MapPath (saasPathandFile );
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;

}
Catch (System. Threading. ThreadAbortException ex)
{
Object miss = System. Reflection. Missing. Value;
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 );
}

// Export
String file = filename. ToString ();
FileInfo fi = new FileInfo (file );
Response. Clear ();
Response. clearheaders ();
Response. Buffer = false;
// Response. appendheader ("content-disposition", "attachment; filename =" + httputility. urlencode (path. getfilename (destfilename), system. Text. encoding. Default ));
Response. appendheader ("content-disposition", "attachment; filename =" + httputility. urlencode (path. getfilename (file), system. Text. encoding. utf8 ));
Response. appendheader ("Content-Length", Fi. length. tostring ());
Response. ContentType = "application/octet-stream ";
Response. WriteFile (file );
Response. Flush ();
Response. End ();
}

 

The above is the code, but for the referenced dll, It is a com component, if you do not set its permissions, an error will be reported.

Call the COM component to publish IIS. common error 80070005 Solution

Symptoms:

OWordApplic = New Word. Application

When the program runs this sentence, the following error occurs:

Failed to retrieve components whose CLSID is {000209FF-0000-0000-C000-000000000046} in the COM class factory because of the following error: 80070005.

OWordApplic = New Word. Application

When the program runs this sentence, the following error occurs:

Failed to retrieve components whose CLSID is {000209ff-0000-0000-c000-000000000046} in the com class factory because of the following error: 80070005.

Solution 1:

Control Panel-> Administrative Tools-> component services-> Computer-> my computer-> DCOM configuration-> Microsoft Word documents

After

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

Custom-> edit-> Add ASP. NET account and iuser _ computer name

* These accounts only exist when IIS is installed on the computer.

13. Make sure that each user is allowed to access the service and click OK.

14. Click OK to disable dcomcnfg.

Solution 2:

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>

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.