asp.net中Excel導入SQL
這是我做的一個在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;
}
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.