引用:
using System.Data.OleDb;
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
using DataTable = System.Data.DataTable;
事件方法:
private void GetDataFromExcel(DataGridView dv)
{
Excel.Workbook wb;
Excel.Worksheet ws;
Excel.Application excel = new Excel.Application();//实例化
openFileDialog1.Title = "选择Excel文件:";
openFileDialog1.Filter = "Excel2007+ files (*.xlsx)|*.xlsx";
openFileDialog1.Multiselect = false;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (File.Exists(openFileDialog1.FileName))
{
wb = excel.Workbooks.Open(openFileDialog1.FileName);
ws = wb.Worksheets["sheet1"];
int rcount = ws.Range["A" + ws.Range["A:A"].Rows.Count].End[Excel.XlDirection.xlUp].Row;
int ccount = ((Excel.Range)ws.Cells[1, ws.Range["1:1"].Columns.Count].End[Excel.XlDirection.xlToLeft]).Column;
//System.Diagnostics.Debug.Write(rcount.ToString() + "||数据1" + ccount);
dv.ColumnCount = ccount;//确定列数
dv.ColumnHeadersVisible = true;
for (int i = 2; i <= rcount + 1; i++)
{
if (dv.RowCount <= i - 1)
{
if (ws.Cells[i, 1].value != null)//判断是否为空值
{
for (int j = 0; j <= ccount - 1; j++)
{
dv.Columns[j].Name = ws.Cells[1, j + 1].value; //添加表头
}
int index = dv.Rows.Add();
dv.Rows[index].Cells[0].Value = ws.Cells[i, 1].value;//第一列数据
dv.Rows[index].Cells[1].Value = ws.Cells[i, 2].value;//第一列数据
dv.Rows[index].Cells[2].Value = ws.Cells[i, 3].value;//第一列数据
}
}
}
MessageBox.Show("数据导入成功", "导入提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
wb.Close();
excel.Quit();
}
}
}
事件方法调用:
GetDataFromExcel(dataGridView1);
PS:这个比较简单,比网上很多大神弯弯绕的要要简明易懂;
记得一定要添加引入:
Microsoft.Office.Interop.Excel