c导入excel数据到数据库
⑴ 如何将excel表导入数据库的方法
首先我们肯定有一个excel的文件,文件中有大量的数据,每一列代表着不同的字段。
我们首先建立一个数据库,然后在库中建立表,表的每个字段对应excel中的每一列。
?
一、假如excel中有四列数据,希望导入到数据库中
mytable
中,对应的字段分别为field1,field2,field3,field4.
二、在excel表格中增加一列(?excel应该是e列),利用excel的公式自动生成sql语句(这个很重要,别写错了),具体方法
如下?:
1、增加一列(excel应该是e列,因为我们原有4列数据,分别为a\b\c\d列)
2、在第一行(这一行必须为有效数据行否则出错)的e列,就是e1中输入公式=concatenate("insert
into
table
(field1,field2,field3,field4)
values
('",a1,"','",b1,"','",c1,"','",d1,"');")
3、此时e1已经生成如下的sql语句:
insert
into
mytable
(field1,field2,field3、field4)
values
('a1中
的数据','b1','c1','d1');
4、将e1的公式复制到所有行的e列,(就是用鼠标点住e1单元格的右下角,一直拖拽下去,到最后一行数据)
5、此时e列已经生成了所有的sql语句
6、选中e列把e列数据复制到一个纯文本文件中,命名为
例如:excel.txt
三、把excel.txt
放到数据库中运行即可,可通过命令行导入
source
f:\excel.txt
⑵ 将excel表导入数据库的方法步骤
在 Excel 中录入好数据以后,可能会有导入数据库的需求,这个时候就需要利用一些技巧导入。接下来是我为大家带来的如何将excel表导入数据库的 方法 ,希望对你有用。
将excel表导入数据库的方法Excel导入数据库步骤1:对于把大量数据存放到数据库中,最好是用图形化数据库管理工具,可是如果没有了工具,只能执行命令的话这会是很费时间的事。那我们只能对数据进行组合,把数据组成insert语句然后在命令行中批量直行即可。
Excel导入数据库步骤2:我们对下面数据进行组合,这用到excel中的一个功能。
在excel中有个fx的输入框,在这里把组好的字符串填上去就好了。
注:字符串1 & A2 &字符串2 & ...
A2可以直接输入,也可以用鼠标点对应的单元格。
Excel导入数据库步骤3:每个字符串之间用 & 符号进行连接。下面是第一条连接字符串
="insert into tavern values('"&A2&"','"&B2&"','"&C2&"','"&D2&"');"
写好后按回车键Enter就能组合出对应的字符串了。
insert into tavern values('jw_agi','曙光','0','1');
Excel导入数据库步骤4:组好第一行的字符串后,把鼠标放到单元格右下方,出现加粗的十字,单击按下(别松开),一直往下拉,直到最后一行再放开就行了。
5这样我们就把insert语句都整理好了,接下来就是大家把这些语句批量执行就可以了。
>>>下一页更多精彩“将EXCEL表格数据导入进CAD中的方法”⑶ C#Excel导入多条数据到数据库,如何快速导入
public static DataSet GetDataSet(string FilePath)
{
string OledbConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + FilePath + "';Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'");
OleDbConnection conn = new OleDbConnection(OledbConnectionString);
ArrayList SheetNameList = new ArrayList();
try
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
DataTable dtExcelSchema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
string SheetName = "";
for (int i = 0; i < dtExcelSchema.Rows.Count; i++)
{
SheetName = dtExcelSchema.Rows[i]["TABLE_NAME"].ToString();
SheetNameList.Add(SheetName);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
DataSet dsExcel = new DataSet(); try
{
string strSql = ""; for (int i = 0; i < SheetNameList.Count; i++)
{
strSql = "select * from [" + (string)SheetNameList[i] + "]";
OleDbDataAdapter oleExcelDataAdapter = new OleDbDataAdapter(strSql, conn);
DataTable dtExcel = new DataTable((string)SheetNameList[i]);
oleExcelDataAdapter.Fill(dtExcel);
dsExcel.Tables.Add(dtExcel);
}
return dsExcel;
}
catch (Exception ex)
{
throw ex;
}
}这个方法就是从EXCEL文件读取数据转换为DataSet 下面一段时调用的时候要注意的,写要在服务器端保存一下上传的EXCEL,然后再调用 string filePath = "";
DataSet ds = new DataSet();
if (System.IO.Path.GetExtension(FileUpload1.FileName) != ".xls")
{
ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>alter('hao')</script>");
return;
}
else
{
filePath = "D:\" + FileUpload1.FileName;
FileUpload1.SaveAs(filePath);
string fileName = FileUpload1.FileName;
int start = fileName.IndexOf('.');
fileName = fileName.Substring(0, start);
ds = GetDataSet(filePath);
}
⑷ C# 如何将EXCEL插入到数据库
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Data;
usingSystem.Collections;
usingSystem.Windows.Forms;
usingSystem.Data.OleDb;
usingSystem.Data.Common;
usingSystem.Data.SqlClient;
publicpartialclassExcel导入_Default:System.Web.UI.Page
{
privatestaticstringfilename;
privatestaticstringsavePath;
privatestaticDataSetds;//要插入的数据
privatestaticDataTabledt;
protectedvoidPage_Load(objectsender,EventArgse)
{
}
//上传文件到指定的服务器
protectedvoidButton1_Click1(objectsender,EventArgse)
{
filename=this.fileUploadExcel.FileName;
//savePath必须包含表名在内的所有路径名
savePath=@"G:项目组文件项目.net学习资料工程HealthExcel导入Files"+this.fileUploadExcel.FileName;//上传服务器文件的存储,存在当前新建的文件夹
this.fileUploadExcel.SaveAs(savePath);
Booleanjudge_excel=Judge_Excel();
if(!judge_excel)
{
MessageBox.Show("上传的不是excel文件","标题",MessageBoxButtons.OKCancel,MessageBoxIcon.Error);
return;
}
else
MessageBox.Show("上传文件成功","标题",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
//测试,将excel中的sheet1导入到sqlserver中
//stringconnString="server=localhost;uid=sa;pwd=sqlgis;database=master";
//System.Windows.Forms.OpenFileDialogfd=newOpenFileDialog();
//if(fd.ShowDialog()==DialogResult.OK)
//{
////TransferData(fd.FileName,"sheet1",connString);
//}
}
//判断文件是否是excel文件函数
protectedBooleanJudge_Excel()
{
stringfileExtend=System.IO.Path.GetExtension(this.fileUploadExcel.FileName);
if(fileExtend==".xlsx"||fileExtend==".xls")
returntrue;
else
returnfalse;
}
//获取excel数据按钮的触发,
protectedvoidButton2_Click(objectsender,EventArgse)
{
ExcelToDataSet();
MessageBox.Show("获取数据成功","标题",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);
}
//从excel表中获取数据的函数
publicvoidExcelToDataSet()
{
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+savePath+";ExtendedProperties="Excel8.0;HDR=Yes;IMEX=1"";
OleDbConnectionconn=newOleDbConnection(strConn);//连接excel
if(conn.State.ToString()=="Open")
{
conn.Close();
}
conn.Open();//外部表不是预期格式,不兼容2010的excel表结构
strings=conn.State.ToString();
OleDbDataAdaptermyCommand=null;
ds=null;
/*DataTableyTable=conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,newObject[]{null,null,null,"TABLE"});//获取表的框架,几行几列
stringtableName=yTable.Rows[0]["filename"].ToString();//表示的是几行几列
stringstrSel="select*from["+filename+"]";//xls*/
stringstrExcel="select*from[sheet1$]";//如果有多个sheet表时可以选择是第几张sheet表
myCommand=newOleDbDataAdapter(strExcel,conn);//用strExcel初始化myCommand,查看myCommand里面的表的数据??
ds=newDataSet();
myCommand.Fill(ds);//把表中的数据存放在ds(dataSet)
conn.Close();
try
{
dt=ds.Tables[0];
this.dataGridView1.DataSource=dt;
}
catch(Exceptionerr)
{
MessageBox.Show("操作失败!"+err.ToString());
}
}
//excel导入数据库sql的按钮触发
protectedvoidButton3_Click(objectsender,EventArgse)
{
//stringpath=@"D:数据库SQLServerMSSQL10_50.MSSQLSERVERMSSQLDATATest.mdf";
stringconnString="server=localhost;uid=sa;pwd=1234;database=Test";//连接数据库的路径方法
//StringconnString=@"server=localhost;uid=sa;pwd=1234;database=D:数据库SQLServerMSSQL10_50.MSSQLSERVERMSSQLDATATest.mdf";
SqlConnectionconn=newSqlConnection(connString);
conn.Open();
DataRowdr=null;
intC_Count=dt.Columns.Count;//获取列数
for(inti=0;i<dt.Rows.Count;i++)//记录表中的行数,循环插入
{
dr=dt.Rows[i];
insertToSql(dr,C_Count,conn);
}
conn.Close();
if(dataGridView1.Rows.Count>0)//把数据库表中的数据显示到表中,可判断有没有数据
{
MessageBox.Show("导入成功!");
}
else
{
MessageBox.Show("没有数据!");
}
}
//使用bcp,不容易出错而且效率高
/*try
{
using(System.Data.SqlClient.SqlBulkCopybcp=newSystem.Data.SqlClient.SqlBulkCopy(connString))
{
bcp.SqlRowsCopied+=newSystem.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize=100;//每次传输的行数
bcp.NotifyAfter=100;//进度提示的行数
bcp.DestinationTableName=savePath;//目标表
bcp.WriteToServer(ds.Tables[0]);
}
}
catch
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}*/
//插入数据库的函数
protectedvoidinsertToSql(DataRowdr,intcolumn_count,SqlConnectionconn)
{
//excel表中的列名和数据库中的列名一定要对应
stringname=dr[0].ToString();//需要把内个列都列出来
stringage=dr[1].ToString();
stringsex=dr[2].ToString();
//当数据库中有多个表时,怎么分辨插入的表
stringsql="insertinto客户values('"+name+"','"+age+"','"+sex+"')";
SqlCommandcmd=newSqlCommand(sql,conn);
cmd.ExecuteNonQuery();
}
//从excel表中获取数据并存在
//protectedvoidImportFromExcel()
//{
//stringexecelConnectionStr=@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=filename;
//ExtendedProperties=""Excel8.0;HDR=YES;IMEX=1""";//表第一行是标题,不做为数据使用,Excel档案只能用来做“读取”用途。
//ds=newDataSet();
//stringconnString="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="
//+savePath+";ExtendedProperties="Excel8.0;HDR=Yes;IMEX=1"";
//DataTabletable=OleDbHelper.GetExcelTables(connString);
//if(table==null||table.Rows.Count<=0)
//{
//return;
//}
//foreach(DataRowdrintable.Rows)
//{
//stringcmdText="select*from["+dr["TABLE_NAME"].ToString()+"]";
//DataTabledt=OleDbHelper.FillDataTable(connString,cmdText);
//dt.TableName=dr["TABLE_NAME"].ToString();
//ds.Tables.Add(dt);
//}
//}
}
⑸ C#把Excel 导入到数据库
方式一:实现在c#中可高效的将excel数据导入到sqlserver数据库中,很多人通过循环来
拼接sql,这样做不但容易出错而且效率低下,最好的办法是使用bcp,也就是
System.Data.SqlClient.SqlBulkCopy类来实现。
usingSystem;
usingSystem.Data;
usingSystem.Windows.Forms;usingSystem.Data.OleDb;
namespaceWindowsApplication2{
publicpartialclassForm1:Form{
publicForm1(){
InitializeComponent();}
privatevoidbutton1_Click(objectsender,EventArgse){
//测试,将excel中的sheet1导入到sqlserver中stringconnString="server=localhost;uid=sa;pwd=sqlgis;database=master";
System.Windows.Forms.OpenFileDialogfd=newOpenFileDialog();if(fd.ShowDialog()==DialogResult.OK){
TransferData(fd.FileName,"sheet1",connString);}}
publicvoidTransferData(stringexcelFile,stringsheetName,stringconnectionString){
DataSetds=newDataSet();try{
//获取全部数据
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+excelFile+";"+"ExtendedProperties=Excel8.0;";
OleDbConnectionconn=newOleDbConnection(strConn);conn.Open();
stringstrExcel="";
OleDbDataAdaptermyCommand=null;
strExcel=string.Format("select*from[{0}$]",sheetName);myCommand=newOleDbDataAdapter(strExcel,strConn);
myCommand.Fill(ds,sheetName);
//如果目标表不存在则创建excel文件的第一行为列标题,从第二行开始全部都是数据记录
stringstrSql=string.Format("ifobject_id('{0}')isnullcreatetable{0}(",sheetName);//以sheetName为表名
foreach(System.Data.DataColumncinds.Tables[0].Columns){strSql+=string.Format("[{0}]varchar(255),",c.ColumnName);}
strSql=strSql.Trim(',')+")";
using(System.Data.SqlClient.SqlConnectionsqlconn=newSystem.Data.SqlClient.SqlConnection(connectionString)){
sqlconn.Open();System.Data.SqlClient.SqlCommandcommand=sqlconn.CreateCommand();
command.CommandText=strSql;command.ExecuteNonQuery();sqlconn.Close();}
//用bcp导入数据
//excel文件中列的顺序必须和数据表的列顺序一致,因为数据导入时,是从excel文件的第二行数据开始,不管数据表的结构是什么样的,反正就是第一列的数据会插入到数据表的第一列字段中,第二列的数据插入到数据表的第二列字段中,以此类推,它本身不会去判断要插入的数据是对应数据表中哪一个字段的
using(System.Data.SqlClient.SqlBulkCopybcp=newSystem.Data.SqlClient.SqlBulkCopy(connectionString)){bcp.SqlRowsCopied+=newSystem.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);bcp.BatchSize=100;//每次传输的行数bcp.NotifyAfter=100;//进度提示的行数
bcp.DestinationTableName=sheetName;//目标表bcp.WriteToServer(ds.Tables[0]);}}
catch(Exceptionex){
System.Windows.Forms.MessageBox.Show(ex.Message);}}
//进度显示
voidbcp_SqlRowsCopied(objectsender,
System.Data.SqlClient.SqlRowsCopiedEventArgse){
this.Text=e.RowsCopied.ToString();this.Update();}}}
C# Excel导入数据库(二) 方式二:
本文先将Excel文件转换成DataTable,然后再循环将记录插入到数据库表中,这种方式可以任由程序员来选择将哪列数据导入到数据表的哪个字段中 DataTable table =new DataTable();
//数据绑定到datagridview1
privatevoidbutton1_Click(objectsender,EventArgse){
System.Windows.Forms.OpenFileDialogfd=newOpenFileDialog();if(fd.ShowDialog()==DialogResult.OK){
stringfileName=fd.FileName;bind(fileName);}}
privatevoidbind(stringfileName){
stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+fileName+";"+
"ExtendedProperties='Excel8.0;HDR=Yes;IMEX=1'";OleDbDataAdapterda=newOleDbDataAdapter("SELECT*FROM[Sheet1$]",strConn);
DataSetds=newDataSet();try{
da.Fill(ds);
dt=ds.Tables[0];
this.dataGridView1.DataSource=dt;}
catch(Exceptionerr){
MessageBox.Show("操作失败!"+err.ToString());}}
//将Datagridview1的记录插入到数据库
privatevoidbutton2_Click(objectsender,EventArgse){if(dataGridView1.Rows.Count>0){
DataRowdr=null;
for(inti=0;i<dt.Rows.Count;i++){dr=dt.Rows[i];insertToSql(dr);}
MessageBox.Show("导入成功!");}
else{
MessageBox.Show("没有数据!");}}
privatevoidinsertToSql(DataRowdr){stringname=dr["姓名"].ToString();stringage=dr["年龄"].ToString();
stringsql="insertintosheet1values('"+name+"','','"+age+"')";SqlConnectionconn=newSqlConnection();SqlCommandcmd=newSqlCommand(sql,conn);conn.Open();
cmd.ExecuteNonQuery();conn.Close();
}
⑹ 如何将excel中的数据导入到数据库
1)打开你的sql server,找到要导入数据的数据库,右键——〉任务——〉导入数据
⑺ 如何导入excel并存入数据库
1.使用php
Excel
Parser
Pro软件,但是这个软件为收费软件;
2.可将EXCEL表保存为CSV格式,然后通过phpmyadmin或者SQLyog导入,SQLyog导入的方法为:
·将EXCEL表另存为CSV形式;
·打开SQLyog,对要导入的表格右击,点击“导入”-“导入使用加载本地CSV数据”;
·在弹出的对话框中,点击“改变..”,把选择“填写excel友好值”,点击确定;
·在“从文件导入”中选择要导入的CSV文件路径,点击“导入”即可导入数据到表上;
3.一个比较笨的手工方法,就是先利用excel生成sql语句,然后再到mysql中运行,这种方法适用于excel表格导入到各类sql数据库:
·假设你的表格有A、B、C三列数据,希望导入到你的数据库中表格tablename,对应的字段分别是col1、col2、col3
·在你的表格中增加一列,利用excel的公式自动生成sql语句,具体方法如下:
1)增加一列(假设是D列)
2)在第一行的D列,就是D1中输入公式:
=CONCATENATE("insert
into
tablename
(col1,col2,col3)
values
(",A1,",",B1,",",C1,");")
3)此时D1已经生成了如下的sql语句:
insert
into
table
(col1,col2,col3)
values
('a','11','33');
4)将D1的公式复制到所有行的D列(就是用鼠标点住D1单元格的右下角一直拖拽下去啦)
5)此时D列已经生成了所有的sql语句
6)把D列复制到一个纯文本文件中,假设为sql.txt
·把sql.txt放到数据库中运行即可,你可以用命令行导入,也可以用phpadmin运行。
⑻ C#中如何实现将EXCEL中的数据导入到数据库
这个楼主得到了有数据的dataset还想怎么办?是不是想直接dataset和数据库直接关联,然后update一下?SQL或者Access,这个似乎是不行。这个DataSet更新的话只是针对你一开始连的Excel的表
其实的话你就一条一条吧dataset里面的东西地写进SQL或者Access数据库不就可以了,或者你连数据库的时候再新建一个
Dataset与之关联,然后将你的Excel的ds的数据更新到那个Dataset中然后再将后者Update,那样数据就进入数据库了。
⑼ C#中如何将Excel中的数据批量导入到sql server
1.本文实现在c#中可高效的将excel数据导入到sqlserver数据库中,很多人通过循环来拼接sql,这样做不但容易出错而且效率低下,最好的办法是使用bcp,也就是System.Data.SqlClient.SqlBulkCopy 类来实现。不但速度快,而且代码简单,下面测试代码导入一个6万多条数据的sheet,包括读取(全部读取比较慢)在我的开发环境中只需要10秒左右,而真正的导入过程只需要4.5秒。x0dx0a2.代码如下:x0dx0ausing System; x0dx0ausing System.Data; x0dx0ausing System.Windows.Forms; x0dx0ausing System.Data.OleDb; x0dx0anamespace WindowsApplication2 x0dx0a{ x0dx0a public partial class Form1 : Form x0dx0a { x0dx0a public Form1() x0dx0a { x0dx0a InitializeComponent(); x0dx0a } x0dx0ax0dx0a private void button1_Click(object sender, EventArgs e) x0dx0a { x0dx0a //测试,将excel中的sheet1导入到sqlserver中 x0dx0a string connString = "server=localhost;uid=sa;pwd=sqlgis;database=master"; x0dx0a System.Windows.Forms.OpenFileDialog fd = new OpenFileDialog(); x0dx0a if (fd.ShowDialog() == DialogResult.OK) x0dx0a { x0dx0a TransferData(fd.FileName, "sheet1", connString); x0dx0a } x0dx0a } x0dx0ax0dx0a public void TransferData(string excelFile, string sheetName, string connectionString) x0dx0a { x0dx0a DataSet ds = new DataSet(); x0dx0a tryx0dx0a { x0dx0a //获取全部数据 x0dx0a string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelFile + ";" + "Extended Properties=Excel 8.0;"; x0dx0a OleDbConnection conn = new OleDbConnection(strConn); x0dx0a conn.Open(); x0dx0a string strExcel = ""; x0dx0a OleDbDataAdapter myCommand = null; x0dx0a strExcel = string.Format("select * from [{0}$]", sheetName); x0dx0a myCommand = new OleDbDataAdapter(strExcel, strConn); x0dx0a myCommand.Fill(ds, sheetName); x0dx0ax0dx0a //如果目标表不存在则创建 x0dx0a string strSql = string.Format("if object_id('{0}') is null create table {0}(", sheetName); x0dx0a foreach (System.Data.DataColumn c in ds.Tables[0].Columns) x0dx0a { x0dx0a strSql += string.Format("[{0}] varchar(255),", c.ColumnName); x0dx0a } x0dx0a strSql = strSql.Trim(',') + ")"; x0dx0ax0dx0a using (System.Data.SqlClient.SqlConnection sqlconn = new System.Data.SqlClient.SqlConnection(connectionString)) x0dx0a { x0dx0a sqlconn.Open(); x0dx0a System.Data.SqlClient.SqlCommand command = sqlconn.CreateCommand(); x0dx0a command.CommandText = strSql; x0dx0a command.ExecuteNonQuery(); x0dx0a sqlconn.Close(); x0dx0a } x0dx0a //用bcp导入数据 x0dx0a using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(connectionString)) x0dx0a { x0dx0a bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied); x0dx0a bcp.BatchSize = 100;//每次传输的行数 x0dx0a bcp.NotifyAfter = 100;//进度提示的行数 x0dx0a bcp.DestinationTableName = sheetName;//目标表 x0dx0a bcp.WriteToServer(ds.Tables[0]); x0dx0a } x0dx0a } x0dx0a catch (Exception ex) x0dx0a { x0dx0a System.Windows.Forms.MessageBox.Show(ex.Message); x0dx0a }x0dx0a } x0dx0ax0dx0a //进度显示 x0dx0a void bcp_SqlRowsCopied(object sender, System.Data.SqlClient.SqlRowsCopiedEventArgs e) x0dx0a { x0dx0a this.Text = e.RowsCopied.ToString(); x0dx0a this.Update(); x0dx0a }x0dx0a } x0dx0a} x0dx0a3.上面的TransferData基本可以直接使用,如果要考虑周全的话,可以用oledb来获取excel的表结构,并且加入ColumnMappings来设置对照字段,这样效果就完全可以做到和sqlserver的dts相同的效果了。
⑽ 高分求救。急,C#中导入EXcel表到数据库里面
这个方法是读取Excel中的内容到DataTable 中,方法返回一个DataTable
该方法是静态方法,直接调用就行
类名+点+方法名 DataTable dt = ClassName.readExcel("文件路径")
你这个逻辑,大概是先获得文件名和文件时间,查看文件名和时间在表中是否存在
如果不存在,就把Excel的内容导到数据库中,反之不导入。
导入成功后,把文件名和时间,插入到数据库中。(biaoming 和文件名应该是对应,对应规则你自己规定)
中间再加上数据安全机制