Excel 导入 DataSet 的类

using System;
using System.Data;
using System.Data.OleDb;

namespace Legendigital.Swim.Common
{
    
///<summary>
    
/// Summary description for Excel.
    
///</summary>
    publicclass Excel
     {
        
privateconststring STRING_CONECTTIONSTRING ="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 8.0;HDR=Yes;IMEX=1;"";
        
public Excel()
         {
            
//
            
// TODO: Add constructor logic here
            
//
         }
        
publicstatic DataTable GetDataTable(string excelFilePath,string sql)
         {
            
try
             {
                 DataSet ds
=new DataSet();
                
string connstring =string.Format(STRING_CONECTTIONSTRING,excelFilePath);
                
using(OleDbConnection cnn =new OleDbConnection(connstring))
                 {
                     cnn.Open();
                     OleDbDataAdapter dataAdapter
=new OleDbDataAdapter(sql,cnn);
                     dataAdapter.Fill(ds);
                     cnn.Close();
                    
return ds.Tables[0];
                 }
             }
            
finally
             {        
             }
         }
        
publicstatic DataSet FillDataSet(string excelFilePath,string sql,DataSet ds)
         {
             DataTable dt
= GetDataTable(excelFilePath,sql);

            
foreach(DataRow dr in dt.Rows)
             {
                
try
                 {
                     DataRow newdr
= ds.Tables[0].NewRow();
                    
foreach(DataColumn dc in dt.Columns)
                     {
                        
if(ds.Tables[0].Columns.Contains(dc.ColumnName))
                         {
                             newdr[dc.ColumnName]
= dr[dc.ColumnName];                            
                         }
                     }
                     ds.Tables[
0].Rows.Add(newdr);
                 }
                
catch
                 {

                 }
             }

             ds.AcceptChanges();

            
return ds;
            
         }
     }
}

你可能感兴趣的:(Excel)