最好能有这方面的例子啊,越详细越好
解决方案 »
- IDbCommand.Prepare()后命令只执行一次,那么Prepare()方法还有用吗
- 如何将SQL Server中对应某个XML中的某个attribute的Record给输出成XML?
- WPF 跪求 求解 在线等待?
- 急问一个数据库约束问题~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- C#中webBrowser 第二次访问同一个地址,验证码不刷新的问题!
- 求一个正则表达式?
- 为什么Assembly.Load(Path).CreateInstance(ClassName);的值为null?
- winCe 通信
- 如何将一个byte[]类型的数组转换成自己定义的Struct类型?
- 那里可以下载MapX 中的.Net Sample
- 关于查询的问题 (菜鸟级别)
- 咨询:C#程序运行中,就存在大量的新建对象,释放新建对象。不知道这样有同志这么做过项目吗?可行不
public static DataSet ImportExcel(string file)
{
FileInfo fileInfo = new FileInfo(file);
if (!fileInfo.Exists)
return null;
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + file + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
OleDbConnection objConn = new OleDbConnection(strConn);
DataSet dsExcel = new DataSet();
try
{
objConn.Open();
string strSql ="select * from [Sheet1$]";
OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
odbcExcelDataAdapter.Fill(dsExcel);
//关闭excel数据源
objConn.Close(); return dsExcel;
}
catch (Exception ex)
{
//这里该如何控制呢!当格式不符合需求的时候????????????
MessageBox.Show(ex.Message,"提示");
return dsExcel;
//throw ex;
}
}这个方法将excel标中的数据读出:下一个方法调用
DataSet ds;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
ds = ImportExcel(this.openFileDialog1.FileName);//获取excel
if (ds.Tables.Count <=0)
{
//MessageBox.Show("表中没有数据或者预期格式不对!\n请检查","提示");
return;
}
}
else
{
return;
}
……
int dsLength = ds.Tables[0].Rows.Count;//获取excel中数据的长度
for (int i = 1; i < dsLength; i++)
{
//判断获取到的数据是不是数字!如果不是数字就弹出提示
string pattern = @"^\d+(\.\d)?$";
if(!System.Text.RegularExpressions.Regex.IsMatch(ds.Tables[0].Rows[i][3].ToString(),pattern))
{
MessageBox.Show("请检查你的EXCEL表列的顺序是不是\n物料名称、规格型号、单位、数量、生产商","提示");
return;
}
}
在for循环中获取ds里面的数据,然后一条一条插入数据库即可
public DataTable dt;
string str = "Data Source=localhost;Initial Catalog=excel;Integrated Security=True";
string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\1.xls;Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(strCon);
string sql = "select * from [Sheet1$]";
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(sql, strCon);
ds = new DataSet();
myCommand.Fill(ds, "[Sheet1$]");
dataGridView1.DataMember = "[Sheet1$]";
dataGridView1.DataSource = ds;
conn.Close();
SqlBulkCopy DesBulkOp = new SqlBulkCopy(str);
dt = ds.Tables[0] ;
if (dt!= null&&dt.Rows.Count!=0)
{
try
{
DesBulkOp.DestinationTableName = "Table1";
DesBulkOp.WriteToServer(dt);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DesBulkOp.Close();
}
MessageBox.Show("恭喜你,插入成功!");
}