遇到的问题:
1. 和cs模式不同,Asp.net读取excel的过程在服务器端(cs模式一般在客户端)所以你读入excel文件的时候,文件要上传在服务器目录下,
在自己电脑上做测试的时候也要在你的目录上加上Server.MapPath("NewsHtml/stu.xls");这样才能确保服务器能读到数据。
2.初次读入excel的时候总是发现某些单元格的数据会是空白,导致这个发生的原因是:excel某一列的数据不是统一格式,是混合模式-----有的单元格是数字,有的是字符串。解决的方式是在oledb连接的字符串中加入IMEX=1,即将混合列的每个单元格都强制作为文本读入。
Code
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Data.OleDb;
public partial class daoru : System.Web.UI.Page
{
private DataSet Ds_excle = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn_daoru_Click(object sender, EventArgs e)
{
try
{
string filename = Server.MapPath("NewsHtml/stu.xls");
//string XlsFileName=FileUpload1.PostedFile.FileName;
//DataSet Ds_excle = new DataSet();
OleDbConnection objConn = new OleDbConnection("Provider=Microsoft.jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=\"Excel 8.0;HDR=NO;IMEX=1\";");
objConn.Open();
string sqlstr = "select * from [sheet1$]";// 是要读入的sheet的名字
OleDbCommand comm = new OleDbCommand(sqlstr, objConn);
OleDbDataAdapter dap = new OleDbDataAdapter(comm);
dap.Fill(Ds_excle,"student");
GridView1.DataSource = Ds_excle;
GridView1.DataBind();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=709813;database=test;");
conn.Open();
string procName = "dbo.execl_database1";
foreach (DataRow dr in Ds_excle.Tables["student"].Rows)
{
SqlParameter[] prams ={new SqlParameter("@StuNum",SqlDbType.VarChar,50),
new SqlParameter("@UserName",SqlDbType.VarChar,50),
new SqlParameter("@PassWord",SqlDbType.VarChar,50),
new SqlParameter("@Major",SqlDbType.VarChar,20),
new SqlParameter("@Address",SqlDbType.VarChar,200),
new SqlParameter("@Tel",SqlDbType.VarChar,20),
};
prams[0].Value = dr[0].ToString();
prams[1].Value = dr[1].ToString();
prams[2].Value = dr[2].ToString();
prams[3].Value = dr[3].ToString();
prams[4].Value = dr[4].ToString();
prams[5].Value = dr[5].ToString();
SqlCommand cmd = DataBase.CreatCmd(procName, prams, conn);
cmd.ExecuteNonQuery();
}
}
}