0

我们如何从 Excel 或 Access 文件中导出或导入数据到 Datagridview?我需要知道导出和导入的代码..请任何人帮助

4

2 回答 2

1

尝试这个:

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();
        }
    }
}

这是另一个教程 或只是使用谷歌

于 2012-09-04T05:49:55.877 回答
0

我将尝试使用Access示例扩展之前的帖子:

    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();
    }
}
}

希望这有帮助。

于 2014-04-03T19:01:51.170 回答