c# 将页面导出到word(含图片及控件)

/// <summary>
        /// 创建word
        /// <param name="filePath">文件路径 </param>
        /// </summary>
        protected void CreateWordFile(string filePath)
                {
            if (File.Exists(filePath)) 
                        {
                File.Delete(filePath);
            }
            using (FileStream fs = File.Create(filePath))
                        {
                fs.Close();
            }
        }
    /// <summary>
        /// 将页面内容输出到Word
        /// <param name="filePath">文件路径 </param>
        /// </summary>
        protected void WritePageContentToWord(string filePath)
        {
            string pageHtml = string.Empty;
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(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"));//这里将图片相对路径换成绝对路径

            if (File.Exists(filePath))
            {

                StreamWriter streamW = File.CreateText(filePath);
                streamW.Write(pageHtml);
                streamW.Close();
            }
            sw.Close();
            htw.Close();
        }
protected void InsertPhoto(string filePath)
        {
            //生成图片
            string imagePath = MapPath("/File2/" + Request.QueryString["ID"].ToString() + ".png");
            Session["imagePath"] = imagePath;
            //插入图片;
            StringBuilder reportContent = new StringBuilder();

            object Nothing = System.Reflection.Missing.Value;
            object filename = filePath;
            Microsoft.Office.Interop.Word.Application WordApp2 = new Microsoft.Office.Interop.Word.Application();//.ApplicationClass();
            Microsoft.Office.Interop.Word.Document WordDoc2 = WordApp2.Documents.Open(ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);

            //此处打开的这个word实际为网页的文本格式(可用记事本打开看一下),需另存为doc格式,
            //才能把图片嵌入到word文档中,否则保存的永远就是链接
            WordDoc2.SaveAs(filePath, WdSaveFormat.wdFormatDocument);

            //循环Word文档中所有插入的图元,查找显示为空的图元,进行替换
            //因该Word文档是由HTML生成而来,存放的图片实际为空,类型为wdInlineShapeLinkedPicture,需替换为实际类型
            //IEnumerable<InlineShape> shape2 =new IEnumerable  WordDoc2.InlineShapes;
            foreach (InlineShape shape in WordDoc2.InlineShapes)
         {
//查找插入图形的位置 object oRange = WordDoc2.Paragraphs[17].Range;//获取图片插入的位置 object LinkToFile = false; object SaveWithDocument = true; //插入图形 WordDoc2.InlineShapes.AddPicture(imagePath, ref LinkToFile, ref SaveWithDocument, ref oRange); //删除显示为空的图元 shape.Select(); WordApp2.Selection.Delete(); break;  } //打开该文档时默认视图为页面视图方式 WordDoc2.ActiveWindow.View.Type = WdViewType.wdPrintView; //保存插入图片的Word WordDoc2.SaveAs(filePath, WdSaveFormat.wdFormatDocument); //关闭所有的Word文档 WordApp2.NormalTemplate.Saved = true; Object saveChanges2 = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges; WordApp2.Documents.Close(saveChanges2, Type.Missing, Type.Missing); //退出Word应用程序 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 void lnkToWord_Click(object sender, EventArgs e)
        { 
            Chart2.SaveImage(Server.MapPath("~/File2/" + Request.QueryString["ID"].ToString() + ".png"), ChartImageFormat.Png);
            Label lbName = fv.FindControl("lbName") as Label;
            string wordname = lbName.Text.ToString() + Request.QueryString["ID"];
            string filePath = MapPath("~/File2/") + wordname + ".doc";  //文件路径
            CreateWordFile(filePath);
            WritePageContentToWord(filePath);
            InsertPhoto(filePath);
            string FileName = wordname + ".doc";
            Response.Redirect(string.Format("~/File2/{0}", FileName));
            string ImagePath = Session["imagePath"].ToString();
        }

具体做法是:先将页面写成html,在写成html时将图片相对路径改成绝对路径,保存成一份word到服务器。此页面包含.Net里面的chart控件,所以先将chart控件变成图片存入服务器,最后将图片插入到word

原文地址:https://www.cnblogs.com/miaoying/p/4902531.html