日期:2014-05-18 浏览次数:20487 次
/// <summary>
/// 将Excle数据导入数据库
/// Excle列名必须与要传入表的列名一致
/// </summary>
/// <param name="strPath">路径 </param>
/// <param name="strTableName">表名 </param>
public static int InTableFromExcel(string strPath,string strTableName)
{
SqlServerDbAccess m_SqlServerDbAccess = new SqlServerDbAccess();
OleDbConnection cnnxls = null;
OleDbCommand comm = null;
OleDbDataAdapter myda = null;
int x = 0;
int intOpinion = 0;
DataSet myds;
try
{
//读取Excel
string mystring = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strPath + ";" + "Extended Properties=Excel 8.0;";
cnnxls = new OleDbConnection(mystring);
comm = new OleDbCommand("select * from [sheet1$]", cnnxls);
myda = new OleDbDataAdapter(comm);
myds = new DataSet();
myda.Fill(myds);
//查看列名是否一直
string strOpinion = "SELECT TOP 0 * FROM " + strTableName;
DataSet ds = new DataSet();
ds = m_SqlServerDbAccess.executeDataSetCmdString(strOpinion);
System.Data.DataTable table = ds.Tables[0];
System.Data.DataTable excelTable = myds.Tables[0];
if (excelTable.Columns.Count > table.Columns.Count)
{
cnnxls.Close();
return 0;
}
foreach (DataColumn col in table.Columns)
{
for (int y = 0; y < excelTable.Columns.Count; y++)
{
if (col.ColumnName.Trim() == excelTable.Columns[y].ColumnName.Trim())
{
intOpinion++;
break;
}
}
}
if (intOpinion != excelTable.Columns.Count)
{
cnnxls.Close();
return 0;
}
//数据导入数据库
int intColumnCount = excelTable.Columns.Count;
string strColumnName = excelTable.Columns[0].ColumnName;
for (int i = 1; i < excelTable.Columns.Count; i++)
{
strColumnName += "," + excelTable.Columns[i].ColumnName;
}
string strCommText = string.Empty;
&