C # export pages to Word (with pictures and controls)

Source: Internet
Author: User

/// <summary>        ///Create Word/// <param name= "FilePath" >file path</param>        /// </summary>        protected voidCreatewordfile (stringFilePath) {            if(File.exists (FilePath)) {file.delete (FilePath); }            using(FileStream fs =file.create (FilePath)) {fs.            Close (); }        }
    /// <summary>        ///output page content to Word/// <param name= "FilePath" >file path</param>        /// </summary>        protected voidWritepagecontenttoword (stringFilePath) {            stringpagehtml =string.            Empty; StringWriter SW=NewStringWriter (); HtmlTextWriter HTW=NewHtmlTextWriter (SW);  This. Divall.rendercontrol (HTW); Pagehtml=SW.            ToString (); Pagehtml.replace (".. /app_themes/blue/image/fivestar.png", Server.MapPath ("./app_themes/blue/image/fivestar.png")); Pagehtml.replace (".. /app_themes/blue/image/fourstar.png", Server.MapPath ("./app_themes/blue/image/fourstar.png")); Pagehtml.replace (".. /app_themes/blue/image/threestar.png", Server.MapPath ("./app_themes/blue/image/threestar.png") ;//Change the image relative path to an absolute path hereif(File.exists (FilePath)) {StreamWriter STREAMW=File.createtext (FilePath);                Streamw.write (pagehtml);            Streamw.close (); } SW.            Close (); Htw.        Close (); }
protected voidInsertphoto (stringFilePath) {            //Create a picture            stringImagePath = MapPath ("/file2/"+ request.querystring["ID"]. ToString () +". PNG"); session["ImagePath"] =ImagePath; //Insert Picture;StringBuilder reportcontent =NewStringBuilder (); Objectnothing =System.Reflection.Missing.Value; Objectfilename =FilePath; Microsoft.Office.Interop.Word.Application WordApp2=NewMicrosoft.Office.Interop.Word.Application ();//. ApplicationClass ();Microsoft.Office.Interop.Word.Document WordDoc2 = WordApp2.Documents.Open (refFileNamerefNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing,refNothing ); //The word that opens here is actually the text format of the Web page (you can open it with Notepad) and save it as a doc format .//in order to embed a picture in a Word document, otherwise the saved is always a linkWorddoc2.saveas (FilePath, wdsaveformat.wdformatdocument); //loops all inserted entities in a Word document, finds entities that appear empty, and replaces them//because the Word document is generated by HTML, the picture being stored is actually empty, the type is wdinlineshapelinkedpicture, and it needs to be replaced with the actual type//ienumerable<inlineshape> shape2 =new IEnumerable worddoc2.inlineshapes;            foreach(InlineShape shapeinchworddoc2.inlineshapes)
{ //find where to insert a graphic ObjectORange = worddoc2.paragraphs[ -]. Range;//get the position where the picture is inserted ObjectLinkToFile =false; ObjectSaveWithDocument =true; //inserting graphicsWordDoc2.InlineShapes.AddPicture (ImagePath,refLinkToFile,refSaveWithDocument,refORange); //Delete an entity that is displayed as emptyshape. Select (); WordApp2.Selection.Delete (); Break; } //The default view is Page view when you open the documentWordDoc2.ActiveWindow.View.Type =Wdviewtype.wdprintview; //Save the word that you inserted the picture inWorddoc2.saveas (FilePath, wdsaveformat.wdformatdocument); //Close all Word documentsWordApp2.NormalTemplate.Saved =true; Object SaveChanges2=Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges; WordApp2.Documents.Close (SaveChanges2, Type.Missing, Type.Missing); //quit the Word application try
      {WordApp2.Application.Quit (Type.Missing, Type.Missing, Type.Missing); if(WordApp2! =NULL)
{WORDAPP2=NULL; } } Catch { } finally
{GC. Collect (); Gc. WaitForPendingFinalizers (); Gc. Collect (); Gc. WaitForPendingFinalizers (); } }
protected voidLnktoword_click (Objectsender, EventArgs e) {Chart2.saveimage (Server.MapPath ("~/file2/"+ request.querystring["ID"]. ToString () +". PNG"), chartimageformat.png); Label Lbname= FV. FindControl ("Lbname") asLabel; stringWordname = lbName.Text.ToString () + request.querystring["ID"]; stringFilePath = MapPath ("~/file2/") + Wordname +". doc";//file pathCreatewordfile (FilePath);            Writepagecontenttoword (FilePath);            Insertphoto (FilePath); stringFileName = Wordname +". doc"; Response.Redirect (string. Format ("~/file2/{0}", FileName)); stringImagePath = session["ImagePath"]. ToString ();        }

In particular, the page is written in HTML, when written in HTML, the relative path of the picture is changed to absolute path, saved as a copy of Word to the server. This page contains the. NET inside the chart control, so first the chart control into a picture to the server, and finally insert the picture into Word

C # export pages to Word (with pictures and controls)

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.