C#.NET Excel文件数据导入SQL Server数据库完整代码

三个控件:FileUploadButton1Button1点击Button1,Button2将FileUpload选择的Excel文件数据导入\导出数据库... 三个控件:
FileUpload
Button1
Button1

点击Button1,Button2将FileUpload选择的Excel文件数据导入\导出数据库
展开
 我来答
xiangjuan314
推荐于2016-02-04 · TA获得超过3.3万个赞
知道大有可为答主
回答量:2.9万
采纳率:0%
帮助的人:2752万
展开全部

在日常的项目中,Excel,Word,txt等格式的数据导入到数据库中是很常见

这里将分为.net导入Sql Server,Oracle数据库和WinForm导入Sql Server,Oracle数据库。

 

实现的基本思想:

1,先使用FileUpload控件fuload将Excel文件上传到服务器上得某一个文件夹。 

2,使用OleDb将已经上传到服务器上的Excel文件读出来,这里将Excel文件当做一个数据库来读。在联系数据库语句中,Data Source就是该文件在服务器上得物理路径

3,将第二步中读出的数据以DataTable对象返回。

4,遍历DataTable对象,然后到Sql Server数据库中查询,是否存在该条数据。如果存在,可以做更新,或者不做处理;如果不存在,则插入数据。

注意:在遍历DataTable的时候,可是使用dt.Rows[i]["Name"].ToString();Name为Name列的表头,所以Excel中列的顺序就无关紧要了。当然,前提是你知道Excel里列中各表头的名字。如果Excel中列的顺序固定,即可按下面代码中的方式进行。

添加的引用:

 

using System; 
using System.Data; 
using System.Data.OleDb; 
using System.Data.SqlClient; 
using System.IO; 
using System.Text; 
using System.Web; 
using System.Web.UI; 
private DataTable  xsldata() 
        { 
           if(fuload.FileName == "") 
            { 
                lbmsg.Text = "请选择文件"; 
                return null; 
            } 
            string fileExtenSion; 
            fileExtenSion = Path.GetExtension(fuload.FileName); 
            if(fileExtenSion.ToLower() != ".xls" && fileExtenSion.ToLower() != ".xlsx") 
            { 
                lbmsg.Text = "上传的文件格式不正确"; 
                return null; 
            } 
            try 
            { 
                string FileName = "App_Data/" + Path.GetFileName(fuload.FileName); 
                if(File.Exists(Server.MapPath(FileName))) 
                { 
                    File.Delete(Server.MapPath(FileName)); 
                } 
                fuload.SaveAs(Server.MapPath(FileName)); 
                //HDR=Yes,这代表第一行是标题,不做为数据使用 ,如果用HDR=NO,则表示第一行不是标题,做为数据来使用。系统默认的是YES 
                string connstr2003 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'"; 
                string connstr2007 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + Server.MapPath(FileName) + ";Extended Properties=\"Excel 12.0;HDR=YES\""; 
                OleDbConnection conn; 
                if(fileExtenSion.ToLower() == ".xls") 
                { 
                    conn = new OleDbConnection(connstr2003); 
                } 
                else 
                { 
                    conn = new OleDbConnection(connstr2007); 
                } 
                conn.Open(); 
                string sql = "select * from [Sheet1$]"; 
                OleDbCommand cmd = new OleDbCommand(sql, conn); 
                DataTable dt = new DataTable(); 
                OleDbDataReader sdr = cmd.ExecuteReader(); 
 
                dt.Load(sdr); 
                sdr.Close(); 
                conn.Close(); 
                //删除服务器里上传的文件 
                if(File.Exists(Server.MapPath(FileName))) 
                { 
                    File.Delete(Server.MapPath(FileName)); 
                } 
                return dt; 
            } 
            catch(Exception e) 
            { 
                return null; 
            } 
        } 
 
        protected void Btn_Export_Excel_To_DB_Click(object sender, EventArgs e) 
        { 
            try{ 
 
                DataTable dt = xsldata(); 
 
                //dataGridView2.DataSource = ds.Tables[0]; 
                int errorcount = 0;//记录错误信息条数 
                int insertcount = 0;//记录插入成功条数 
 
                int updatecount = 0;//记录更新信息条数 
 
                string strcon = "server=localhost;database=database1;uid=sa;pwd=sa"; 
                SqlConnection conn = new SqlConnection(strcon);//链接数据库 
                conn.Open(); 
 
                for(int i = 0; i < dt.Rows.Count; i++) 
                { 
                    string Name = dt.Rows[i][0].ToString();//dt.Rows[i]["Name"].ToString(); "Name"即为Excel中Name列的表头 
                    string Sex = dt.Rows[i][1].ToString(); 
                    int Age = Convert.ToInt32(dt.Rows[i][2].ToString()); 
                    string Address = dt.Rows[i][3].ToString(); 
                    if(Name != "" && Sex != "" && Age != 0 && Address != "") 
                    { 
                        SqlCommand selectcmd = new SqlCommand("select count(*) from users where Name='" + Name + "' and Sex='" + Sex + "' and Age='" + Age + "' and Address=" + Address, conn); 
                        int count = Convert.ToInt32(selectcmd.ExecuteScalar()); 
                        if(count > 0) 
                        { 
                            updatecount++; 
                        } 
                        else 
                        { 
                            SqlCommand insertcmd = new SqlCommand("insert into users(Name,Sex,Age,Address) values('" + Name + "','" + Sex + "'," + Age + ",'" + Address + "')", conn); 
                            insertcmd.ExecuteNonQuery(); 
                            insertcount++; 
                        } 
                    } 
                    else 
                    { 
                        errorcount++; 
                    } 
                } 
                Response.Write((insertcount + "条数据导入成功!" + updatecount + "条数据重复!" + errorcount + "条数据部分信息为空没有导入!")); 
            } 
            catch(Exception ex) 
            { 
 
            } 
        }
