aspx根据模板导出word(含文字和图片)

来源:互联网 发布:网上绘图软件 编辑:程序博客网 时间:2024/06/05 07:34

如上图,word模板。word中插入表格。如用户需要表格形式,自己将表格线条去掉即可。


后台代码:

/* * 日期:2016年12月13 20:05 * 作者:王振 QQ 273509239  * 功能描述:用于导出word,word模板可自行定义 *  * 用到的DLL:Microsoft.Office.Interop.Word.dll  */using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using Word = Microsoft.Office.Interop.Word;namespace WebWordDemo{    public partial class WebFormWord : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {        }        /// <summary>        /// 导出Word 按钮        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void btnExportWord_Click(object sender, EventArgs e)        {            try            {                WordModel model = new WordModel();                model.title = txtTitle.Text;                model.content = txtContent.Text;                ExpWordByWord(model);            }            catch (Exception ex)            {            }        }        #region Word操作        /// <summary>        /// word操作  根据Word模板生成word        /// </summary>        /// <returns></returns>        private string ExpWordByWord(WordModel model)        {            string resultMsg = "";            if (model != null)            {                object temp;                temp = System.Web.HttpContext.Current.Server.MapPath("~/WordTempPath/TemplateTable.doc");//读取模板文件  使用见WordTempPath下的 模板说明.txt                string expFileName = System.DateTime.Now.ToString("yyyy年MM月dd日 HH时mm分ss秒") + ".doc";//保存的word文件名,可自行定义                Word.Application app = new Word.Application();                //表示System.Type信息中的缺少值                object nothing = Type.Missing;                try                {                    //建立一个基于摸版的文档                    Word._Document doc = app.Documents.Add(ref temp, ref nothing, ref nothing, ref nothing);                    //得到第一个表格                    Word.Table tbl = doc.Tables[1];//正常情况下,列表索引值从0开始,但是word的索引值却是从1开始,Excel类似。                    //在指定单元格填值  每行只有一列                    tbl.Cell(1, 1).Range.Text = model.title;//第一行第一列                    tbl.Cell(2, 1).Range.Text = model.content;//第二行第一列                    //tbl.Cell(3, 1).Range.Text = model.content;//第三行第一列                    //tbl.Cell(4, 1).Range.Text = model.content;//第四行第一列                    object fileName = "";                    //保存到服务器(这里使用guid,或使用时间加随机数)                    tbl.Cell(3, 1).Range.Text = model.content;//第三行第一列 可以在同一个单元格插入图片或者文字                    object range = tbl.Cell(3, 1).Range;//存储图片                    object linkToFile = System.Reflection.Missing.Value;                    string imgFileName = "http://p1.so.qhmsg.com/bdr/200_200_/t0115949a42d922c6bb.jpg";//图片url                    object LinkToFile = Type.Missing;                    object SaveWithDocument = Type.Missing;                    Word.InlineShape shape = app.ActiveDocument.InlineShapes.AddPicture(imgFileName, ref linkToFile, ref SaveWithDocument, ref range);                    shape.Width = 100f;//图片宽度                    shape.Height = 120f;//图片高度                    shape.ConvertToShape().WrapFormat.Type = Word.WdWrapType.wdWrapSquare;//文字四周环绕的方式                    fileName = System.Web.HttpContext.Current.Server.MapPath("~/WordTempPath/") + expFileName;//获取服务器路径                    //保存doc文档                    doc.SaveAs(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);                    doc.Close(ref nothing, ref nothing, ref nothing);                    app.Quit(ref nothing, ref nothing, ref nothing);                    ExtWord(fileName.ToString(), expFileName);//输出word                }                catch (Exception ex)                {                    resultMsg = "导出错误:" + ex.Message;                }                finally                {                    app.Quit(ref nothing, ref nothing, ref nothing);                }            }            else            {                resultMsg = "暂无数据";            }            return resultMsg;        }        /// <summary>        /// 输出word        /// </summary>        /// <param name="filename"></param>        private void ExtWord(string fileName, string wordname)        {            try            {                Response.Redirect("/WordTempPath/" + wordname, false);//endResponse属性必须写false,否则会报错            }            catch (Exception ex)            {            }        }        ///// <summary>        ///// 输出word        ///// </summary>        ///// <param name="filename"></param>        //private void ExtWord(string fileName, string wordname)        //{        //    try        //    {        //        //输出word        //        System.IO.FileInfo file = new System.IO.FileInfo(fileName);        //        System.Web.HttpContext.Current.Response.Clear();        //        System.Web.HttpContext.Current.Response.Charset = "GB2312";        //        System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;        //        // 添加头信息,为"文件下载/另存为"对话框指定默认文件名         //        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(wordname, System.Text.Encoding.UTF8));        //        // 添加头信息,指定文件大小,让浏览器能够显示下载进度         //        System.Web.HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());        //        // 指定返回的是一个不能被客户端读取的流,必须被下载         //        System.Web.HttpContext.Current.Response.ContentType = "application/ms-word";        //        // 把文件流发送到客户端         //        System.Web.HttpContext.Current.Response.WriteFile(file.FullName);        //        // 停止页面的执行         //        //HttpContext.Current.ApplicationInstance.CompleteRequest        //        System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();        //    }        //    catch (Exception ex)        //    {        //    }        //}        #endregion    }    /// <summary>    /// 导出word实体类 可根据需要自行扩展    /// </summary>    public class WordModel    {        /// <summary>        /// 标题        /// </summary>        public string title { get; set; }        /// <summary>        /// 内容        /// </summary>        public string content { get; set; }    }}

前台页面代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebFormWord.aspx.cs" Inherits="WebWordDemo.WebFormWord" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />    <title></title></head><body>    <form id="form1" runat="server">        <div>            <asp:Label ID="Label1" runat="server" Text="书名"></asp:Label>            <asp:TextBox ID="txtTitle" runat="server" Width="450px" Text="我是标题"></asp:TextBox>        </div>        <div style="clear: both;">        </div>        <div>            <asp:Label ID="Label2" runat="server" Text="内容"></asp:Label>            <asp:TextBox ID="txtContent" runat="server"  Width="450px" Height="450px" Text="我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容我是内容"></asp:TextBox>        </div>        <div style="clear: both;">        </div>        <div>            <asp:Button runat="server" ID="btnExportWord" OnClick="btnExportWord_Click" Text="导出word" />        </div>    </form></body></html>

导出word:


0 0