如何将Excel工作表插入sql server以及如何从中检索数据而不是整个Excel工作表?

时间:2013-10-10 07:14:19

标签: asp.net c#-4.0 sql-server-2005

嗨,我有一个500行的excel表,我想在服务器上上传那张表并将数据插入sqlserver,我创建了名为excel的表,其列与excel表相同,数据需要在上传excel表时存入此表,当我只想检索一行时我只想显示该行,怎么可能,请问任何人请告诉我?我不想使用ms访问和oledb连接,我在我的项目中使用过Sql server 2005 .. 我试过这样,请告诉我错误在哪里...........

protected void btnSend_Click(object sender, EventArgs e)
        {
            con.Open();
            String strConnection = "user id=sa;pssword=E@2013;Data Source=EKTHA-3D34;Initial Catalog=Ektha;Integrated Security=True";

                  string path = fileuploadExcel.PostedFile.FileName;
                         //Create connection string to Excel work book
                 // string excelConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";
                  string excelConnectionString = "user id=sa;password=E@2013;Data Source=EKTHA-3D34;Persist Security Info=False";
                     //Create Connection to Excel work book
                     SqlConnection excelConnection =new SqlConnection(excelConnectionString);
                      //Create OleDbCommand to fetch data from Excel
                      SqlCommand cmd = new SqlCommand("Select * from [Sheet1$]",excelConnection);
                     excelConnection.Open();
                      SqlDataReader dReader;
                        dReader = cmd.ExecuteReader();
                        SqlBulkCopy sqlBulk = new SqlBulkCopy(strConnection);
                       //Give your Destination table name
                        sqlBulk.DestinationTableName = "PayDescription";
                          sqlBulk.WriteToServer(dReader);
                         excelConnection.Close();
                         }

    }
}

1 个答案:

答案 0 :(得分:0)

你不需要那么挣扎。将第一行保留为表中所需的列。然后将excel表格转换为xls(97-2003)格式。右键单击数据库任务 - > import-> clickNext->选择datasource microsoft excel并将第一行检查为列。给next.confirm验证给下一个,接下来,在网格中你检查第二行并去编辑选择正确的数据类型。然后继续。该表是在数据库中导入的。只需根据需要重命名即可。