0
我們如何從Excel或Access文件導出或導入數據到Datagridview? 我需要知道出口的代碼和import..any一個幫助,請Datagrid在C#winform中查看
我們如何從Excel或Access文件導出或導入數據到Datagridview? 我需要知道出口的代碼和import..any一個幫助,請Datagrid在C#winform中查看
試試這個:
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}
我會盡量延長以前的帖子用訪問樣本:
DataTable LoadSchemaFromAccess(string szFilePath)
{
System.Data.OleDb.OleDbCommand cmd;
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection(string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szFilePath));
cnn.Open();
System.Data.DataTable schemaTable = cnn.GetSchema("Tables");
cnn.Close();
return schemaTable;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
string LoadDataFromAccess(string szTableName)
{
string GetData = L"SELECT * FROM " + szTableName;
System.Data.OleDb.OleDbCommand cmd;
string szColumns = "";
try
{
System.Data.OleDb.OleDbConnection cnn = new System.Data.OleDb.OleDbConnection
(string.Format(L"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Persist Security Info=False;", szPath));
cnn.Open();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = cnn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = GetData;
OleDbDataAdapter adt = new OleDbDataAdapter(cmd);
adt.SelectCommand = cmd;
adt.Fill(dt);
cnn.Close();
return dt;
}
catch (exception e)
{
MessageBox.Show(e.Message);
return null;
}
finally
{
if (cmd != null)
{
cmd.Dispose();
}
}
}
希望日是有幫助的。
如果你需要代碼,你可以做谷歌。如果您在代碼中遇到特定問題需要幫助,請尋求幫助。如果你還沒有嘗試過任何東西,我想別人很難幫助你。 –
我很驚訝這個問題是如何提高的 – Habib