asp.net页面怎么数据导出到word 文档?

时间:2022-01-11 06:16:56
asp.net页面的数据导出到word文档~~~

里面有图片怎么解决~~~~~~~~

现在有点急~~

16 个解决方案

#1


恐怕有图片还真没办法。
word可以打开.html格式,你似乎可以保存成.html
只是后缀名改一下。

#2


ASP.NET(C#)将数据导出到Word或Excel 
命名空间:
using System.IO;
using System.Text;
将DataGrid的数据导出到Excel
         string excelname="excel文件名";
         HttpContext.Current.Response.Charset = "GB2312";
         HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
         HttpContext.Current.Response.ContentType = "application/ms-excel";
         HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".xls");
         dr1.Page.EnableViewState = false;
         StringWriter sw = new StringWriter();
         HtmlTextWriter tw = new HtmlTextWriter(sw);
         dr1.RenderControl(tw);
         HttpContext.Current.Response.Write(sw.ToString());
         HttpContext.Current.Response.End();



将DataGrid的数据导出到Word
         string excelname="word文件名";
         HttpContext.Current.Response.Charset = "GB2312";
         HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
         HttpContext.Current.Response.ContentType = "application/ms-winword";
         HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".doc");
         dr1.Page.EnableViewState = false;
         StringWriter sw = new StringWriter();
         HtmlTextWriter tw = new HtmlTextWriter(sw);
         dr1.RenderControl(tw);
         HttpContext.Current.Response.Write(sw.ToString());
         HttpContext.Current.Response.End(); 
ASP.NET 2.0,C#----利用GridView控件导出其他文件(导出Excel,导出Word文件) 
// 注意,在Visual Studio2005平台下,如果使用GridView导出文件,

     //就必须重载VerifyRenderingInServerForm方法

        public override void VerifyRenderingInServerForm(Control control)

        {

           

        }

 

        /// <summary>

        ///  导出到文件的方法,

        /// </summary>

        /// <param name="Model">Model=1:导出为Execl,Model=2:导出为Word</param>

        private void toFiles(int Model)

        {

            string strFileName = DateTime.Now.ToString("yyyyMMdd-hhmmss");

            System.Web.HttpContext HC = System.Web.HttpContext.Current;

             HC.Response.Clear();

             HC.Response.Buffer = true;

             HC.Response.ContentEncoding = System.Text.Encoding.UTF8;//设置输出流为简体中文

 

            if (Model == 1)

            {

                //---导出为Excel文件

                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls");

                 HC.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。

            }

            else

            {

                //--- 导出为Word文件

                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".doc");

                 HC.Response.ContentType = "application/ms-word";//设置输出文件类型为Word文件。

            }

 

            System.IO.StringWriter sw = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            this.GridView1.RenderControl(htw);

 

             HC.Response.Write(sw.ToString());

             HC.Response.End(); 

          

        }

        //-导出为Excel文件

        protected void ToExecl_Click(object sender, EventArgs e)

        {

            toFiles(1);

        }

        //-导出为Word文件

        protected void Button1_Click(object sender, EventArgs e)

        {

            toFiles(2);

        }  

#3


没有看到,有图片不好办

#4


