Excel을 DataSet으로 변환하여 데이터베이스에 저장
2571 단어 C# Excel 읽기
1. 먼저 Excel 파일을 업로드하여 업로드된 Excel 파일의 절대 경로를 찾습니다.
2. Excel의 데이터를 DataSet에 읽기;
/// <summary>
/// Excel DataSet
/// </summary>
/// <param name="path">Excel </param>
/// <returns> </returns>
public static DataSet ExcelToDataSet(string path)
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=Excel 8.0;";
DataSet myDataSet = new DataSet();
using (OleDbConnection myOleDbConnection = new OleDbConnection(strConn))
{
myOleDbConnection.Open();
string strExcel = " select * from [sheet1$]";
using (OleDbCommand myOleDbCommand = new OleDbCommand(strExcel, myOleDbConnection))
{
myOleDbCommand.ExecuteNonQuery();
using (OleDbDataAdapter myOleDbDataAdapter = new OleDbDataAdapter(myOleDbCommand))
{
myOleDbDataAdapter.Fill(myDataSet);
}
}
}
return myDataSet;
}
3. SqlCommandBuilder와 결합하여 DataSet의 데이터를 데이터베이스에 저장한다.
/// <summary>
/// DataSet
/// </summary>
/// <param name="sql"> </param>
/// <param name="strTblName"> </param>
/// <returns></returns>
public static int CommondDataTable(DataTable dt, string strTblName)
{
using (SqlConnection Connection = new SqlConnection(connectionString))
{
Connection.Open();
SqlTransaction trans = Connection.BeginTransaction();
try
{
SqlDataAdapter adapter = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand("select * from " + strTblName, Connection);
cmd.Transaction = trans;
adapter.SelectCommand = cmd;
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(adapter);
int reuslt = adapter.Update(dt);
trans.Commit();
return reuslt;
}
catch (Exception ex)
{
trans.Rollback();
return 0;
}
}
}