当前位置:首页 » 操作系统 » excel导入数据库net

excel导入数据库net

发布时间: 2022-02-16 07:08:31

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

在日常的项目中,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中列的顺序固定,即可按下面代码中的方式进行。

添加的引用:

usingSystem;
usingSystem.Data;
usingSystem.Data.OleDb;
usingSystem.Data.SqlClient;
usingSystem.IO;
usingSystem.Text;
usingSystem.Web;
usingSystem.Web.UI;
privateDataTablexsldata()
{
if(fuload.FileName=="")
{
lbmsg.Text="请选择文件";
returnnull;
}
stringfileExtenSion;
fileExtenSion=Path.GetExtension(fuload.FileName);
if(fileExtenSion.ToLower()!=".xls"&&fileExtenSion.ToLower()!=".xlsx")
{
lbmsg.Text="上传的文件格式不正确";
returnnull;
}
try
{
stringFileName="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
stringconnstr2003="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+Server.MapPath(FileName)+";ExtendedProperties='Excel8.0;HDR=Yes;IMEX=1;'";
stringconnstr2007="Provider=Microsoft.ACE.OLEDB.12.0;DataSource="+Server.MapPath(FileName)+";ExtendedProperties="Excel12.0;HDR=YES"";
OleDbConnectionconn;
if(fileExtenSion.ToLower()==".xls")
{
conn=newOleDbConnection(connstr2003);
}
else
{
conn=newOleDbConnection(connstr2007);
}
conn.Open();
stringsql="select*from[Sheet1$]";
OleDbCommandcmd=newOleDbCommand(sql,conn);
DataTabledt=newDataTable();
OleDbDataReadersdr=cmd.ExecuteReader();

dt.Load(sdr);
sdr.Close();
conn.Close();
//删除服务器里上传的文件
if(File.Exists(Server.MapPath(FileName)))
{
File.Delete(Server.MapPath(FileName));
}
returndt;
}
catch(Exceptione)
{
returnnull;
}
}

protectedvoidBtn_Export_Excel_To_DB_Click(objectsender,EventArgse)
{
try{

DataTabledt=xsldata();

//dataGridView2.DataSource=ds.Tables[0];
interrorcount=0;//记录错误信息条数
intinsertcount=0;//记录插入成功条数

intupdatecount=0;//记录更新信息条数

stringstrcon="server=localhost;database=database1;uid=sa;pwd=sa";
SqlConnectionconn=newSqlConnection(strcon);//链接数据库
conn.Open();

for(inti=0;i<dt.Rows.Count;i++)
{
stringName=dt.Rows[i][0].ToString();//dt.Rows[i]["Name"].ToString();"Name"即为Excel中Name列的表头
stringSex=dt.Rows[i][1].ToString();
intAge=Convert.ToInt32(dt.Rows[i][2].ToString());
stringAddress=dt.Rows[i][3].ToString();
if(Name!=""&&Sex!=""&&Age!=0&&Address!="")
{
SqlCommandselectcmd=newSqlCommand("selectcount(*)fromuserswhereName='"+Name+"'andSex='"+Sex+"'andAge='"+Age+"'andAddress="+Address,conn);
intcount=Convert.ToInt32(selectcmd.ExecuteScalar());
if(count>0)
{
updatecount++;
}
else
{
SqlCommandinsertcmd=newSqlCommand("insertintousers(Name,Sex,Age,Address)values('"+Name+"','"+Sex+"',"+Age+",'"+Address+"')",conn);
insertcmd.ExecuteNonQuery();
insertcount++;
}
}
else
{
errorcount++;
}
}
Response.Write((insertcount+"条数据导入成功!"+updatecount+"条数据重复!"+errorcount+"条数据部分信息为空没有导入!"));
}
catch(Exceptionex)
{

}
}

⑵ ASP.NET中如何将Excel表中的数据导入到数据库中

ASP.NET中将Excel表中的数据导入到数据库中的方法是利用可视化界面工具直接选择字段映射导入。
1)接受数据导入的表已经存在。
insert into t1 select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0' ,
'Excel 5.0;HDR=YES;DATABASE=c:\\test.xls',sheet1$);
2)导入数据并生成表。
select * into t1 from OPENROWSET('MICROSOFT.JET.OLEDB.4.0',
'Excel 5.0;HDR=YES;DATABASE=c:\\test.xls',sheet1$);

3) 导入Excel中指定的列到数据库表中指定的列。
INSERT INTO t1(a1,a2,a3) SELECT a1,a2,a3 FROM OPENROWSET'MICROSOFT.JET.OLEDB.4.0' ,'Excel5.0; HDR=YES; DATABASE=c:\\test.xls',sheet1$);
需要注意的地方。
1)外围应用配置器的设置。
从“功能外围应用配置器”中选择“启动 OPENROWSET 和 OPENDATASOURCE 支持”选项。
2)关闭Excel表。
如果在导入时要导入的Excel表格处于打开状态,会提示:
“无法初始化链接服务器 "(null)" 的 OLE DB 访问接口 "microsoft.jet.oledb.4.0" 的数据源对象。”
3)导入数据时,Excel的首行会作为表头,若导入到已存在的数据库表,则忽略首行。

