Excel导入到SQL Server ·····返回电子表格中某个表并形成datatable
Posted on 2006-10-26 00:07 且行且思 阅读(570) 评论(0) 编辑 收藏 举报格式一定要统一,要不然程序就不好以什么为标准进行判断,
#region 返回打开的电子表格中的某个表并形成datatable
/// <summary>
/// 返回打开的电子表格中的某个表并形成datatable
/// </summary>
/// <param name="path">文件绝对路径</param>
/// <param name="target">要打开的表名</param>
/// <returns>返回DATATABLE数据库集</returns>
private void ReadExcel()
{
try
{
DataTable rs=new DataTable();
rs=null;
DataSet rDs=null;
string strConn="";
int count=0;
string id =Request["id"];
DateTime createtime=DateTime.Now ;
string date=createtime.Year.ToString()+"-"+createtime.Month.ToString ()+"-"+createtime.Day.ToString ()+" "+createtime.Hour.ToString()+":"+createtime.Minute.ToString()+":"+createtime.Second.ToString();
string sqlstr=" select * from tab_uppart_file where id ="+id+"";
string userid=data1.readout(sqlstr,1);
string fileName=data1.readout(sqlstr,3);
string path = Server.MapPath("../upparts/"+fileName);
string filepath="..\\upparts\\"+fileName;
if (File.Exists (Server.MapPath(filepath)))//判断文件是否存在
{
strConn ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+path+";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"; //IMEX=1 用来转换文本
OleDbConnection conn = new OleDbConnection(strConn);
OleDbDataAdapter myCommand = new OleDbDataAdapter("SELECT * FROM [Sheet1$]",strConn);
DataSet myDataSet = new DataSet();
myCommand.Fill(myDataSet,"[Sheet1$]");
foreach(DataRow row in myDataSet.Tables[0].Rows)
{
count++;
string classid="";
string name="";
string model="";
string price="";
string num="";
string mfg="";
string package="";
string remark="";
classid=row["产品类型"].ToString();
name=row["产品名称"].ToString();
model=row["产品型号"].ToString();
price=row["产品价格"].ToString();
num=row["数 量"].ToString();
mfg=row["生产厂商"].ToString();
package=row["封 装"].ToString();
remark=row["交易说明"].ToString();
if (name!="" && model!="")
{
sqlstr="insert into tab_part values('"+name+"','"+model+"','"+num+"','"+package+"','"+mfg+"','"+price+"','"+remark+"','"+classid+"','"+createtime+"','"+userid+"','0')";
data1.moddata(sqlstr);
}
}
string updatesql="update tab_uppart_file set flag='1',uploadtime='"+date+"' where id='"+id+"'";
data1.moddata(updatesql);
data1.Alert2 ("上传记录成功!","BatchAddParts.aspx",Page);
}
else
{
data1.Alert2("没有找到相应的模板文件","BatchAddParts.aspx",Page);
}
}
catch(System.Data.OleDb.OleDbException ex)
{
Response.Write(ex.Message );
}
}
#endregion