我将excel导入sql数据,总是提示在位置0处没有数据行

问题描述

privatevoidbtn_Import_Click(objectsender,System.EventArgse){OpenFileDialogdlg=newOpenFileDialog();dlg.Filter="Excel文件|*.xls";if(dlg.ShowDialog()==DialogResult.OK){stringstrPath=dlg.FileName;stringsConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource='+strPath+';"+"ExtendedProperties=Excel8.0;";//stringsConnectionString="Provider=Microsoft.Jet.OLEDB.4.0;DataSource=strPath;ExtendedProperties=Excel8.0";try{OleDbConnectionoleDbConnection=newOleDbConnection(sConnectionString);oleDbConnection.Open();//获取excel表DataTabledataTable=oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);//获取sheet名,其中[0][1]...[N]:按名称排列的表单元素stringtableName=dataTable.Rows[0][2].ToString().Trim();tableName="["+tableName.Replace("'","")+"]";//利用SQL语句从Excel文件里获取数据stringquery="SELECT移动电话,机主姓名,年龄,月收入,月消费,车辆价格,所在公司名称,主营产品或服务,主营行业,企业类型,注册资金,地址,邮编FROM"+tableName;DataSetdataset=newDataSet();OleDbDataAdapteroleAdapter=newOleDbDataAdapter(query,sConnectionString);oleAdapter.Fill(dataset,"LSHXHMK");//this.DataGrid1.DataBind();//创建OldDbDataAdapter执行sql语句//OleDbDataAdapterexcelDA=newOleDbDataAdapter("select*from[1全市总表$]",sConnectionString);////创建DataSet对象//DataSetExcelDs=newDataSet();////执行Sql语句,并将结果填充到DataSet中//excelDA.Fill(ExcelDs);//从web.config中取得数据库连接//string//con=System.Configuration.ConfigurationManager.AppSe//ttings["ConnectionString"].ToString();SqlConnectionsqlcon=newSqlConnection("server=localhost;database=hao;UserID=sa;");sqlcon.Open();//fot(i=0;if<)//从excel文件获得数据后,插入记录到SQLServer的数据表DataTabledataTable1=newDataTable();SqlDataAdaptersqlDA1=newSqlDataAdapter(@"SELECT移动电话,机主姓名,年龄,月收入,月消费,车辆价格,所在公司名称,主营产品或服务,主营行业,企业类型,注册资金,地址,邮编FROMLSHXHMK",sqlcon);SqlCommandBuildersqlCB1=newSqlCommandBuilder(sqlDA1);sqlDA1.Fill(dataTable1);foreach(DataRowdataRowindataset.Tables["LSHXHMK"].Rows){//sql里数据dataRow1DataRowdataRow1=dataTable1.NewRow();dataRow1["移动电话"]=dataRow["移动电话"];dataRow1["机主姓名"]=dataRow["机主姓名"];dataRow1["年龄"]=dataRow["年龄"];dataRow1["月收入"]=dataRow["月收入"];dataRow1["月消费%"]=dataRow["月消费%"];dataRow1["车辆价格"]=dataRow["车辆价格"];dataRow1["所在公司名称"]=dataRow["所在公司名称"];dataRow1["主营产品或服务"]=dataRow["主营产品或服务"];dataRow1["企业类型"]=dataRow["企业类型"];dataRow1["注册资金"]=dataRow["注册资金"];dataRow1["地址"]=dataRow["地址"];dataRow1["邮编"]=dataRow["邮编"];dataTable1.Rows.Add(dataRow1);}Console.WriteLine("新插入"+dataTable1.Rows.Count.ToString()+"条记录");sqlDA1.Update(dataTable1);oleDbConnection.Close();}catch(Exceptionex){MessageBox.Show(ex.Message.ToString());}}}}

解决方案

解决方案二:
为什么运行到stringtableName=dataTable.Rows[0][2].ToString().Trim();就是读不到数据
解决方案三:
给你一个例子吧。。。:给你一个例子吧。。。:自己看看给你一个例子吧。。。:自己看看给你一个例子吧。。。:自己看看给你一个例子吧。。。:自己看看
解决方案四:
usingSystem;usingSystem.Data;usingSystem.Drawing;usingSystem.Web;usingSystem.Web.UI.WebControls;usingSystem.Web.UI.HtmlControls;usingSystem.Data.SqlClient;usingSystem.Text;usingSystem.Web.UI;usingSystem.Data.OleDb;usingSystem.Configuration;usingSystem.Text.RegularExpressions;namespaceBaseDataImport{///<summary>///BaseData的摘要说明。///</summary>publicclassBaseData:System.Web.UI.Page{protectedSystem.Web.UI.WebControls.LabelLblShowMsg;protectedSystem.Web.UI.HtmlControls.HtmlInputFilemyFile;protectedSystem.Web.UI.HtmlControls.HtmlSelectsltType;protectedSystem.Web.UI.HtmlControls.HtmlInputButtonbtnShow;protectedSystem.Web.UI.HtmlControls.HtmlInputButtonbtnParser;protectedSystem.Web.UI.HtmlControls.HtmlInputButtonbtnImport;protectedSystem.Web.UI.WebControls.DataGriddgExcel;protectedSystem.Web.UI.HtmlControls.HtmlTableResultTable;privatevoidPage_Load(objectsender,System.EventArgse){//在此处放置用户代码以初始化页面}#regionWeb窗体设计器生成的代码overrideprotectedvoidOnInit(EventArgse){////CODEGEN:该调用是ASP.NETWeb窗体设计器所必需的。//InitializeComponent();base.OnInit(e);}///<summary>///设计器支持所需的方法-不要使用代码编辑器修改///此方法的内容。///</summary>privatevoidInitializeComponent(){this.btnShow.ServerClick+=newSystem.EventHandler(this.btnShow_ServerClick);this.btnParser.ServerClick+=newSystem.EventHandler(this.btnParser_ServerClick);this.Load+=newSystem.EventHandler(this.Page_Load);}#endregionprivatevoidbtnShow_ServerClick(objectsender,System.EventArgse){try{LblShowMsg.Text="正在加载数据......";stringtmpFilePathName="";stringtmpFileName="";stringtmpExtendedName="";tmpFilePathName=myFile.PostedFile.FileName;stringsUrl=HttpContext.Current.Request.Url.AbsoluteUri;System.IO.FileInfofi=newSystem.IO.FileInfo(tmpFilePathName);tmpFileName=fi.Name;tmpExtendedName=fi.Extension;stringsServerPath=Server.MapPath("UploadFile/");System.IO.DirectoryInfodi=newSystem.IO.DirectoryInfo(sServerPath);if(!di.Exists){di.Create();}myFile.PostedFile.SaveAs(sServerPath+tmpFileName);stringsTName=sltType.Value;DataSetds=this.GetDataFromExcel(sServerPath+tmpFileName,sTName);dgExcel.DataSource=ds;dgExcel.DataBind();this.btnParser.Disabled=false;}catch(Exceptionex){LblShowMsg.Text=ex.Message;}LblShowMsg.Text="加载成功!";}///<summary>///获取Excel文档后,转换为DataSet///</summary>///<paramname="sExcelFilePath">Excel文件</param>///<returns></returns>publicDataSetGetDataFromExcel(stringsExcelFilePath,stringsTableName){DataSetmyDataSet=newDataSet();stringstrConn="Provider=Microsoft.Jet.OLEDB.4.0;"+"DataSource="+sExcelFilePath+";"+"ExtendedProperties=Excel8.0;";OleDbConnectionconn=newOleDbConnection(strConn);try{conn.Open();//DataTableSchemaTable=conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,newobject[]{null});OleDbDataAdaptermyCommand=newOleDbDataAdapter("SELECT*FROM["+sTableName+"$]",strConn);myCommand.Fill(myDataSet);}catch(ExceptionEx){LblShowMsg.Text=Ex.Message;}finally{conn.Close();conn.Dispose();}returnmyDataSet;}///<summary>///分析数据///</summary>///<paramname="sender"></param>///<paramname="e"></param>privatevoidbtnParser_ServerClick(objectsender,System.EventArgse){SqlConnectionsc;SqlCommandcmd;try{sc=newSqlConnection(ConfigurationSettings.AppSettings["ConnStr_Local"].ToString());sc.Open();cmd=sc.CreateCommand();//------先清空表中数据------cmd.CommandText="TrunCateTable"+sltType.Value;cmd.ExecuteNonQuery();//------先清空表中数据------}catch{LblShowMsg.Text="无法操作数据库,操作被终止。";return;}boolbTag=true;//foreach(DataGridItemitemindgExcel.Items)//{//foreach(TableCellcellinitem.Cells)//{//if(cell.Text=="&nbsp;")//{//bTag=false;//cell.BackColor=Color.Red;//break;//}////if(cell.Text=="中文")cell.Text="1";//if(cell.Text=="英文")cell.Text="2";//}////if(!bTag)break;//if(!this.ImportDataToTable(item,sltType.Value,cmd,sltType.Value))//{//bTag=false;//break;//}//}stringtmpFilePathName="";stringtmpFileName="";stringtmpExtendedName="";tmpFilePathName=myFile.PostedFile.FileName;stringsUrl=HttpContext.Current.Request.Url.AbsoluteUri;System.IO.FileInfofi=newSystem.IO.FileInfo(tmpFilePathName);tmpFileName=fi.Name;tmpExtendedName=fi.Extension;stringsServerPath=Server.MapPath("UploadFile/");System.IO.DirectoryInfodi=newSystem.IO.DirectoryInfo(sServerPath);if(!di.Exists){di.Create();}myFile.PostedFile.SaveAs(sServerPath+tmpFileName);stringsTName=sltType.Value;DataSetds=this.GetDataFromExcel(sServerPath+tmpFileName,sTName);
解决方案五:
dgExcel.DataSource=ds;dgExcel.DataBind();//for(inti=0;i<ds.Tables[0].Columns.Count;i++)//{//LblShowMsg.Text+=ds.Tables[0].Columns[i].ColumnName+"____";//}for(inti=0;i<ds.Tables[0].Rows.Count;i++){for(intj=0;j<ds.Tables[0].Columns.Count;j++){if(ds.Tables[0].Rows[i]["语言"].ToString()=="&nbsp;"){bTag=false;//cell.BackColor=Color.Red;break;}if(ds.Tables[0].Rows[i]["语言"].ToString()=="中文")ds.Tables[0].Rows[i]["语言"]="1";if(ds.Tables[0].Rows[i]["语言"].ToString()=="英文")ds.Tables[0].Rows[i]["语言"]="2";}if(!bTag)break;if(!this.ImportDataToTable(ds.Tables[0].Rows[i]["国家代码"].ToString(),ds.Tables[0].Rows[i]["国家名称"].ToString(),ds.Tables[0].Rows[i]["语言"].ToString(),ds.Tables[0].Rows[i]["所属区域"].ToString(),sltType.Value,cmd,sltType.Value)){bTag=false;break;}}if(bTag==false){LblShowMsg.Text="数据分析不正确,导入终止。";this.btnParser.Disabled=true;}else{LblShowMsg.Text="数据正确,并已入库!";this.btnParser.Disabled=true;}cmd.Dispose();sc.Close();sc.Dispose();}///<summary>///数据入库///</summary>///<paramname="Dgi"></param>///<paramname="sTable"></param>///<paramname="cmd"></param>privateboolImportDataToTable(stringstr1,stringstr2,stringstr3,stringstr4,stringsTable,SqlCommandcmd,stringsTableName){try{stringsSQL="";//区域//if(sTableName=="Inter_AirArea")//sSQL="INSERTINTOInter_AirArea(AreaName,LangCode,IsValid)VALUES(N'"+Dgi.Cells[1].Text+"',"+Dgi.Cells[2].Text+",1)";//国家if(sTableName=="Inter_AirCountry"){stringsAreaID="0";cmd.CommandText="selectAreaIDfromInter_AirAreawhereAreaName=N'"+str4+"'andLangCode="+str3;objectobj=cmd.ExecuteScalar();if(obj==null||obj.ToString().Trim()==""){//Dgi.Cells[3].BackColor=Color.Red;returnfalse;}sAreaID=obj.ToString();sSQL="INSERTINTOInter_AirCountry(CountryCode,CountryName,LangCode,AreaID)VALUES"+"(upper(N'"+str1+"'),N'"+str2+"',"+str3+","+sAreaID+")";//Dgi.Cells[3].Text=sAreaID;}//城市//if(sTableName=="Inter_AirCity")//{//stringsCountryName="";//cmd.CommandText="selectCountryNamefromInter_AirCountrywhereCountryCode=N'"+Dgi.Cells[3].Text.Trim()+"'andLangCode="+Dgi.Cells[2].Text;//objectobj=cmd.ExecuteScalar();//if(obj==null)//{//Dgi.Cells[3].BackColor=Color.Red;//returnfalse;//}////sCountryName=obj.ToString();//////sSQL="INSERTINTOInter_AirCity(CityCode,CityName,LangCode,CountryCode)VALUES"+//"(upper(N'"+Dgi.Cells[0].Text+"'),N'"+Dgi.Cells[1].Text+"',"+Dgi.Cells[2].Text+",'"+Dgi.Cells[3].Text+"')";////Dgi.Cells[3].Text=sCountryName;//}//机场//if(sTableName=="Inter_AirPort")//{//stringsCityName="";//cmd.CommandText="selectCityNamefromInter_AirCitywhereCityCode=N'"+Dgi.Cells[3].Text.Trim()+"'andLangCode="+Dgi.Cells[2].Text;//objectobj=cmd.ExecuteScalar();//if(obj==null)//{//Dgi.Cells[3].BackColor=Color.Red;//returnfalse;//}////sCityName=obj.ToString();//////sSQL="INSERTINTOInter_AirPort(AirPortCode,AirPortName,LangCode,CityCode)VALUES"+//"(upper(N'"+Dgi.Cells[0].Text+"'),N'"+Dgi.Cells[1].Text+"',"+Dgi.Cells[2].Text+",'"+Dgi.Cells[3].Text+"')";////Dgi.Cells[3].Text=sCityName;//}//航空公司//if(sTableName=="Inter_AirLine")//{//stringsCountryName="";//cmd.CommandText="selectCountryNamefromInter_AirCountrywhereCountryCode=N'"+Dgi.Cells[4].Text.Trim()+"'andLangCode="+Dgi.Cells[3].Text;//objectobj=cmd.ExecuteScalar();//if(obj==null)//{//Dgi.Cells[4].BackColor=Color.Red;//returnfalse;//}////sCountryName=obj.ToString();////sSQL="INSERTINTOInter_AirLine(AirLineCode,AirLineName,AirLineShortName,LangCode,CountryCode)VALUES"+//"(upper(N'"+Dgi.Cells[0].Text+"'),N'"+Dgi.Cells[1].Text+"','"+Dgi.Cells[2].Text+"',"+Dgi.Cells[3].Text+",'"+Dgi.Cells[4].Text+"')";////Dgi.Cells[4].Text=sCountryName;//}if(sSQL!=""){cmd.CommandText=sSQL;cmd.ExecuteNonQuery();}}catch{returnfalse;}returntrue;}}}
解决方案六:
谢谢,问题解决了,就是把双引号写成单引号了
解决方案七:
yong用Ado怎么搞

时间: 2024-08-02 00:43:22

我将excel导入sql数据,总是提示在位置0处没有数据行的相关文章

ASP.NETR把Excel导入SQL数据库的自定义类

ASP.NETR把Excel导入SQL数据库的自定义类 以下是引用片段:public class SaveToSql {   public string strNewCodeId = string.Empty;   public string strNewCode = string.Empty;   public string strNewDes = string.Empty;   public string strOldCodeId = string.Empty;   public strin

new-VB6实现excel导入SQL SERVER7程序问题

问题描述 VB6实现excel导入SQL SERVER7程序问题 Set cnn = New ADODB.Connection cnn.Open "Provider=SQLOLEDB.1;Persist Security Info=True;User ID=sa;Initial Catalog=labor;Data Source=RPC_004" cnn.CursorLocation = adUseClient Set RS = New ADODB.Recordset STR = &q

excel-用ADO将Excel导入sql server 2008 报error# 3092错误

问题描述 用ADO将Excel导入sql server 2008 报error# 3092错误 我用ADO将一张excel表导入到sql server中去,代码如下: hr=m_pConnection->Open(_bstr_t("Provider=SQLOLEDB;server=TOUCH;Database=MR_NXT;Uid=touch0413;Pwd=LJm_1989915"),"","",adModeUnknown); m_pCo

C#,将excel导入sql 表里的时候,如何读取excel第一行标头的内容阿

问题描述 C#,将excel导入sql表里的时候,如何读取excel第一行标头的内容阿.也就是指定单元格的内容.谢谢 解决方案 解决方案二:http://www.cnblogs.com/GodSpeed/archive/2008/03/14/1105178.html解决方案三:如果仅需要读取标题信息的话可用使用OleDbConnection的GetSchema方法解决方案四:将excel作为数据库读取,加载到datatable里面,就可以取到表头了.解决方案五:能说详细点吗,我是新手.另,我已经

using-websevice提示从索引 0 处开始,初始化字符串的格式不符合规范。ADD功能不能用 第二个可以

问题描述 websevice提示从索引 0 处开始,初始化字符串的格式不符合规范.ADD功能不能用 第二个可以 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient; namespace WebService2 { /// /// Service1 的摘要说明 /// [W

EXCEL导入sql 用C#体现?

问题描述 表结构建立好后,以下是SQL代码?我想能够用excel导入到sqlServer后显示以下代码返回的所有行在导出到excel?代码该如何写,本人新手@.@感谢!SQL-代码selectname,workshop,sum(integral)frombirthdaywherefdate>='2014-07-01'groupbyworkshop,namehavingsum(integral)>=50orderbyworkshop,name; 解决方案 解决方案二:如果就这需求,根本就不用借助

excel导入sql sever-求完整的JSP页面上传excel 将数据导入数据库的代码

问题描述 求完整的JSP页面上传excel 将数据导入数据库的代码 找的的代码都会各种报错 上传的jsp页面的action要指向哪个文件? 解决方案 这篇文章主要介绍了JSP上传excel及excel插入至数据库的方法,涉及JSP文件上传及针对excel的读取.写入数据库等操作技巧,需要的朋友可以参考下 本文实例讲述了JSP上传excel及excel插入至数据库的方法.分享给大家供大家参考.具体如下: 此导入excel是与pojo绑定的,(缺点)excle表头必须是pojo的字段值 1. htm

格式导致的Excel导入sql出现异常的解决方法_MsSql

本来程序是正常运行的,有时候会因为用户的excel文档没有按要求的格式来做,才会出现一些异常情况.本以为这次也是一样,后来拿到数据一看,并没有发现什么异常,而且自己又照着做了一些数据,竟然也会出现异常,只好怀疑是自己的程序有问题了. 常言说的好,最难找的是最后一个错误,这话确实不错.我几乎动用了我所掌握的各种手段,程序上真的没办法找出有啥问题了.在一个问题上折腾久了,浪费时间不说,还容易让自己的情绪低落.到后来,还是转去怀疑用户的数据有问题,无意中做了一下格式调整,竟然发现异常不见了. Exce

excel导入sql

<% 'On Error Resume Next '导入Excel电子表格数据到SQL Sever数据库 By Dicky 2004-12-27 16:41:12 Function Open_Conn(SqlDatabaseName,SqlPassword,SqlUsername,SqlLocalName,SqlConn) '创建数据库连接对象并打开数据库连接 Dim ConnStr 'SQL Server数据库连接参数:数据库名.用户密码.用户名.连接名(本地用local,外地用IP) Con