简体   繁体   English

将数据从 Excel 工作表导入 SQL Server 数据库

[英]Import data from an Excel sheet into a SQL Server database

How to import the data from an Excel sheet into SQL Server database in asp net?如何将Excel工作表中的数据导入asp net中的SQL Server数据库?

Dim OleDbcon As New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & path) + ";Extended Properties=Excel 12.0;")

Dim cmd As New OleDbCommand("SELECT * FROM [Sheet1$]", OleDbcon)
Dim objAdapter1 As New OleDbDataAdapter(cmd)

OleDbcon.Open()
Dim dr As DbDataReader = cmd.ExecuteReader()

Dim con_str As String = "Data Source=.;Initial Catalog=studentdetails;Integrated Security=True"

' Bulk Copy to SQL Server 
Dim bulkInsert As New SqlBulkCopy(con_str)
bulkInsert.DestinationTableName = "Table name"
bulkInsert.WriteToServer(dr)
OleDbcon.Close()e here

Break this down into two steps:将其分解为两个步骤:

1) Save the file somewhere - it's very common to see this: 1)将文件保存在某处 - 看到这个很常见:

string saveFolder = @"C:\\temp\\uploads"; string saveFolder = @"C:\\temp\\uploads"; //Pick a folder on your machine to store the uploaded files //在你的机器上选择一个文件夹来存放上传的文件

string filePath = Path.Combine(saveFolder, FileUpload1.FileName); string filePath = Path.Combine(saveFolder, FileUpload1.FileName);

FileUpload1.SaveAs(filePath); FileUpload1.SaveAs(filePath); Now you have your file locally and the real work can be done.现在您在本地拥有您的文件并且可以完成真正的工作。

2) Get the data from the file. 2)从文件中获取数据。 Your code should work as is but you can simply write your connection string this way:您的代码应该按原样工作,但您可以简单地以这种方式编写连接字符串:

string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath); string excelConnString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties="Excel 12.0";", filePath); You can then think about deleting the file you've just uploaded and imported.然后您可以考虑删除您刚刚上传和导入的文件。

To provide a more concrete example, we can refactor your code into two methods:为了提供更具体的示例,我们可以将您的代码重构为两种方法:

private void SaveFileToDatabase(string filePath)
{
    String strConnection = "Data Source=.\\SQLEXPRESS;AttachDbFilename='C:\\Users\\Hemant\\documents\\visual studio 2010\\Projects\\CRMdata\\CRMdata\\App_Data\\Database1.mdf';Integrated Security=True;User Instance=True";

    String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);
    //Create Connection to Excel work book 
    using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
    {
        //Create OleDbCommand to fetch data from Excel 
        using (OleDbCommand cmd = new OleDbCommand("Select [ID],[Name],[Designation] from [Sheet1$]", excelConnection))
        {
            excelConnection.Open();
            using (OleDbDataReader dReader = cmd.ExecuteReader())
            {
                using(SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection))
                {
                    //Give your Destination table name 
                    sqlBulk.DestinationTableName = "Excel_table";
                    sqlBulk.WriteToServer(dReader);
                }
            }
        }
    } 
}


private string GetLocalFilePath(string saveDirectory, FileUpload fileUploadControl)
{


    string filePath = Path.Combine(saveDirectory, fileUploadControl.FileName);

    fileUploadControl.SaveAs(filePath);

    return filePath;

}

You could simply then call SaveFileToDatabase(GetLocalFilePath(@"C:\\temp\\uploads", FileUpload1));然后你可以简单地调用 SaveFileToDatabase(GetLocalFilePath(@"C:\\temp\\uploads", FileUpload1));

Consider reviewing the other Extended Properties for your Excel connection string.考虑查看 Excel 连接字符串的其他扩展属性。 They come in useful!他们来有用!

Other improvements you might want to make include putting your Sql Database connection string into config, and adding proper exception handling.您可能想要进行的其他改进包括将 Sql 数据库连接字符串放入配置,并添加适当的异常处理。 Please consider this example for demonstration only!请考虑此示例仅用于演示!

