A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© dongqinglove 中级黑马   /  2013-6-24 17:02  /  1953 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 dongqinglove 于 2013-6-26 12:27 编辑

今天写了一个读取Excel表里数据的程序,结果出错了,网上搜了很多解决方案,都没什么效果,这个程序有一部分是没有源码的,office装的是2003版本的,系统是w7旗舰64位
  1. public partial class ZSTeaManage_Import_Demo1 : System.Web.UI.Page
  2. {
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.     }
  6.     protected void button1_Click(object sender, EventArgs e)
  7.     {
  8.         if (f1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件
  9.         {
  10.             Response.Write("<script>alert('请您选择Excel文件')</script> ");
  11.             return;
  12.         }
  13.         string IsXls = Path.GetExtension(f1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
  14.         if (IsXls != ".xls")
  15.         {
  16.             Response.Write("<script>alert('只可以选择Excel文件')</script>");
  17.             return;
  18.         }
  19.         string filename = f1.FileName;
  20.         //文件upfiles还没有
  21.         string savePath = Server.MapPath(("Upload\\") + filename);//Server.MapPath 获得虚拟服务器相对路径

  22.         f1.SaveAs(savePath);
  23.         DataSet ds = ExcelSqlConnection(savePath, filename);
  24.         if (ds == null)
  25.         {
  26.             Response.Write("读取Excel失败!!!");
  27.         }
  28.         //DataRow[] dr = ds.Tables[0].Select();
  29.         //int rowsnum = ds.Tables[0].Rows.Count;
  30.         //if (rowsnum == 0)
  31.         //{
  32.         //    Response.Write("<script>alert('Excel表为空表,无数据!')</script>");
  33.         //}
  34.         //else
  35.         //{
  36.         //    for (int i = 0; i < dr.Length; i++)
  37.         //    {
  38.         //        //前面除了你需要在建立一个“upfiles”的文件夹外,其他的都不用管了,你只需要通过下面的方式获取Excel的值,然后再将这些值用你的方式去插入到数据库里面
  39.         //        string title = dr[i]["标题"].ToString();
  40.         //        string linkurl = dr[i]["链接地址"].ToString();
  41.         //        string categoryname = dr[i]["分类"].ToString();
  42.         //        string customername = dr[i]["内容商"].ToString();
  43.         //    }
  44.         //    Response.Write("<script>alert('Excle表导入成功!');</script>");
  45.         //}
  46.     }
  47.     /// <summary>
  48.     /// 连接Excel  读取Excel数据   并返回DataSet数据集合
  49.     /// </summary>
  50.     /// <param name="filepath">Excel服务器路径</param>
  51.     /// <param name="tableName">Excel表名称</param>
  52.     /// <returns></returns>
  53.     public static DataSet ExcelSqlConnection(string filepath, string tableName)
  54.     {
  55.         string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";
  56.         OleDbConnection ExcelConn = new OleDbConnection(strCon);
  57.         //try
  58.         //{
  59.         string strCom = string.Format("select * from [Sheet1$]");
  60.         ExcelConn.Open();
  61.         OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
  62.         DataSet ds = new DataSet();
  63.         myCommand.Fill(ds, "[" + tableName + "$]");
  64.         ExcelConn.Close();
  65.         return ds;
  66.         //}
  67.         //catch (Exception)
  68.         //{
  69.         //ExcelConn.Close();
  70.         //return null;
  71.         //}
  72.     }
  73. }
复制代码

希望能给小弟指点迷津,不甚感激

研究了3天,知道原因了,office的驱动没有,也装不了,因为系统是x64位的,office大部分都是x86的


评分

参与人数 1技术分 +1 收起 理由
杞文明 + 1

查看全部评分

2 个回复

倒序浏览

读取excel中的数据并且提交到数据库

本帖最后由 杜鹏 于 2013-6-24 18:07 编辑

/// <summary>
       /// 从指定的路径中读取excel,此方法单独写在了ASPNETControlHelper 这个类中;
       /// </summary>
       /// <param name="fileupload">上传控件名称</param>
       /// <param name="savePath">保存的路径</param>
       /// <param name="fileExtension">文件的扩展名</param>
       /// <returns></returns>
       public static string UploadFile(FileUpload fileupload,string savePath,params string[] fileExtension)
       {
           bool flag = false;
           string type = fileupload.FileName.Substring(fileupload.FileName.LastIndexOf('.')+1);
           foreach (string s in fileExtension)
           {
               if (type == s)
               {
                   flag = true;
                   break;
               }
           }
           if (flag)
           {
               string name = "";
               savePath = string.Format("{0}{1}.{2}",savePath,Guid.NewGuid().ToString(),type);
               fileupload.SaveAs(savePath);
               FileInfo ft = new FileInfo(savePath);
               if (ft.Length > 0)
               {
                   name = savePath.Substring(savePath.LastIndexOf("\\") + 1);
               }
               else
               {
                   name = "0";
               }
               return name;
           }
           return null;
       }

/// <summary>
       /// 从Excel中读取数据并提交到数据库,次方法写在了 Common类下的ExcelHelper通用方法中 ;
       /// </summary>
       /// <param name="uploadFile">上传控件的名称</param>
       /// <returns></returns>
       public static DataTable GetDataSetFromExcel(FileUpload uploadFile)
       {
           try
           {
               string filename = ASPNETControlHelper.UploadFile(uploadFile, System.Web.HttpContext.Current.Server.MapPath("~/Template/"),"xls","xlsx");
               OleDbConnection conn = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0",System.Web.HttpContext.Current.Server.MapPath("~/Template/")+filename));
               try
               {
                   conn.Open();
               }
               catch
               {
                   conn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", System.Web.HttpContext.Current.Server.MapPath("~/Template/") + filename));
                   conn.Open();
               }
               OleDbCommand cmd = conn.CreateCommand();
               cmd.CommandText = "select * from [Sheet1$]";
               OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
               DataSet ds = new DataSet();
               oda.Fill(ds);
               DataTable dt = ds.Tables[0];

               return dt;
           }
           catch
           {
               throw;
           }
       }
protected void btnImport_Click(object sender, EventArgs e)
{
DataTable dt = Common.ExcelHelper.GetDataSetFromExcel(uploadFile);//至此,将Excel中的数据源存到DataTable中,继而可以进行其他操作
}

评分

参与人数 1技术分 +1 收起 理由
杞文明 + 1

查看全部评分

回复 使用道具 举报
杜鹏 发表于 2013-6-24 17:59
///
       /// 从指定的路径中读取excel,此方法单独写在了ASPNETControlHelper 这个类中;
       ///

谢谢你的解答,但你并没有解决问题,只是把问题转化了,
  1. try
  2.         {
  3.             string filename = UploadFile(uploadFile, System.Web.HttpContext.Current.Server.MapPath("~/upload/"), "xls", "xlsx");
  4.      <span style="color: Red;">       OleDbConnection conn = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0", System.Web.HttpContext.Current.Server.MapPath("~/upload/") + filename));</span>
  5.             try
  6.             {
  7.                 conn.Open();
  8.             }
  9.             catch
  10.             {
  11.               <span style="color: Red;">  conn = new OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 12.0", System.Web.HttpContext.Current.Server.MapPath("~/upload/") + filename));</span>
  12.                 conn.Open();
  13.             }
  14. ....}
  15. catch
  16. {}
  17. 现在报<i style="color: Red;">未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。<span style="color: DarkSlateGray;">我估计是我环境的问题,有没有办法解决呢,谢谢你了</span></i>
复制代码
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马