不难 引用 word.dll 还是挺简单的

 private byte [] CreateDOC ( Dictionary<string, string> dicHeader, Dictionary<int, Dictionary<string, string>> dicProductCollection ) {
                 ........
                 ........
                 ........

                            string fileName = path;
                            if ( File.Exists ( fileName ) ) {     //图片存在就加进去
                                object linkToFile = false;
                                object saveWithDocument = true;
                                b = wordApp.Selection.Find.Execute (
                                     ref from, 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 );
                                wordApp.Selection.Text = "";
                                object anchor = wordDoc.Application.Selection.Range;
                                wordDoc.Application.ActiveDocument.InlineShapes.AddPicture ( fileName, ref linkToFile, ref saveWithDocument, ref anchor ); // 添加图片
                                                              
                                float [] arrFix = GetFixImage ( fileName, 180 );
                                if ( arrFix [0] != 0 && arrFix [1] != 0 ) {  //设置宽度 
                                    wordDoc.Application.ActiveDocument.InlineShapes [pictureCount].Width = arrFix [0];//图片宽度
                                    wordDoc.Application.ActiveDocument.InlineShapes [pictureCount].Height = arrFix [1];//图片高度
                                }
                                pictureCount++;
                            } else {

                                to = "";
                                b = wordApp.Selection.Find.Execute (
                                  ref from, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                  ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref to,
                                  ref replaceOne, ref Nothing, ref Nothing, ref Nothing, ref Nothing ); //替换掉#image
                            }
                        }
                    }

                }
                #endregion
                string folder = ConfigurationManager.AppSettings ["Folder"];
                string outPath = Server.MapPath ( folder );
                object name = DateTime.Now.Year.ToString () + "_" + DateTime.Now.Month.ToString () + "_" + DateTime.Now.Day.ToString () +
                     "_" + DateTime.Now.Hour.ToString () + "_" + DateTime.Now.Minute.ToString () + "_" + DateTime.Now.Second.ToString () + ".doc";
                object filename = outPath + "\\" + name;
                if ( !Directory.Exists ( outPath ) ) {
                    Directory.CreateDirectory ( outPath );
                }
                wordDoc.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 );
                wordDoc.Close ( ref Nothing, ref Nothing, ref Nothing );
                wordApp.Quit ( ref Nothing, ref Nothing, ref Nothing );
                GC.Collect ();
                byte [] bytes = File.ReadAllBytes ( filename.ToString () );
                return bytes;
            } catch ( SystemException ee ) {
                log.Error ( "OfferSheet Word Error:" + ee.ToString () );
                GC.Collect ();
                return null;
            }

        }

        private float [] GetFixImage ( string fileName ,float fixNumber) {
            float [] arrFix = new float [2];
            System.Drawing.Image imageCheck = System.Drawing.Image.FromFile ( fileName );
            if ( Convert.ToInt32 ( imageCheck.Width ) > 400 || Convert.ToInt32 ( imageCheck.Height ) > 400 ) {
                if ( imageCheck.Width > imageCheck.Height ) {         // 宽》高
                    arrFix [0] = fixNumber;
                    arrFix [1] = fixNumber * Convert.ToInt32 ( imageCheck.Height ) / Convert.ToInt32 ( imageCheck.Width );
                } else {
                    arrFix [0] =  fixNumber * Convert.ToInt32 ( imageCheck.Width ) / Convert.ToInt32 ( imageCheck.Height );
                    arrFix [1] = fixNumber;
                }

            } else {
                arrFix [0] = 0;
                arrFix [1] = 0;
            }
            return arrFix;
        }
        
    }


#5


试试楼上的方法,但愿通决有图片时的问题

#6


不用dll用2楼方法导不进去吗?

#7


应该有这样的dll,你找找吧。

#9


学习

#10


顶四楼~

是必须引用msword.olb得

#11


msword.olb
这是一个什么啊~~~?

是什么文件?

#12


4楼的,可不可以把你的那3个省略号的
代码也贴出来~~~

2楼的方法很好用,就是图片不能解决

