需要通过class / Method传递连接

时间:2016-12-21 21:21:54

标签: c# .net sql-server excel

我必须将excel导入SQL db。我已经在上传按钮上写了如下所有代码。

但是我必须单独编写一个类/方法,而不是在按钮点击时编写任何sql。

请帮助我,我是编程新手

我的总代码:

private void SaveFileToDatabase(string filePath)
{
    if (Path.GetExtension(filePath) == ".xls")
    {
        excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties=\"Excel 12.0\"", filePath);
    }
    else if (Path.GetExtension(filePath) == ".xlsx")
    {
        excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0}; Extended Properties='Excel 12.0 Xml'", filePath);
    }

    // Importing a file data to Database

    // Create Connection to Excel work book 
    OleDbConnection Oledbconn = new OleDbConnection(excelConnString);
    OleDbCommand cmd = new OleDbCommand();
    cmd.Connection = Oledbconn;
    OleDbDataAdapter da = new OleDbDataAdapter(cmd);
    Oledbconn.Open();
    DataTable dtSheet = Oledbconn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    Oledbconn.Close();

    // iterate each sheet
    foreach (System.Data.DataRow sheet in dtSheet.Rows)
    {
        Oledbconn.Open();
        DataTable dt = new DataTable();
        string sheetName = sheet["table_name"].ToString();
        cmd.CommandText = "select * from [" + sheetName + "]";
        da.SelectCommand = cmd;
        da.Fill(dt);
        ISqlMapper sqlMapper = ApplicationContainer.Current.Resolve<ISqlMapper>("StageDB");
        ISqlMapSession SqlMapSession = sqlMapper.OpenConnection();
        SqlMapSession.Connection.Open();

        using (SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlMapSession.Connection.ConnectionString))
        {
            // Destination table name.  Table name is sheet name minus any $
            sqlBulk.DestinationTableName = sheetName.Replace("$", "");
            foreach (var column in dt.Columns)
            {
                sqlBulk.ColumnMappings.Add(column.ToString(), column.ToString());
            }
            sqlBulk.WriteToServer(dt);
        }
        Oledbconn.Close();
        sqlMapper.CloseConnection();
    }

**The code which I have to make a class and just callhere:**

    ISqlMapper sqlMapper = ApplicationContainer.Current.Resolve<ISqlMapper>("StageDB");
    ISqlMapSession SqlMapSession = sqlMapper.OpenConnection();
    SqlMapSession.Connection.Open();
    using (SqlBulkCopy sqlBulk = new SqlBulkCopy(SqlMapSession.Connection.ConnectionString))
    {
        // Destination table name.  Table name is sheet name minus any $
        sqlBulk.DestinationTableName = sheetName.Replace("$", "");
        foreach (var column in dt.Columns)
        {
            sqlBulk.ColumnMappings.Add(column.ToString(), column.ToString());
        }
        sqlBulk.WriteToServer(dt);
    }
    Oledbconn.Close();
    sqlMapper.CloseConnection();
}

1 个答案:

答案 0 :(得分:0)

在将数据批量插入SQL Server时,使用与SQL命令关联的DbDataReader对象取得了很大成功。我已经在源数据是许多不同的DBMS平台的地方使用过它。不可否认,我从来没有用电子表格作为来源,但我没有看到任何理由不起作用。

这是未经测试的,但它应该让你在很大程度上:

OleDbConnection Oledbconn = new OleDbConnection(excelConnString);
Oledbconn.Open();
OleDbCommand cmd = new OleDbCommand("select * from [" + sheetName + "]", Oledbconn);
OleDbDataReader reader = cmd.ExecuteReader();

SqlConnection conn = new SqlConnection(connectionString);
conn.Open();
SqlBulkCopy copy = new SqlBulkCopy(conn);
copy.BulkCopyTimeout = 120000;
copy.DestinationTableName = "MyTable";

// presupposes the columns line up, as they do in your example

for (int i = 0; i < reader.FieldCount; i++)
    copy.ColumnMappings.Add(reader.GetName(i), reader.GetName(i));

copy.WriteToServer(reader);

reader.Close();
conn.Close();
Oledbconn.Close();