we will create a method data table in which we will take excel sheet info in data table or data set after that we will push that data into SQL database table using SQL bulk我们将创建一个方法数据表,我们将在其中获取数据表或数据集中的 Excel 表信息,然后我们将使用 SQL 批量将该数据推送到 SQL 数据库表中

protected void Button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(@"Data 
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated 
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
 for()
}
}
catch(Exception ex)
{
Response.Write(ex);
}
}
protected void Button2_Click(object sender, EventArgs e)
{
try
{
SqlConnection con = new SqlConnection(@"Data 
Source=SANI2711\SQLEXPRESS;Initial Catalog=customer;Integrated 
Security=True;");
con.Open();
DataTable dt = new DataTable();
dt = DataExcel();
if (dt.Rows.Count > 0)
{
 SqlBulkCopy objbulk = new SqlBulkCopy(con);
 objbulk.DestinationTableName = "customer1";
 objbulk.ColumnMappings.Add("CustomerID", "CustomerID");
 objbulk.ColumnMappings.Add("City", "City");
 objbulk.ColumnMappings.Add("Country", "Country");
  objbulk.ColumnMappings.Add("PostalCode", "PostalCode");
  objbulk.WriteToServer(dt);
  }
 }
 catch (Exception ex)
 {
 Response.Write(ex);
 }
 }
 protected DataTable DataExcel()
 {
 DataTable dt = new System.Data.DataTable();
 try
 {
 string filenname=@"C:\Users\sani singh\Documents\Excel03.xls";
string sWorkbook = "[Sheet1$]";
 string ExcelConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;Data 
Source="+filenname+";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
 OleDbConnection OleDbConn = new OleDbConnection(ExcelConnectionString);
 OleDbConn.Open();
 OleDbCommand OleDbCmd = new OleDbCommand(("SELECT * FROM " + sWorkbook), 
 OleDbConn);
 DataSet ds = new DataSet();
 OleDbDataAdapter sda = new OleDbDataAdapter(OleDbCmd);
 sda.Fill(ds);
 dt = ds.Tables[0];
 OleDbConn.Close();
 }
 catch(Exception ex) 
 {
 Response.Write(ex);
 }
 return dt;
 }
 }
 }

Add a DataTable which can hold the Excel data generated via OLEDb.添加一个 DataTable,它可以保存通过 OLEDb 生成的 Excel 数据。

string excelconnectionstring = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelfilepath + ";Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text;Jet OLEDB:Max Buffer Size=256;");

using (OleDbConnection oledbconn = new OleDbConnection(excelconnectionstring))
  {
                    using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
                    {
                        oledbconn.Open();
                        OleDbDataReader dr = oledbcmd.ExecuteReader();


                        dtBulkUpload.Load(dr);
}
}

Then serialize this DataTable to XML which can be sent to SQL Stored Proc.然后将此数据表序列化为可发送到 SQL 存储过程的 XML。 This approach is very useful if there are too many fields and you can send all in a single parameter如果字段太多并且您可以在单个参数中发送所有字段,则此方法非常有用

using (StringWriter strXML = new StringWriter())
{
   dtBulkUpload.TableName = "BulkUpload";
   dtBulkUpload.WriteXml(strXML, XmlWriteMode.IgnoreSchema, false);
   xmlString = strXML.ToString();
}                                     



using (SqlCommand cmd = new SqlCommand("Stored PROC Name"))
{
   cmd.Parameters.AddWithValue("@dtBulkUpload", bulkUploadData);
                        //SqlParameter returnParameter = cmd.Parameters.Add("@result", SqlDbType.NVarChar);
                        //returnParameter.Direction = ParameterDirection.Output;
                        cmd.Parameters.Add("@result", SqlDbType.NVarChar,3000);
                        cmd.Parameters["@result"].Direction = ParameterDirection.Output;

                        cmd.Connection = con;
                        cmd.CommandType = CommandType.StoredProcedure;

                        con.Open();
                        cmd.ExecuteNonQuery();
                        query = (string)(cmd.Parameters["@result"].Value.ToString());
                        con.Close();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM