如何将Excel多个工作表导入SQL服务器 [英] How to import excel multiples sheet in to SQL server

查看:115
本文介绍了如何将Excel多个工作表导入SQL服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约20个文件,所有文件都有20张或更多张。我需要从表中的所有工作表中导入特定数据(与表格相同的列)。我的代码只导入一张表。如何导入多张床单?以及如何从Excel中导入特定单元格?。我已经阅读了很多问题,但没有人做我需要的,而且大部分都是旧的



数据库SQL服务器



我希望你帮助我。我是新手。



我尝试了什么:



< pre> public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(HttpPostedFileBase postedFile)
{
string filePath = string.Empty;
if(postedFile!= null)
{
string path = Server.MapPath(〜/ Uploads /);
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}

filePath = path + Path.GetFileName(postedFile.FileName);
string extension = Path.GetExtension(postedFile.FileName);
postedFile.SaveAs(filePath);

string conString = string.Empty;
开关(分机)
{
case.xls:// Excel 97-03。
conString = ConfigurationManager.ConnectionStrings [Excel03ConString]。ConnectionString;
休息;
case.xlsx:// Excel 07及以上版本。
conString = ConfigurationManager.ConnectionStrings [Excel07ConString]。ConnectionString;
休息;
}

DataTable dt = new DataTable();
conString = string.Format(conString,filePath);

使用(OleDbConnection connExcel = new OleDbConnection(conString))
{
using(OleDbCommand cmdExcel = new OleDbCommand())
{
using(OleDbDataAdapter) odaExcel = new OleDbDataAdapter())
{
cmdExcel.Connection = connExcel;

//获取First Sheet的名称。
connExcel.Open();
DataTable dtExcelSchema;
dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,null);
string sheetName = dtExcelSchema.Rows [0] [TABLE_NAME]。ToString();
connExcel.Close();

//从第一张纸上读取数据。
connExcel.Open();
cmdExcel.CommandText =SELECT * From [+ sheetName +];
odaExcel.SelectCommand = cmdExcel;
odaExcel.Fill(dt);
connExcel.Close();
}
}
}

conString = ConfigurationManager.ConnectionStrings [Constring]。ConnectionString;
using(SqlConnection con = new SqlConnection(conString))
{
using(SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
{
//设置数据库表名称。
sqlBulkCopy.DestinationTableName =dbo.Table_1;

// [可选]:将Excel列映射到数据库表
sqlBulkCopy.ColumnMappings.Add(Rut,Rut);
sqlBulkCopy.ColumnMappings.Add(Nombres,Nombres);
sqlBulkCopy.ColumnMappings.Add(Malla,Malla);

con.Open();
sqlBulkCopy.WriteToServer(dt);
con.Close();
}
}
}

return View();
}
}

解决方案

您需要做的就是遍历表格集合。 />


 DataRow [] sheetsToImport = dtExcelSchema.Rows; 
foreach (DataRow r in sheetsToImport)
{
string sheetName = r [ TABLE_NAME]。的ToString();
cmdExcel.CommandText = SELECT * From [ + sheetName + ];
// 这里导入说明!
}


I have about 20 files , all with 20 or more sheets. I need to import specific data from all sheets in tables (as the same columns as the table). My code only import one sheet. How to import multiple sheets? and How Import specific cells from Excel?.I have read many questions but none do what I need and the most are old

Database SQL SERver

I hope ur help me. Im newbie.

What I have tried:

<pre>public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(HttpPostedFileBase postedFile)
    {
        string filePath = string.Empty;
        if (postedFile != null)
        {
            string path = Server.MapPath("~/Uploads/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);

            string conString = string.Empty;
            switch (extension)
            {
                case ".xls": //Excel 97-03.
                    conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                    break;
                case ".xlsx": //Excel 07 and above.
                    conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                    break;
            }

            DataTable dt = new DataTable();
            conString = string.Format(conString, filePath);

            using (OleDbConnection connExcel = new OleDbConnection(conString))
            {
                using (OleDbCommand cmdExcel = new OleDbCommand())
                {
                    using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                    {
                        cmdExcel.Connection = connExcel;

                        //Get the name of First Sheet.
                        connExcel.Open();
                        DataTable dtExcelSchema;
                        dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                        string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                        connExcel.Close();

                        //Read Data from First Sheet.
                        connExcel.Open();
                        cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
                        odaExcel.SelectCommand = cmdExcel;
                        odaExcel.Fill(dt);
                        connExcel.Close();
                    }
                }
            }

            conString = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
            using (SqlConnection con = new SqlConnection(conString))
            {
                using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.Table_1";

                    //[OPTIONAL]: Map the Excel columns with that of the database table
                    sqlBulkCopy.ColumnMappings.Add("Rut", "Rut");
                    sqlBulkCopy.ColumnMappings.Add("Nombres", "Nombres");
                    sqlBulkCopy.ColumnMappings.Add("Malla", "Malla");

                    con.Open();
                    sqlBulkCopy.WriteToServer(dt);
                    con.Close();
                }
            }
        }

        return View();
    }
}

解决方案

All you need to do is to loop through the collection of sheets.

DataRow[] sheetsToImport = dtExcelSchema.Rows;
foreach(DataRow r in sheetsToImport)
{
    string sheetName = r["TABLE_NAME"].ToString();
    cmdExcel.CommandText = "SELECT * From [" + sheetName + "]";
    //import instructions here!
}


这篇关于如何将Excel多个工作表导入SQL服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