#13



     private byte [] CreateDOC ( Dictionary<string, string> dicHeader, Dictionary<int, Dictionary<string, string>> dicProductCollection ) {
            try {

                string inPath = ConfigurationManager.AppSettings [""];

                object templetName = Server.MapPath ( inPath );
                word.Application wordApp = new word.ApplicationClass ();
                word.Document wordDoc = wordApp.Documents.Add ( ref templetName, ref Nothing, ref Nothing, ref Nothing );
                wordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
                wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
                object from, to;
                bool b = false;
                object replaceOne = WdReplace.wdReplaceAll;

                #region 表头
                foreach ( KeyValuePair<string, string> keyVo in dicHeader ) {
                    from = "#" + keyVo.Key + "#";
                    to = keyVo.Value;
                    b = wordApp.Selection.Find.Execute (
                       ref from, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                       ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref to,
                       ref replaceOne, ref Nothing, ref Nothing, ref Nothing, ref Nothing );
                }
                wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
                #endregion

                #region Product
                int productCount = dicProductCollection.Count; //统计有多少product
                int pictureCount = 1;
                wordApp.ActiveDocument.Tables [1].Select ();
                wordApp.ActiveWindow.Selection.Cut ();
                object unit, count;
                unit = WdUnits.wdParagraph;
                count = 1;
                object nextPage = WdBreakType.wdSectionBreakNextPage;
                wordApp.ActiveWindow.Selection.Paste ();
                wordApp.ActiveWindow.Selection.MoveEnd ( ref unit, ref count );
                for ( int i = 1; i < productCount; i++ ) {                           //循环复制Product Table
                    wordApp.ActiveWindow.Selection.InsertBreak ( ref nextPage );
                    wordApp.ActiveWindow.Selection.Paste ();
                    wordApp.ActiveWindow.Selection.MoveEnd ( ref unit, ref count );
                }
                for ( int i = 1; i <= productCount; i++ ) {
                    wordApp.ActiveDocument.Tables [i].Select ();
                    foreach ( KeyValuePair<string, string> keyVo in dicProductCollection [i] ) {  //替换   
                        //Dictionary<string, string> dicPrudct = ( Dictionary<string, string> ) dicProductCollection [i].Values;
                        from = "#" + keyVo.Key + "#";
                        to = Server.HtmlDecode ( keyVo.Value );
                        if ( keyVo.Key != "image" ) {
                                b = wordApp.Selection.Find.Execute (
                               ref from, 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 );
                                wordApp.Selection.Text = to.ToString ().Replace ( "^p", "\r\n" );
                                wordApp.ActiveDocument.Tables [i].Select ();
                        } else {
                            string path = Server.MapPath ( "" );
                            path = path.Substring ( 0, path.LastIndexOf ( "\\" ) );

                            path += "\\" + to.ToString ().Replace ( "/", "\\" );
                              //........ 太长了 放不下 ,这里接上面

       


其实网上找找都有很多的......

#14


用 office控件来实现

#15


还是谢谢各位的意见~~~

4楼的代码太多了~~~用不太好~~有些地方也不明白`~

自己也找到了一个方法~~~~~~但是也不太理想,

唉,郁闷啊~~~~

自己在找找~有没有更好的~~


#16


HHE 

#1


恐怕有图片还真没办法。
word可以打开.html格式,你似乎可以保存成.html
只是后缀名改一下。

#2


ASP.NET(C#)将数据导出到Word或Excel 
命名空间:
using System.IO;
using System.Text;
将DataGrid的数据导出到Excel
         string excelname="excel文件名";
         HttpContext.Current.Response.Charset = "GB2312";
         HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
         HttpContext.Current.Response.ContentType = "application/ms-excel";
         HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".xls");
         dr1.Page.EnableViewState = false;
         StringWriter sw = new StringWriter();
         HtmlTextWriter tw = new HtmlTextWriter(sw);
         dr1.RenderControl(tw);
         HttpContext.Current.Response.Write(sw.ToString());
         HttpContext.Current.Response.End();



将DataGrid的数据导出到Word
         string excelname="word文件名";
         HttpContext.Current.Response.Charset = "GB2312";
         HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
         HttpContext.Current.Response.ContentType = "application/ms-winword";
         HttpContext.Current.Response.AppendHeader("Content-disposition", "attachment;filename=" + excelname + ".doc");
         dr1.Page.EnableViewState = false;
         StringWriter sw = new StringWriter();
         HtmlTextWriter tw = new HtmlTextWriter(sw);
         dr1.RenderControl(tw);
         HttpContext.Current.Response.Write(sw.ToString());
         HttpContext.Current.Response.End(); 
ASP.NET 2.0,C#----利用GridView控件导出其他文件(导出Excel,导出Word文件) 
// 注意,在Visual Studio2005平台下,如果使用GridView导出文件,

     //就必须重载VerifyRenderingInServerForm方法

        public override void VerifyRenderingInServerForm(Control control)

        {

           

        }

 

        /// <summary>

        ///  导出到文件的方法,

        /// </summary>

        /// <param name="Model">Model=1:导出为Execl,Model=2:导出为Word</param>

        private void toFiles(int Model)

        {

            string strFileName = DateTime.Now.ToString("yyyyMMdd-hhmmss");

            System.Web.HttpContext HC = System.Web.HttpContext.Current;

             HC.Response.Clear();

             HC.Response.Buffer = true;

             HC.Response.ContentEncoding = System.Text.Encoding.UTF8;//设置输出流为简体中文

 

            if (Model == 1)

            {

                //---导出为Excel文件

                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".xls");

                 HC.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。

            }

            else

            {

                //--- 导出为Word文件

                 HC.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8) + ".doc");

                 HC.Response.ContentType = "application/ms-word";//设置输出文件类型为Word文件。

            }

 

            System.IO.StringWriter sw = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);

            this.GridView1.RenderControl(htw);

 

             HC.Response.Write(sw.ToString());

             HC.Response.End(); 

          

        }

        //-导出为Excel文件

        protected void ToExecl_Click(object sender, EventArgs e)

        {

            toFiles(1);

        }

        //-导出为Word文件

        protected void Button1_Click(object sender, EventArgs e)

        {

            toFiles(2);

        }  

#3


没有看到,有图片不好办

#4


不难 引用 word.dll 还是挺简单的

 private byte [] CreateDOC ( Dictionary<string, string> dicHeader, Dictionary<int, Dictionary<string, string>> dicProductCollection ) {
                 ........
                 ........
                 ........

                            string fileName = path;
                            if ( File.Exists ( fileName ) ) {     //图片存在就加进去
                                object linkToFile = false;
                                object saveWithDocument = true;
                                b = wordApp.Selection.Find.Execute (
                                     ref from, 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 );
                                wordApp.Selection.Text = "";
                                object anchor = wordDoc.Application.Selection.Range;
                                wordDoc.Application.ActiveDocument.InlineShapes.AddPicture ( fileName, ref linkToFile, ref saveWithDocument, ref anchor ); // 添加图片
                                                              
                                float [] arrFix = GetFixImage ( fileName, 180 );
                                if ( arrFix [0] != 0 && arrFix [1] != 0 ) {  //设置宽度 
                                    wordDoc.Application.ActiveDocument.InlineShapes [pictureCount].Width = arrFix [0];//图片宽度
                                    wordDoc.Application.ActiveDocument.InlineShapes [pictureCount].Height = arrFix [1];//图片高度
                                }
                                pictureCount++;
                            } else {

                                to = "";
                                b = wordApp.Selection.Find.Execute (
                                  ref from, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                                  ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref to,
                                  ref replaceOne, ref Nothing, ref Nothing, ref Nothing, ref Nothing ); //替换掉#image
                            }
                        }
                    }

                }
                #endregion
                string folder = ConfigurationManager.AppSettings ["Folder"];
                string outPath = Server.MapPath ( folder );
                object name = DateTime.Now.Year.ToString () + "_" + DateTime.Now.Month.ToString () + "_" + DateTime.Now.Day.ToString () +
                     "_" + DateTime.Now.Hour.ToString () + "_" + DateTime.Now.Minute.ToString () + "_" + DateTime.Now.Second.ToString () + ".doc";
                object filename = outPath + "\\" + name;
                if ( !Directory.Exists ( outPath ) ) {
                    Directory.CreateDirectory ( outPath );
                }
                wordDoc.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 );
                wordDoc.Close ( ref Nothing, ref Nothing, ref Nothing );
                wordApp.Quit ( ref Nothing, ref Nothing, ref Nothing );
                GC.Collect ();
                byte [] bytes = File.ReadAllBytes ( filename.ToString () );
                return bytes;
            } catch ( SystemException ee ) {
                log.Error ( "OfferSheet Word Error:" + ee.ToString () );
                GC.Collect ();
                return null;
            }

        }

        private float [] GetFixImage ( string fileName ,float fixNumber) {
            float [] arrFix = new float [2];
            System.Drawing.Image imageCheck = System.Drawing.Image.FromFile ( fileName );
            if ( Convert.ToInt32 ( imageCheck.Width ) > 400 || Convert.ToInt32 ( imageCheck.Height ) > 400 ) {
                if ( imageCheck.Width > imageCheck.Height ) {         // 宽》高
                    arrFix [0] = fixNumber;
                    arrFix [1] = fixNumber * Convert.ToInt32 ( imageCheck.Height ) / Convert.ToInt32 ( imageCheck.Width );
                } else {
                    arrFix [0] =  fixNumber * Convert.ToInt32 ( imageCheck.Width ) / Convert.ToInt32 ( imageCheck.Height );
                    arrFix [1] = fixNumber;
                }

            } else {
                arrFix [0] = 0;
                arrFix [1] = 0;
            }
            return arrFix;
        }
        
    }


#5


试试楼上的方法,但愿通决有图片时的问题

#6


不用dll用2楼方法导不进去吗?

#7


应该有这样的dll,你找找吧。

#8


#9


学习

#10


顶四楼~

是必须引用msword.olb得

#11


msword.olb
这是一个什么啊~~~?

是什么文件?

#12


4楼的,可不可以把你的那3个省略号的
代码也贴出来~~~

2楼的方法很好用,就是图片不能解决

#13



     private byte [] CreateDOC ( Dictionary<string, string> dicHeader, Dictionary<int, Dictionary<string, string>> dicProductCollection ) {
            try {

                string inPath = ConfigurationManager.AppSettings [""];

                object templetName = Server.MapPath ( inPath );
                word.Application wordApp = new word.ApplicationClass ();
                word.Document wordDoc = wordApp.Documents.Add ( ref templetName, ref Nothing, ref Nothing, ref Nothing );
                wordApp.ActiveWindow.View.Type = WdViewType.wdOutlineView;
                wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
                object from, to;
                bool b = false;
                object replaceOne = WdReplace.wdReplaceAll;

                #region 表头
                foreach ( KeyValuePair<string, string> keyVo in dicHeader ) {
                    from = "#" + keyVo.Key + "#";
                    to = keyVo.Value;
                    b = wordApp.Selection.Find.Execute (
                       ref from, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                       ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref to,
                       ref replaceOne, ref Nothing, ref Nothing, ref Nothing, ref Nothing );
                }
                wordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekMainDocument;//跳出页眉设置
                #endregion

                #region Product
                int productCount = dicProductCollection.Count; //统计有多少product
                int pictureCount = 1;
                wordApp.ActiveDocument.Tables [1].Select ();
                wordApp.ActiveWindow.Selection.Cut ();
                object unit, count;
                unit = WdUnits.wdParagraph;
                count = 1;
                object nextPage = WdBreakType.wdSectionBreakNextPage;
                wordApp.ActiveWindow.Selection.Paste ();
                wordApp.ActiveWindow.Selection.MoveEnd ( ref unit, ref count );
                for ( int i = 1; i < productCount; i++ ) {                           //循环复制Product Table
                    wordApp.ActiveWindow.Selection.InsertBreak ( ref nextPage );
                    wordApp.ActiveWindow.Selection.Paste ();
                    wordApp.ActiveWindow.Selection.MoveEnd ( ref unit, ref count );
                }
                for ( int i = 1; i <= productCount; i++ ) {
                    wordApp.ActiveDocument.Tables [i].Select ();
                    foreach ( KeyValuePair<string, string> keyVo in dicProductCollection [i] ) {  //替换   
                        //Dictionary<string, string> dicPrudct = ( Dictionary<string, string> ) dicProductCollection [i].Values;
                        from = "#" + keyVo.Key + "#";
                        to = Server.HtmlDecode ( keyVo.Value );
                        if ( keyVo.Key != "image" ) {
                                b = wordApp.Selection.Find.Execute (
                               ref from, 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 );
                                wordApp.Selection.Text = to.ToString ().Replace ( "^p", "\r\n" );
                                wordApp.ActiveDocument.Tables [i].Select ();
                        } else {
                            string path = Server.MapPath ( "" );
                            path = path.Substring ( 0, path.LastIndexOf ( "\\" ) );

                            path += "\\" + to.ToString ().Replace ( "/", "\\" );
                              //........ 太长了 放不下 ,这里接上面

       


其实网上找找都有很多的......

#14


用 office控件来实现

#15


还是谢谢各位的意见~~~

4楼的代码太多了~~~用不太好~~有些地方也不明白`~

自己也找到了一个方法~~~~~~但是也不太理想,

唉,郁闷啊~~~~

自己在找找~有没有更好的~~


#16


HHE