C#winform中的Datagridview

时间:2012-09-04 05:29:21

标签: c#

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

2 个答案:

答案 0 :(得分: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();
        }
    }
}

Here is another tutorial 或者只使用google

答案 1 :(得分:0)

我将尝试使用访问示例扩展上一篇文章:

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

希望这会有所帮助。