在c#中,从excel中导入数据到数据库,有没有人有这个代码的,能否给我一份
在c#中,从excel中导入数据到数据库,有没有人有这个代码的,能否给我一份,还有就是在excel中我要做判断有其中一列有的内容是‘dtp’那么存到数据库里对应的字段里传值1 --------------------编程问答--------------------
public class Define
{
//连接字符串
public const string Define_ConnectStringFormat = "Provider=Microsoft.Jet.OleDb.4.0;data source={0};Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
//SQL格式字符串
public const string Define_SQLStringFormat = "Select * from [{0}$]";
}
//Excel操作类
class DBInte易做图ce
{
private OleDbConnection conn = null;
private OleDbDataAdapter adapter = null;
/// <summary>
/// 打开Excel
/// </summary>
/// <param name="excelFilename">Excel名</param>
/// <returns>true:成功 false:失败</returns>
internal bool OpenExcel(string excelFilename)
{
try
{
//生成连接字符串
string strConn = string.Format(Define.Define_ConnectStringFormat, excelFilename);
conn = new OleDbConnection(strConn);
return true;
}
catch
{
return false;
}
}
/// <summary>
/// 取得Sheet的内容
/// </summary>
/// <param name="sheetName">Sheet名</param>
/// <returns>DataTable</returns>
internal DataTable GetSheet(string sheetName)
{
try
{
string strSQL = string.Format(Define.Define_SQLStringFormat, sheetName);
adapter = new OleDbDataAdapter(strSQL, conn);
DataSet dataSet = new DataSet();
conn.Open();
adapter.Fill(dataSet, sheetName);
DataTable dataTable = dataSet.Tables[sheetName];
conn.Close();
return dataTable;
}
catch
{
return null;
}
}
}
//对数据操作
DBInte易做图ce dbInte易做图ce = new DBInte易做图ce();
//打开Excel
dbInte易做图ce.OpenExcel("filename.xls");
//得到Sheet的内容
DataTable inputTable = dbInte易做图ce.GetSheet("Sheet1");
按照这种方式得到的DatatTable的列名是Sheet第一行的内容,例:你的Sheet的内容为:
name id
xxxx 3
那么DataTable就有俩列,列名分别为name和id.
你也可以使用Excel的Com接口来对Excel进行操作,不过麻烦一些而已。
--------------------编程问答-------------------- string conn= "Server=127.0.0.1;Database=数据库;UID=sa;pwd=********;";
try {
using (System.Data.SqlClient.SqlBulkCopy bcp = new System.Data.SqlClient.SqlBulkCopy(conn)) {
//bcp.SqlRowsCopied += new System.Data.SqlClient.SqlRowsCopiedEventHandler(bcp_SqlRowsCopied);
bcp.BatchSize = 100;//每次传输的行数
bcp.NotifyAfter = 100;//进度提示的行数
bcp.DestinationTableName = sTableName;//目标表
bcp.WriteToServer(dsExcel.Tables[0]);
Response.Write("ok");
}
} catch (Exception ex) {
sError = ex.Message;
}
这个方法导入很好,很快,适用于数据量大的导入. --------------------编程问答-------------------- 漏了点
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;" + "Data Source=" + sPath + sFileName + ";" + "Extended Properties='Excel 8.0; HDR=YES; IMEX=1'";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = null;
strExcel = "select * from [sheet1$]";
myCommand = new OleDbDataAdapter(strExcel, strConn);
myCommand.Fill(dsExcel, "table1");
conn.Close(); --------------------编程问答-------------------- 给你参考下
http://hi.baidu.com/honghu3000/blog/item/73a092fadbd3629158ee9026.html
补充:.NET技术 , C#