以特定方式将Excel导入到datagridview [英] Import excel to datagridview in a specific manner
问题描述
我正在开发一个应用程序,我需要将excel导入到datagridview.我在google上搜索,知道将Excel导入到数据集然后填充dataadapter并绑定到datagridview的正常方法,但是我想以一种方式导入,使得excel中的每一列都是我的datagridview中的一行,任何人都可以帮助我
在此先感谢
Hi I am in the development of an application where I need to import excel to datagridview. I serached in google and came know the normal way of importing the excel to dataset and then filling the dataadapter and binding to datagridview, but I want to import in such a way that each column in excel is a row in my datagridview can anyone help me
Thanks in advance
推荐答案
public void Exel2Sql()
{
OdbcConnection connection;
SqlBulkCopy bulkCopy;
string ConnectionString = @"server="servername";database=" ";uid=" ";pwd=" ";";
//Use your SQL servername ,userID and Password.
string connstr = @"Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=filepath";
using (connection = new OdbcConnection(connstr))
{
OdbcCommand command = new OdbcCommand("Select * FROM [Sheet1
",连接); // 您可以使用工作表名称更改[Sheet1
", connection); //you can change [Sheet1
connection.Open(); // 创建DbDataReader到数据工作表 使用(OdbcDataReader dr = command.ExecuteReader()) { // 批量复制到SQL Server 使用(bulkCopy = 新 SqlBulkCopy(ConnectionString)) { bulkCopy.DestinationTableName = " ; // 名称"是要在其中复制所有数据的sql表. bulkCopy.WriteToServer(dr); } dr.Close(); } } bulkCopy.Close(); connection.Close(); }
with your sheet name connection.Open(); // Create DbDataReader to Data Worksheet using (OdbcDataReader dr = command.ExecuteReader()) { // Bulk Copy to SQL Server using (bulkCopy = new SqlBulkCopy(ConnectionString)) { bulkCopy.DestinationTableName = "Names"; //"Names" is the sql table where you want to copy all data. bulkCopy.WriteToServer(dr); } dr.Close(); } } bulkCopy.Close(); connection.Close(); }
使用此代码将数据从excel移动到SQL,然后将数据绑定到gridview中.
希望对您有帮助.
Use this code to move the data from excel to SQL and then bind the data in gridview .
Hope this helps you.
这篇关于以特定方式将Excel导入到datagridview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!