这是我做的一个在asp.net中,将excel数据导入sql的实例,数据导入时分3种形式:追加导入、覆盖导入、清空导入,希望能对新手有点帮助。
using
System;
using
System.Collections;
using
System.ComponentModel;
using
System.Data;
using
System.Drawing;
using
System.Web;
using
System.Web.SessionState;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.HtmlControls;
using
System.IO;
using
System.Text;
using
System.Configuration;
using
System.Data.SqlClient;
using
System.Data.OleDb;
namespace
GZYYWZ.Adm
{
///<summary>
/// Adm_Score_Upload
的摘要说明。
///</summary>
public class Adm_Score_Upload : System.Web.UI.Page
{
protected System.Web.UI.HtmlControls.HtmlInputFile File_Name;
protected System.Web.UI.HtmlControls.HtmlInputButton Button_Old_Up;
protected System.Web.UI.HtmlControls.HtmlInputRadioButton Radio1;
protected System.Web.UI.HtmlControls.HtmlInputRadioButton Radio2;
protected System.Web.UI.HtmlControls.HtmlInputRadioButton Radio3;
protected OA.Config Conn = new OA.Config();
private void Page_Load(object sender, System.EventArgs e)
{
//
在此处放置用户代码以初始化页面
if(!this.IsPostBack)
{
if(Session["User_Name"] == null || Session["module_authority"] == null || Session["module_authority"].ToString().IndexOf("13",0) < 0)
this.Response.Redirect("Adm_Login.aspx");
}
}
#region
Web
窗体设计器生成的代码
override protected void OnInit(EventArgs e)
{
//
// CODEGEN:
该调用是 ASP.NET Web 窗体设计器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
///<summary>
///
设计器支持所需的方法 - 不要使用代码编辑器修改
///
此方法的内容。
///</summary>
private void InitializeComponent()
{
this.Button_Old_Up.ServerClick += new System.EventHandler(this.Button_Old_Up_ServerClick);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void Button_Old_Up_ServerClick(object sender, System.EventArgs e)
{
string File_Name = this.File_Name.PostedFile.FileName;
int File_Size = this.File_Name.PostedFile.ContentLength;
if (File_Name.Length!=0 && File_Size>0)
{
string File_ExName = File_Name.Substring(File_Name.LastIndexOf(".")+1);//
扩展名
if (File_ExName!="xls")
{
Conn.MessageBox(this,"
不是有效的EXCEL文件!");
return;
}
else
{
//
上传EXCEL文件到ExcelFile目录
DateTime now = DateTime.Now;
string NewName=now.ToShortDateString()+now.Hour.ToString()+now.Minute.ToString()+now.Second.ToString()+"."+File_ExName;
string filePath="../ExcelFile/"+NewName;
this.File_Name.PostedFile.SaveAs(Server.MapPath(@filePath));
//
获取EXCEL文件,执行导入
string excelConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(filePath) + ";Extended Properties=Excel 8.0";
string excelCmdstr=string.Format("select * from [Sheet1$]");
string Error="";
try
{
OleDbConnection oleDbConnection = new OleDbConnection(excelConnect);
oleDbConnection.Open();
OleDbCommand excelCmd=new OleDbCommand(excelCmdstr,oleDbConnection);
OleDbDataAdapter excelDa=new OleDbDataAdapter(excelCmd);
DataTable edt=new DataTable();
excelDa.Fill(edt);
string sql="";
string chk_sql="",chk_code="";
string Input_Date=DateTime.Now.ToString("yyyy-MM-dd");
int i=2;//
电子表格行号,含有表头,所以从2开始
if (this.Radio1.Checked==true)
{
//
追加导入
foreach (DataRow dr in edt.Rows)
{
try
{
string Code=dr[0].ToString().Trim().Replace("'","''");
if (Code.Length>30)
{
Error += "
第"+i+"行0列,字符超长,最大长度为30位<BR>";
}
string Name=dr[1].ToString().Trim().Replace("'","''");
if (Name.Length>20)
{
Error += "
第"+i+"行1列,字符超长,最大长度为20位<BR>";
}
string Sex=dr[2].ToString().Trim().Replace("'","''");
if (Sex.Length>4)
{
Error += "
第"+i+"行2列,字符超长,最大长度为4位<BR>";
}
string Birth=dr[3].ToString().Trim().Replace("'","''");
if (Birth.Length>10)
{
Error += "
第"+i+"行3列,字符超长,最大长度为10位<BR>";
}
string Unit=dr[4].ToString().Trim().Replace("'","''");
if (Unit.Length>50)
{
Error += "
第"+i+"行4列,字符超长,最大长度为50位<BR>";
}
int Test_Year=Convert.ToInt32(dr[5].ToString().Trim().Replace("'","''"));
int Test_Month=Convert.ToInt32(dr[6].ToString().Trim().Replace("'","''"));
decimal Score=Convert.ToDecimal(dr[7].ToString().Trim().Replace("'","''"));
string Grade=dr[8].ToString().Trim().Replace("'","''");
if (Grade.Length>15)
{
Error += "
第"+i+"行8列,字符超长,最大长度为15位<BR>";
}
string Class=dr[9].ToString().Trim().Replace("'","''");
if (Class.Length>15)
{
Error += "
第"+i+"行9列,字符超长,最大长度为15位<BR>";
}
string Content=dr[10].ToString().Trim().Replace("'","''");
if (Code!="" && Code!=null)
{
chk_sql="select count(Code) from Achievement where Code='"+Code+"'";
chk_code=Conn.ExecuteScalar_return_String(chk_sql);
if (chk_code=="" || chk_code=="0")
{
sql += "insert Achievement(Code,Name,Sex,Birth,Unit,Test_Year,Test_Month,Score,Grade,Class,Content,Input_Date) values ('"+Code+"','"+Name+"','"+Sex+"','"+Birth+"','"+Unit+"',"+Test_Year+","+Test_Month+","+Score+",'"+Grade+"','"+Class+"','"+Content+"','"+Input_Date+"');";
}
}
}
catch(Exception e1)
{
Error += "
第"+i+"行:"+e1.Message+"<br>";
throw new ApplicationException(Error);
}
i++;
}
}
else if (this.Radio2.Checked==true)
{
//
覆盖导入
foreach (DataRow dr in edt.Rows)
{
try
{
string Code=dr[0].ToString().Trim().Replace("'","''");
if (Code.Length>30)
{
Error += "
第"+i+"行0列,字符超长,最大长度为30位<BR>";
}
string Name=dr[1].ToString().Trim().Replace("'","''");
if (Name.Length>20)
{
Error += "
第"+i+"行1列,字符超长,最大长度为20位<BR>";
}
string Sex=dr[2].ToString().Trim().Replace("'","''");
if (Sex.Length>4)
{
Error += "
第"+i+"行2列,字符超长,最大长度为4位<BR>";
}
string Birth=dr[3].ToString().Trim().Replace("'","''");
if (Birth.Length>10)
{
Error += "
第"+i+"行3列,字符超长,最大长度为10位<BR>";
}
string Unit=dr[4].ToString().Trim().Replace("'","''");
if (Unit.Length>50)
{
Error += "
第"+i+"行4列,字符超长,最大长度为50位<BR>";
}
int Test_Year=Convert.ToInt32(dr[5].ToString().Trim().Replace("'","''"));
int Test_Month=Convert.ToInt32(dr[6].ToString().Trim().Replace("'","''"));
decimal Score=Convert.ToDecimal(dr[7].ToString().Trim().Replace("'","''"));
string Grade=dr[8].ToString().Trim().Replace("'","''");
if (Grade.Length>15)
{
Error += "
第"+i+"行8列,字符超长,最大长度为15位<BR>";
}
string Class=dr[9].ToString().Trim().Replace("'","''");
if (Class.Length>15)
{
Error += "
第"+i+"行9列,字符超长,最大长度为15位<BR>";
}
string Content=dr[10].ToString().Trim().Replace("'","''");
if (Code!="" && Code!=null)
{
chk_sql="select count(Code) from Achievement where Code='"+Code+"'";
chk_code=Conn.ExecuteScalar_return_String(chk_sql);
if (chk_code=="" || chk_code=="0")
{
sql += "insert Achievement(Code,Name,Sex,Birth,Unit,Test_Year,Test_Month,Score,Grade,Class,Content,Input_Date) values ('"+Code+"','"+Name+"','"+Sex+"','"+Birth+"','"+Unit+"',"+Test_Year+","+Test_Month+","+Score+",'"+Grade+"','"+Class+"','"+Content+"','"+Input_Date+"');";
}
else
{
sql += "update Achievement set Code='"+Code+"',Name='"+Name+"',Sex='"+Sex+"',Birth='"+Birth+"',Unit='"+Unit+"',Test_Year="+Test_Year+",Test_Month="+Test_Month+",Score="+Score+",Grade='"+Grade+"',Class='"+Class+"',Content='"+Content+"',Input_Date='"+Input_Date+"' where Code='"+Code+"';";
}
}
}
catch(Exception e1)
{
Error += "
第"+i+"行:"+e1.Message+"<br>";
throw new ApplicationException(Error);
}
i++;
}
}
else if (this.Radio3.Checked==true)
{
//
清空导入
string del_sql="delete from Achievement";
Conn.ExecuteNonQuery_Sql(del_sql);//
删除数据库中所有记录
foreach (DataRow dr in edt.Rows)
{
try
{
string Code=dr[0].ToString().Trim().Replace("'","''");
if (Code.Length>30)
{
Error += "
第"+i+"行0列,字符超长,最大长度为30位<BR>";
}
string Name=dr[1].ToString().Trim().Replace("'","''");
if (Name.Length>20)
{
Error += "
第"+i+"行1列,字符超长,最大长度为20位<BR>";
}
string Sex=dr[2].ToString().Trim().Replace("'","''");
if (Sex.Length>4)
{
Error += "
第"+i+"行2列,字符超长,最大长度为4位<BR>";
}
string Birth=dr[3].ToString().Trim().Replace("'","''");
if (Birth.Length>10)
{
Error += "
第"+i+"行3列,字符超长,最大长度为10位<BR>";
}
string Unit=dr[4].ToString().Trim().Replace("'","''");
if (Unit.Length>50)
{
Error += "
第"+i+"行4列,字符超长,最大长度为50位<BR>";
}
int Test_Year=Convert.ToInt32(dr[5].ToString().Trim().Replace("'","''"));
int Test_Month=Convert.ToInt32(dr[6].ToString().Trim().Replace("'","''"));
decimal Score=Convert.ToDecimal(dr[7].ToString().Trim().Replace("'","''"));
string Grade=dr[8].ToString().Trim().Replace("'","''");
if (Grade.Length>15)
{
Error += "
第"+i+"行8列,字符超长,最大长度为15位<BR>";
}
string Class=dr[9].ToString().Trim().Replace("'","''");
if (Class.Length>15)
{
Error += "
第"+i+"行9列,字符超长,最大长度为15位<BR>";
}
string Content=dr[10].ToString().Trim().Replace("'","''");
if (Code!="" && Code!=null)
{
sql += "insert Achievement(Code,Name,Sex,Birth,Unit,Test_Year,Test_Month,Score,Grade,Class,Content,Input_Date) values ('"+Code+"','"+Name+"','"+Sex+"','"+Birth+"','"+Unit+"',"+Test_Year+","+Test_Month+","+Score+",'"+Grade+"','"+Class+"','"+Content+"','"+Input_Date+"');";
}
}
catch(Exception e1)
{
Error += "
第"+i+"行:"+e1.Message+"<br>";
throw new ApplicationException(Error);
}
i++;
}
}
else
{
Conn.MessageBox(this,"
请选择导入方式!");
return;
}
//
删除临时的EXCEL文件
oleDbConnection.Close();
if (System.IO.File.Exists(Server.MapPath(filePath)))
{
File.Delete(Server.MapPath(filePath));
}
if (sql!="" && sql!=null)
{
Conn.ExecuteNonQuery_Sql(sql);
Conn.MessageBox_alert_refurbish(this,"
导入成功!");
}
else
{
Conn.MessageBox_alert_refurbish(this,"
没有符合条件的数据或数据为空!");
return;
}
}
catch(Exception ex)
{
//Response.Write(Error);
Response.Write("<BR>");
Response.Write(ex.Message);
// return;
}
//
导入结束
}
}
else
{
Conn.MessageBox(this,"
你没有选择文件或文件不存在!");
return;
}
}
/// <summary>
///
将Excel中的数据读入DataSet
/// </summary>
/// <param name="fileName">
文件路径和文件名
</param>
/// <returns>DataSet</returns>
private DataSet ReadExcel(string fileName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" +"Data Source="+ fileName +";"+"Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
string strExcel = "";
OleDbDataAdapter myCommand = null;
strExcel="select * from [sheet1$]";//
从默认的sheet1表中读入数据
myCommand = new OleDbDataAdapter(strExcel, strConn);
DataSet ds = new DataSet();
myCommand.Fill(ds,"Data");
conn.Close();
return ds;
}
}
}