匿名用户
推荐于2018-03-11
展开全部
Excel.Application app = new Excel.Application();
app.Visible = true;
try
{
object obj = System.Reflection.Missing.Value;
Excel.Workbooks wb = app.Workbooks;
Excel._Workbook iwk = wb.Add(obj);
Excel._Worksheet sheet = (Excel._Worksheet)(iwk.ActiveSheet);

app.Caption = "Excle的标题";

//添加列
for (int i = 0; i < this.dataGridView的控件名.Columns.Count; i++)
{
sheet.Cells[1, i + 1] = this.dataGridView的控件名.Columns[i].HeaderText;
}

//添加行
for (int i = 0; i < this.dataGridView的控件名.Rows.Count; i++)
{
for (int j = 0; j < dataGridView的控件名.Columns.Count; j++)
{
sheet.Cells[i + 2, j + 1] = this.dataGridView的控件名.Rows[i].Cells[j].Value.ToString();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
用法:先把Excle.dll 复制在你的项目的bin\Debug文件下:在右击工具箱->选择项(I)... -> 显示"选择工具箱项" -> COM组件 -> 选择Excle就可以了
本回答被网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2013-06-15
展开全部
一.数据库向导本来就可以这样导入,在Excel建的字段,必须在table表中也得有字段.然后在SQL右键点击table表中的导入数据.选择Excel数据类型,就可以了

二:
protected void Button1_Click(object sender, System.EventArgs e)
{
string XLS_Path="";
string XLS_Name = MakeFileName();
string fileExtName = "";
if(File1.PostedFile.ContentLength >0)
{
try
{
fileExtName = File1.PostedFile.FileName.Substring(File1.PostedFile.FileName.LastIndexOf("."));
if(fileExtName!=".xls"||fileExtName.Length<1)
{
Response.Write( "<script language=javascript>alert('数据导入失败.可能是文件格式或路径不正确!!!');</script>");
return;
}
File1.PostedFile.SaveAs(Server.MapPath("../uploadexcel/")+XLS_Name+fileExtName);
XLS_Path =Server.MapPath("../uploadexcel/")+ XLS_Name+fileExtName;
}
catch(Exception ex)
{
Response.Write(ex.ToString());
}
}
else
{
Response.Write( "<script language=javascript>alert('请选择文件后再上传!!!');</script>");
return;
}
string ConStr=System.Configuration.ConfigurationManager.AppSettings["ConnString"];
SqlConnection Conn=new SqlConnection(ConStr);
string mystring="Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = '"+XLS_Path+"'"+";Extended Properties=Excel 8.0";
OleDbConnection cnnxls = new OleDbConnection (mystring);
OleDbDataAdapter myDa =new OleDbDataAdapter("select * from [Sheet1$]",cnnxls);
DataSet myDs =new DataSet();
try
{
myDa.Fill(myDs);
}
catch
{
Response.Write( "<script language=javascript>alert('数据导入失败,请检查!!');</script>");
return;
}
if(myDs.Tables[0].Rows.Count<=0)
{
Response.Write( "<script language=javascript>alert('文件中可能没有数据,请检查后重新导入!');</script>");
return;
}

int []zjid=new int[myDs.Tables[0].Rows.Count];
string strSql = "";
string CnnString="Provider=SQLOLEDB;"+ConStr;
OleDbConnection conn =new OleDbConnection(CnnString);
OleDbCommand myCmd =null;
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
匿名用户
2013-06-15
展开全部
整个数据库?
只是某个表而已吧。
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(2)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式