• 2012年11月23日c#生成Excel文件在服务器并且可以导出到本地


    c#生成Excel文件在服务器并且可以导出到本地

    许多导出Excel都是导出到本地,而很多时候我们都要生成到服务器上。

    好,不多说,先把代码贴出来先.

    首先在头部要using

    using System.IO;
    using System.Text;
    using System.Data;
    using MSExcel=Microsoft.Office.Interop.Excel;
    using System.Reflection;

    如果没有把Excel的dll文件引用进来,首先要引用。在右键添加引用后选择.net里面就能找到了。

    接下来,先给出导出到本地的代码,

    首先要重写一个方法:

        public override void VerifyRenderingInServerForm(Control control)
        {
            // Confirms that an HtmlForm control is rendered for
        }

    然后在摸个按钮事件,或者写成个方法生成Excel文件到本地:

        protected void ButtonToExcel_Click(object sender, EventArgs e)   

      {         

          Response.Clear();   

          Response.Buffer = false;    

         Response.Charset = "GB2312";    

         Response.AppendHeader("Content-Disposition", "attachment;filename=MyExcel.xls");     //文件名为MyExcel 

       Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");    //编码格式

         Response.ContentType = "application/ms-excel";   

          this.EnableViewState = false;     

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

         HtmlTextWriter oHtmlTextWriter = new HtmlTextWriter(oStringWriter);  

           GridViewExcel.RenderControl(oHtmlTextWriter);     //GridViewExcel为GridView的ID

        Response.Write(oStringWriter.ToString());      

       Response.End();

        }

    好,接下来贴出生成到服务器的代码:

        private void CreateExcel()
        {
            object path;
            MSExcel.Application excelApp;
            MSExcel.Workbook excelDoc;
            path = Server.MapPath("~/MyExcel.xls");//在服务的根文件夹下生成MyExcel.xls文件
            excelApp = new MSExcel.ApplicationClass();
            if (File.Exists((string)path))
            {
                File.Delete((string)path);//判断是否存在,如果存在就删掉。
            }
            Object Nothing = Missing.Value;
            excelDoc = excelApp.Workbooks.Add(Nothing);
            MSExcel.Worksheet MyWorkSheet = (MSExcel.Worksheet)excelDoc.Worksheets[1];
            MyWorkSheet.get_Range("A1", System.Type.Missing).Value2 = "技术";
            MyWorkSheet.get_Range("B1", System.Type.Missing).Value2 = "掌握程度";//这里是内容,按Excel里面的格式填就好了。
            object format = MSExcel.XlFileFormat.xlWorkbookDefault;
            excelDoc.SaveAs(path, Nothing, Nothing, Nothing, Nothing, Nothing, MSExcel.XlSaveAsAccessMode.xlExclusive, Nothing, Nothing, Nothing, Nothing, Nothing);
            excelDoc.Close(Nothing, Nothing, Nothing);
            excelApp.Quit();
        }

  • 相关阅读:
    python导入数据的几种方法
    sql 如何删除(代替)字段内某一部分内容
    SQL Server如何将查询的内容保存到新的sql 表中
    sqlserver 计算同比,环比增长
    SQLlite实现增删查改
    如何实现基于框架的选课系统的质量属性
    实验1.2:框架选择及其原因
    期末考试复习c#时总结的抽象类与接口的一些区别
    <<梦断代码>>读书笔记
    结对开发首尾相接数组求子数组最大和
  • 原文地址:https://www.cnblogs.com/zknu/p/2786467.html
Copyright © 2020-2023  润新知