⑶ 请教.net高手 有关Excel导入sql数据库的问题(c#)(急用)

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;

⑷ APS.NET怎样把EXCEL导入到数据库

public static void DataTableToDB()
{
string _strExcelFileName = @"D:\example.xls";
DataTable dtExcel = ExcelToDataTable(_strExcelFileName,"Sheet1");
//这个dtExcel 里头就是excel的数据 excel中的第一行默认为表名

}

二、把Excel数据读入DataTable
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" +"Extended Properties=Excel 5.0;";
string strExcel = string.Format("select * from [{0}$]", strSheetName);
DataSet ds = new DataSet();

using (OleDbConnection conn = new OleDbConnection(strConn))
{
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName);
conn.Close();
}

return ds.Tables[strSheetName];
}

⑸ excel中多个sheet怎么导入sql数据库 .net

Try
Dim xlsConn As String, xlscmd As String, SourcePath As String = Server.MapPath & "~/Excel1.xls"
Dim ExcelConnection As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & SourcePath & "'; Extended Properties=""Excel 12.0 Xml; HDR=Yes""")

xlsConn = ExcelConnection.ConnectionString

Using connection As New OleDbConnection(xlsConn)
connection.Open() : ExcelConnection.Open()
Dim SheetName As String = "Sheet2"

xlscmd = "SELECT [columnA] FROM [" & SheetName & "$]"

Dim command As New OleDbCommand(xlscmd, connection)

' Create DbDataReader to Data Worksheet
Using dr As OleDbDataReader = command.ExecuteReader()

Dim cmd As String = "truncate table " & tableName
SqlCmd = New OleDbCommand(cmd, SqlConn)
SqlCmd.ExecuteNonQuery()

' Bulk Copy to SQL Server
Dim sqlConnectionString As String
sqlConnectionString = "Data Source=" & .SqlConn.DataSource & ";Initial Catalog=" & SqlConn.Database & ";Persist Security Info=True;User ID=sa;Password="

Using bulkCopy As New SqlBulkCopy(sqlConnectionString)
bulkCopy.DestinationTableName = "tableName"
bulkCopy.WriteToServer(dr)
Return True
End Using
End Using
End Using

Catch ex As Exception
Return False
End Try

大致是这样。。。

⑹ 如何实现asp.net中将Excel导入数据库多个表中

用OLEDB进行Excel文件数据读取并返DataSet数据集其几点需要注意:

1.连接字符串参数IMEX 值:
0 is Export mode
1 is Import mode
2 is Linked mode (full update capabilities)
IMEX3值:IMEX=2 EXCEL文档同含字符型数字型比第C列3值2数值型 1231字符型 ABC导入
页面报错库显示数值型123字符型ABC则呈现空值IMEX=1述情况发库确呈现 123 ABC.
2.参数HDR值:
HDR=Yes代表第行标题做数据使用 用HDR=NO则表示第行标题做数据使用系统默认YES
3.参数Excel 8.0
于Excel 97版本都用Excel 8.0

#region获取exceldataset,即名excel_ds
stringexcelFilePath=openFileDialog1.FileName;//弹文件选取窗口获取EXCEL文件路径
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+excelFilePath+";ExtendedProperties="Excel8.0;HDR=YES;IMEX=1"";
OleDbConnectionOleconn=newOleDbConnection(strConn);
stringstrExcel="";
OleDbDataAdapterexcelCommand=null;
DataSetexcel_ds=newDataSet();
strExcel="select*from[sheet1$]";
try
{
Oleconn.Open();
excelCommand=newOleDbDataAdapter(strExcel,Oleconn);
excelCommand.Fill(excel_ds,"exdtSource");//dataset
}
catch(System.Exceptionex)
{
MessageBox.Show("导入错:"+ex,"错误信息");
}
finally
{
Oleconn.Close();
Oleconn.Dispose();
}
#endregion

⑺ c#.net从excel表导入数据到网页而达到快速增加数据库行的操作

这样的问题很多了
你需要一个放一个fileupload控件 用来上传excel ,还需要在项目里建一个文件夹用来存放你要上传的excel 。因为系统总是先把文件传到服务器上再进行操作,而不是对每个人的桌面excel直接操作。
using System.Data.SqlClient;
using System.Data.OleDb; // 要加这两句
public DataSet ExecleDs(string filenameurl, string table) // 这个函数就是将上传的excel读入dataset
{
string strConn = "Provider=Microsoft.Jet.OleDb.4.0;" + "data source=" + filenameurl + ";Extended Properties='Excel 8.0; HDR=YES; IMEX=1'"; // 这里excel03 如要该成07版再问我或者网络
string strcom = "select *from [Sheet1$]";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
DataSet ds = new DataSet();
OleDbDataAdapter odda = new OleDbDataAdapter(strcom, conn);
odda.Fill(ds, table);
return ds;

}

