转载自:http://blog.csdn.net/zhangnan20100811/article/details/6458158
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ReadExcel07
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnPopulate_Click(object sender, EventArgs e)
{
// You can change C:/Members.xlsx to any path where
// the file is located.
string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:/Members.xlsx;Extended Properties=""Excel 12.0;HDR=YES;""";
// if you don't want to show the header row (first row)
// use 'HDR=NO' in the string
string strSQL = "SELECT * FROM [Sheet1$]";
OleDbConnection excelConnection = new OleDbConnection(connectionString);
excelConnection.Open(); // This code will open excel file.
OleDbCommand dbCommand = new OleDbCommand(strSQL, excelConnection);
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(dbCommand);
// create data table
DataTable dTable = new DataTable();
dataAdapter.Fill(dTable);
// bind the datasource
dataBingingSrc.DataSource = dTable;
// assign the dataBindingSrc to the DataGridView
dgvExcelList.DataSource = dataBingingSrc;
// dispose used objects
dTable.Dispose();
dataAdapter.Dispose();
dbCommand.Dispose();
excelConnection.Close();
excelConnection.Dispose();
}
}
}
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ReadExcel07
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}