今天接到一个需求,实现一个小功能—导入Excel,想想诸位活跃于.NET平台上的兄弟们,其中应该有相当一部分是从事如信息系统类开发的,所以小弟在这里姑且臭屁一下导入Excel的几种实现方法,如有错误之处,烦请大虾指正。

      第一步呢当然是将Excel中的数据导入进DataTable里面,这一步是很简单的,贴下Code。之后开始讨论如何将DataTable中的这些数据放进数据库里面:

// 读取Excel
    public static DataTable GetExcelFileData(string filePath)
    {
        OleDbDataAdapter oleAdp 
= new OleDbDataAdapter();
        OleDbConnection oleCon 
= new OleDbConnection();
        
string strCon = "Provider=Microsoft.Jet.oleDb.4.0;data source=" + filePath + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
        
try
        {
            DataTable dt 
= new DataTable();
            oleCon.ConnectionString 
= strCon;
            oleCon.Open();
            DataTable table 
= oleCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            
string sheetName = table.Rows[0][2].ToString();
            
string sqlStr = "Select * From [" + sheetName + "]";
            oleAdp 
= new OleDbDataAdapter(sqlStr, oleCon);
            oleAdp.Fill(dt);
            oleCon.Close();
            
return dt;
        }
        
catch (Exception ex)
        {
            
throw ex;
        }
        
finally
        {
            oleAdp 
= null;
            oleCon 
= null;
        }
    }

相关文章: