• ASP.NET用DataSet导出到Excel


    //读取临时文件
       GYYW.DA.Common.Base_SqlDataBase daBZDM = new GYYW.DA.Common.Base_SqlDataBase();
       DataSet dsBZDM = daBZDM.GetDataSetBySql("select QCDM,MC,GG from WG_BZDM where QCDM like '02%'");
     
     
       //同时将虚拟目录下的Data作为临时文件目录。
       string urlPath = HttpContext.Current.Request.ApplicationPath + "/Data/";
       string physicPath = HttpContext.Current.Server.MapPath(urlPath);
       //string fileName = Guid.NewGuid() + ".Xls";
       string fileName ="DownLoad.Xls";
       string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + physicPath + fileName +";Extended Properties=Excel 8.0;";
     
       OleDbConnection objConn = new OleDbConnection(connString);
       OleDbCommand objCmd = new OleDbCommand();
       objCmd.Connection = objConn;
       objCmd.Connection.Open();
     
     
       //建立表结构
       objCmd.CommandText = @"CREATE TABLE Sheet1(器材代码 varchar,名称 varchar, 规格 varchar)";
       objCmd.ExecuteNonQuery();
     
       //建立插入动作的Command
     
       objCmd.CommandText = "INSERT INTO Sheet1(器材代码, 名称,规格) VALUES (@QCDM, @MC, @GG)";
     
       objCmd.Parameters.Clear();
     
       objCmd.Parameters.Add(new OleDbParameter("@QCDM", OleDbType.VarChar));
       objCmd.Parameters.Add(new OleDbParameter("@MC", OleDbType.VarChar));
       objCmd.Parameters.Add(new OleDbParameter("@GG",OleDbType.VarChar));
      
       //遍历DataSet将数据插入新建的Excel文件中
       foreach (DataRow row in dsBZDM.Tables[0].Rows)
       {  
        for (int i=0; i<objCmd.Parameters.Count; i++)
        {
         objCmd.Parameters[i].Value = row[i];
        }
        objCmd.ExecuteNonQuery();
       }
       objCmd.Connection.Close();
     
       //提供下载
       //清除临时文件
       HttpResponse response = HttpContext.Current.Response;
       response.Clear();
       //为输出作准备
       response.WriteFile(urlPath + fileName);
       string httpHeader="attachment;filename=KCMX.Xls";
       response.AppendHeader("Content-Disposition", httpHeader);
       response.Flush();
       //输出完毕后清除临时文件
       string strSaveDir = "../Data/";
       string strFile = Server.MapPath(strSaveDir + fileName).ToString();
       //string sss = urlPath + fileName;
       System.IO.File.Delete(strFile);//删除临时文件
       response.End();
  • 相关阅读:
    Eclipse配置Maven3.5
    VM搭建Hadoop环境静态IP未起作用
    Word2010制作倒福字
    Word2010制作日历
    【整理】HTML5游戏开发学习笔记(1)- 骰子游戏
    [转载]HTML5开发入门经典教程和案例合集(含视频教程)
    [转载]如何做到 jQuery-free?
    [转载]教你如何塑造JavaScript牛逼形象
    Cloud9免费云IDE代码编辑平台空间支持Node.js,PHP,Python可使用FTP管理
    [转载]PayPal为什么从Java迁移到Node.js,性能提高一倍,文件代码减少44%
  • 原文地址:https://www.cnblogs.com/armyfai/p/4782999.html
Copyright © 2020-2023  润新知