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

时间:2014-02-10 07:08:34

标签: c# asp.net sql-server

如何将数据从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

3 个答案:

答案 0 :(得分:6)

将其分解为两个步骤:

1)将文件保存在某处 - 这很常见:

string saveFolder = @“C:\ temp \ uploads”; //在您的机器上选择一个文件夹来存储上传的文件

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

FileUpload1.SaveAs(文件路径); 现在,您可以在本地使用您的文件,并且可以完成真正的工作。

2)从文件中获取数据。您的代码应该按原样运行,但您可以通过这种方式编写连接字符串:

string excelConnString = String.Format(“Provider = Microsoft.Jet.OLEDB.4.0; Data Source = {0}; Extended Properties =”Excel 12.0“;”,filePath); 然后,您可以考虑删除刚刚上传和导入的文件。

为了提供更具体的示例,我们可以将您的代码重构为两种方法:

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;

}

然后你可以简单地调用SaveFileToDatabase(GetLocalFilePath(@“C:\ temp \ uploads”,FileUpload1));

考虑查看Excel连接字符串的其他扩展属性。它们很有用!

您可能想要进行的其他改进包括将Sql Database连接字符串放入config,并添加适当的异常处理。请将此示例仅用于演示!

答案 1 :(得分:1)

我们将创建一个方法数据表,在该表中我们将在数据表或数据集中获取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;
 }
 }
 }

答案 2 :(得分:-2)

添加一个DataTable,它可以保存通过OLEDb生成的Excel数据。

numbers in arr: [5, 5, null, 3, 6, null]
there are/is 0 ->0 times
there are/is 1 ->0 times 
there are/is 2 ->0 times 
there are/is 3 ->1 times 
there are/is 4 ->0 times 
there are/is 5 ->2 times 
there are/is 6 ->1 times

然后将此DataTable序列化为XML,可以将其发送到SQL Stored Proc。如果字段太多而您可以在一个参数

中发送所有字段,则此方法非常有用
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);
}
}