环境:ASP+EXCEL+SQL
public static void DataTableToDB()
{
string _strExcelFileName = @"D:/Nili.xls";
DataTable dtExcel = ExcelToDataTable(_strExcelFileName, "Sheet1");
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
InsertDataToAccess(dtExcel.Rows[i][0].ToString(), dtExcel.Rows[i][1].ToString(),dtExcel.Rows[i][2].ToString());
}
}
public static DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties=Excel 5.0;";
string strExcel = string.Format("select * from [{0}$]", strSheetName);
DataSet ds = new DataSet();
using (OleDbConnection con = new OleDbConnection(strConn))
{
con.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName);
con.Close();
}
return ds.Tables[strSheetName];
}
public static void InsertDataToAccess(string sFunctionID, string sPerentFunctionID,string sFunctionName)
{
SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["Conn"]);
con.Open();
string strInsertString = "INSERT INTO PWP_Function VALUES (@FunctionID,@PerentFunctionID,@FunctionName)";
SqlCommand cmd = new SqlCommand(strInsertString, con);
cmd.Parameters.Add("@FunctionID", SqlDbType.VarChar, 20);
cmd.Parameters["@FunctionID"].Value = sFunctionID;
cmd.Parameters.Add("@PerentFunctionID", SqlDbType.VarChar, 20);
cmd.Parameters["@PerentFunctionID"].Value = sPerentFunctionID;
cmd.Parameters.Add("@FunctionName", SqlDbType.VarChar, 20);
cmd.Parameters["@FunctionName"].Value = sFunctionName;
cmd.ExecuteNonQuery();
con.Close();
}