什么没有 发表于 2015-7-3 13:20:39

用C#如何将Excel导入到SQL Server

  作者:被偷De贼
  Excel的导入一定给客户规定统一的模板,这样才能方便做业务处理.
  我是这样做的.
  首先将Excel的所有Sheet页全都读出来,请用户选择要处理的Sheet的页,获取Sheet页代码如下
  Code
/      //
      /// 获取Excel的表名
      ///
      /// Excel的路径
      /// DataTable
      public static DataTable GetExcelTableName(string path)
      {
            var conn = GetConnection(path);
            var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            conn.Close();
            return dt;
      }
  返回的DataTable可以绑定到Listbox控件中,
当用户选择好要处理Sheet页后,将选择的Sheet页名称输入到下面的方法,以获取所选Sheet页的内容:
  


Code
      ///
      /// 根据Excel的表名,获取相应表的内容
      ///
      /// Excel的表名
      /// Excel路径
      ///
      public static DataTable GetExcelTable(string tableName,string path)
      {
            var sql = string.Format("SELECT * FROM [{0}]", tableName);
            var conn = GetConnection(path);
            var myCommand = new OleDbDataAdapter(sql, conn);
            var myDataSet = new DataSet();
            myCommand.Fill(myDataSet);
            return myDataSet.Tables;
      }  
  返回一个DataTable,这样你就可以根据自己的业务来处理DataTable中的数据了.
完整的代码如下:
  


Code
using System.Data;
using System.Data.OleDb;
using System.Windows.Forms;
/*
* 程序功能: Excel导入
* 创建日期:2008-8-3
* 创 建 者:Robber
* 开发环境:WinXp_Sp3+VS2008
* URL:http://robber.iyunv.com/
*/
namespace ExcelToDb
{
    ///
    /// Excel 的摘要说明。
    ///
    public class Excel
    {
      public Excel()
      {
            //
            // TODO: 在此处添加构造函数逻辑
            //
      }
      static OleDbConnection GetConnection(string path)
      {
            var strConn=string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Excel 8.0;",path);
            var conn = newOleDbConnection(strConn);
            conn.Open();
            return conn;
      }
      ///
      /// 获取Excel的表名
      ///
      /// Excel的路径
      /// DataTable
      public static DataTable GetExcelTableName(string path)
      {
            var conn = GetConnection(path);
            var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            conn.Close();
            return dt;
      }
      ///
      /// 获取Excel的路径
      ///
      /// 路径
      public static string GetExcelPath()
      {
            var dlg = new OpenFileDialog {Filter = "Microsoft Excel|*.xls"};
            return dlg.ShowDialog() == DialogResult.OK ? dlg.FileName : string.Empty;
      }
      ///
      /// 根据Excel的表名,获取相应表的内容
      ///
      /// Excel的表名
      /// Excel路径
      ///
      public static DataTable GetExcelTable(string tableName,string path)
      {
            var sql = string.Format("SELECT * FROM [{0}]", tableName);
            var conn = GetConnection(path);
            var myCommand = new OleDbDataAdapter(sql, conn);
            var myDataSet = new DataSet();
            myCommand.Fill(myDataSet);
            return myDataSet.Tables;
      }
    }
}  
页: [1]
查看完整版本: 用C#如何将Excel导入到SQL Server