Import Data from Excel to Sql Server 2008 #2

bpsygsoo  于 2023-08-02  发布在  SQL Server
关注(0)|答案(4)|浏览(111)
string path = string.Concat(Server.MapPath("~/TempFiles/"), FileUpload1.FileName);
//Save File as Temp then you can delete it if you want 
FileUpload1.SaveAs(path);

string excelConnectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0", path);

// Create Connection to Excel Workbook 
using (OleDbConnection connection =
             new OleDbConnection(excelConnectionString))
{
    OleDbCommand command = new OleDbCommand
            ("Select * FROM [Sheet1$]", connection);

    connection.Open();

    // Create DbDataReader to Data Worksheet 
    using (DbDataReader dr = command.ExecuteReader())
    {

        // SQL Server Connection String 
        string sqlConnectionString = @conn;

        // Bulk Copy to SQL Server 
        using (SqlBulkCopy bulkCopy =
                   new SqlBulkCopy(sqlConnectionString))
        {
            bulkCopy.DestinationTableName ="Table1";
            bulkCopy.WriteToServer(dr);
            Label1.Text = "The Client data has been exported successfully from Excel to SQL";
        }
    }
}

I am trying to import data from excel to SQL Server, it works fine till I am not passing date but now I want to pass the date to SQL Server it provides error as datatype not matches.

Anyone has logic or please suggest me what can I do to ..

c9x0cxw0

c9x0cxw01#

Might be the column in the Excel Sheet is not in a valid date format.

Change it to Date Type.

Select the Column in the Excel Sheet -> Right Click -> Format Cells ->
Number Tab -> Select Date -> Choose your desired Type -> Ok

Then you try to Import...

3mpgtkmj

3mpgtkmj2#

The DateTime you read from excel is OLE Automation date and you have to convert it to c# DateTime before you insert in to sql server. It would be double value for date when you read from excel. You can use DateTime.FromOADate to convert the double value to DateTime . You can use SqlBulkCopy.WriteToServer(DataTable table) , this method allows you to pass the datatable. You can change the date in datatable in require format and use it to save bulk data in sql server. You can import excel data to datatable, this article will help you.

DateTime dt = DateTime.FromOADate(double.Parse(stringVariableContainingDateTime));
gdx19jrr

gdx19jrr3#

It works i tried to convert it in datatble den change datatype and then insert

string sqlConnectionString = @conn;
command.CommandType = CommandType.Text;
                OleDbDataAdapter objAdapter1 = new OleDbDataAdapter(command);
                DataTable dt = new DataTable();
                DataSet objDataset1 = new DataSet();

                objAdapter1.Fill(dt);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    if (dt.Rows[0][5].ToString() != "")
                    {
                        DateTime dt1 = cf.texttodb(dt.Rows[0][5].ToString());
                        dt.Rows[i][5] = dt1;
                    }}
 using (SqlBulkCopy bulkCopy =
                               new SqlBulkCopy(sqlConnectionString))
                {
                    bulkCopy.DestinationTableName = "Tablename";
                    bulkCopy.WriteToServer(dt);
                    Label1.Text = "The Client data has been exported successfully from Excel to SQL";
                }

in this i had created a function txtdob which converts my string to datetime format Thank you i tried it workes if u feel so mark it as answer

cngwdvgl

cngwdvgl4#

Using  Web form  ..

using System;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

public partial class YourPageName : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string excelFilePath = Server.MapPath("~/Uploads/") + FileUpload1.FileName;
            FileUpload1.SaveAs(excelFilePath);
            ImportDataFromExcel(excelFilePath);
        }
    }

    public void ImportDataFromExcel(string excelFilePath)
    {`enter code here`
        string ssqltable = TextBox1.Text;
        string myexceldataquery = "select * from [Sheet1$]";
        try
        {
            string sexcelconnectionstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties='Excel 12.0 Xml;HDR=YES;IMEX=1;'";
            string ssqlconnectionstring = "Data Source=95.217.196.125;Initial Catalog=Test;Persist Security Info=True;User ID=sa;Password=Dup(e)0@98!";
            string sclearsql = "DELETE FROM " + ssqltable;

            using (SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring))
            {
                sqlconn.Open();

                using (SqlCommand sqlcmd = new SqlCommand(sclearsql, sqlconn))
                {
                    sqlcmd.ExecuteNonQuery();
                }
            }

            using (OleDbConnection oledbconn = new OleDbConnection(sexcelconnectionstring))
            {
                oledbconn.Open();

                using (OleDbCommand oledbcmd = new OleDbCommand(myexceldataquery, oledbconn))
                {
                    using (OleDbDataReader dr = oledbcmd.ExecuteReader())
                    {
                        using (SqlConnection sqlconn = new SqlConnection(ssqlconnectionstring))
                        {
                            sqlconn.Open();

                            using (SqlBulkCopy bulkcopy = new SqlBulkCopy(sqlconn))
                            {
                                bulkcopy.DestinationTableName = ssqltable;
                                bulkcopy.WriteToServer(dr);
                            }
                        }
                    }
                }
            }

            Label1.Text = "File imported into SQL Server successfully.";
        }
        catch (Exception ex)
        {
            // Handle exception
        }
    }
}

相关问题