protected void Button4_Click(object sender, EventArgs e) // 你的那个确定按钮
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server='CWJMXT-14\\SQLEXPRESS';database='E-test';uid='sa';pwd=‘..'" ; // 你自己的数据库连接
if (FileUpload1.HasFile == false)//HasFile用来检查FileUpload是否有指定文件
{
Response.Write("<script>alert('请您选择Excel文件')</script> ");
return;//当无文件时,返回
}
string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
if (IsXls != ".xls")
{
Response.Write("<script>alert('只可以选择Excel文件')</script>");
return;//当选择的不是Excel文件时,返回
}

con.Open();
string filename = FileUpload1.FileName; //获取Execle文件名 DateTime日期函数
// Label2.Text = filename;
string savePath = Server.MapPath(("~\\upfiles\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
FileUpload1.SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
DataSet ds = ExecleDs(savePath, filename); //调用自定义方法
DataRow[] dr = ds.Tables[0].Select(); //定义一个DataRow数组
int rowsnum = ds.Tables[0].Rows.Count;
if (rowsnum == 0)
{
Response.Write("<script>alert('Excel表为空表,无数据!')</script>"); //当Excel表为空时,对用户进行提示
}
else
{
for (int i = 0; i < dr.Length; i++)
{
//string pininputdate = dr[i]["].ToString();//日期 excel列名【名称不能变,否则就会出错】

string insertstr = "insert into item1(试题组别,试题类型,试题题目,选项A,选项B,选项C,选项D,正确答案,随机或必出)values('" + dr[i][0].ToString() + "','" + dr[i][1].ToString() + "','" + dr[i][2].ToString() + "','" + dr[i][3].ToString() + "','" + dr[i][4].ToString() + "','" + dr[i][5].ToString() + "','" + dr[i][6].ToString() + "','" + dr[i][7].ToString() + "','" + dr[i][8].ToString() + "')"; //这里就是具体怎么样一行一行将dataset中的数据导入sql的 你也可以加一些其他判断什么的。 SqlCommand cmd = new SqlCommand(insertstr, con);
try
{
cmd.ExecuteNonQuery();
}
catch (MembershipCreateUserException ex) //捕捉异常
{
Response.Write("<script>alert('导入内容:" + ex.Message + "')</script>");
}

}
Response.Write("<script>alert('Excle表导入成功!');location='itemmaintain.aspx'</script>");
}
con.Close();
}

⑻ 怎样将EXCEL表格数据通过C#.NET导入到SQL数据库中

你完全可以把Excel当数据表一样读出来,然后再写进Sql
读Excel的方法:
string strConn = "provider=Microsoft.Jet.OLEDB.4.0;data source=Excel文件;Extended Properties=Excel 8.0;";

OleDbConnection oleConn = new OleDbConnection(strConn);
oleConn.Open();
string olestr = "select * from [Sheet1$]";
OleDbCommand oleComm = new OleDbCommand(olestr, oleConn);
oleComm.Connection = oleConn;
OleDbDataAdapter oleDa = new OleDbDataAdapter();
oleDa.SelectCommand = oleComm;
DataSet ds = new DataSet();
oleDa.Fill(ds);
foreach (DataRow row in ds.Tables["INFO"].Rows)
{
string userInfo = row[0].ToString().Trim();
}
oleConn.Close();

⑼ ASP.NET项目把Excel表中数据导入到数据库!我用的是实体框架(Entity Framework)

用NPOI操作excel就很简单,调用他的接口就可以。

⑽ 如何数据库内容导入excel表格(C#/ASP.NET)

使用一些数据库查询工具,比如 pl/sql 或者 tode,都自带数据导出为excel文件的功能

热点内容
python3默认安装路径 发布:2024-09-19 08:50:22 浏览:514
环卫视频拍摄脚本 发布:2024-09-19 08:35:44 浏览:416
sqlserveronlinux 发布:2024-09-19 08:16:54 浏览:255
编程常数 发布:2024-09-19 08:06:36 浏览:951
甘肃高性能边缘计算服务器云空间 发布:2024-09-19 08:06:26 浏览:161
win7家庭版ftp 发布:2024-09-19 07:59:06 浏览:716
数据库的优化都有哪些方法 发布:2024-09-19 07:44:43 浏览:268
知乎华为编译器有用吗 发布:2024-09-19 07:32:20 浏览:617
访问虚拟机磁盘 发布:2024-09-19 07:28:13 浏览:668
原地工作算法 发布:2024-09-19 07:28:07 浏览:423