读取Excel

首先引用

using Microsoft.Office.Interop.Excel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Text;

用Oledb方式读Excel

if (FileUpload1.HasFile)//判断上传控件是否包含文件
            {
                string time = DateTime.Now.ToString("yyyy_MM_dd_H_mm_ss");//获取当前时间
                string path = Server.MapPath("~/Excel/") + time + " " + FileUpload1.FileName;//保存路径+文件名
                FileUpload1.PostedFile.SaveAs(path);//保存文件到服务器端

                string filepath = path;//获取当前文件路径
                string geshi = System.IO.Path.GetExtension(filepath).ToLower();//获取当前文件的格式
                StringBuilder strcon = new StringBuilder();//获取链接excel的字符串
                int i = 0;
                switch (geshi)
                { 
                    case ".xls":
                        strcon.Append("Provider =Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'");//连接excel文件的字符串(用于2003版以前)
                        i = 1;
                        break;
                    case ".xlsx":
                        strcon.Append ("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + filepath + "';Extended Properties='Excel 12.0;HDR=YES'");//用于2007版以后
                        break;
                }
                if (filepath == null)//如果文件不存在返回
                {
                    return;
                }
                OleDbConnection con = new OleDbConnection(strcon.ToString());
                StringBuilder sql = new StringBuilder("select * from [Sheet1$]");//查询excel第一个sheet
                OleDbDataAdapter da = new OleDbDataAdapter(sql.ToString(), con);
                DataSet ds = new DataSet();
                da.Fill(ds);//获取数据集
                for (; i < ds.Tables[0].Rows.Count; i++)//遍历
                { 
                    //从第二行开始读取
                }
            }

 

posted @ 2014-03-27 17:33  岳帅超  阅读(212)  评论(0编辑  收藏  举报