(1)建立窗体应用项目
(2)安装NPOI.选择项目并右键单击
(3)搜索NOPI,并安装
(4)在设计窗口处放上Button, Textbox, dataGridView三个控件,Name分别为button1, textbox1, dataGridView1
(5) 添加命名空间
(7)下载Access数据连接引擎,并安装。(略过这步会提示:未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序)
链接:https://pan.baidu.com/s/1–wOV8fTBlVIOSw8I6CeYg
提取码:6pay
(8)完整代码如下。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.IO;
using System.Data.OleDb;
namespace MySystem
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.Load += new EventHandler(Form1_Load);//Form1_Load事件注册
}
//读取Excel文件
private void ReadFromExcelFile(string filePath)
{
//创建读取对象
IWorkbook wk = null;
//获取指定的路径文件的扩展名
string extension = System.IO.Path.GetExtension(filePath);
//根据不同的扩展名创建不同的对象
try
{
FileStream fs = File.OpenRead(filePath);
if(extension.Equals(".xls"))
{
//把xls文件中的数据写入wk中
wk = new HSSFWorkbook(fs);
}
else
{
//把xlsx文件中的数据写入wk中
wk = new XSSFWorkbook(fs);
}
fs.Close();
ISheet sheet = wk.GetSheetAt(0); //读取第一个表
IRow row = sheet.GetRow(0); //定义行变量并初始化为第一个行
double[,] arry = new double[100,100]; //定义DOUBLE数组,用来保存读到的数据
for (int i = 1; i <= sheet.LastRowNum; i++)//略过第一行表头,开始存储到数组中, //LastRowNum 是当前表的总行数-1
{
row = sheet.GetRow(i); //读取当前行数据
if (row != null)
{
for (int j = 0; j < row.LastCellNum; j++) //LastCellNum 是当前行的总列数
{
string value = row.GetCell(j).ToString(); //读取该行的第j列数据
arry[i, j] = Convert.ToDouble(value);
}
}
}
//textBox2.Text = arry[3, 2].ToString();//测试无误,数组数据正确,第三行是表格除去表头的第三行。第2列是除去第一列开始的第二列
}catch(Exception e)
{
MessageBox.Show(e.Message);//捕捉异常
}
}
//将EXCEL文件显示到Datagridview上
private DataTable ReadFromExcel(string excelPath)
{
string extension = System.IO.Path.GetExtension(excelPath);
string sConn = null;
if(extension == ".xlsx")
{
sConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + excelPath + ";" + "Extended Properties='Excel 12.0;HDR=YES'";
}
else if(extension == ".xls")
{
sConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + excelPath + ";" + "Extended Properties=Excel 8.0";
}
else
{
throw new Exception("文件类型不对,请核对信息");
}
OleDbConnection oledbConn = new OleDbConnection(sConn);
oledbConn.Open();
OleDbDataAdapter command = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", oledbConn);
DataSet ds = new DataSet();
command.Fill(ds);
oledbConn.Close();
return ds.Tables[0];
}
private void button1_Click(object sender, EventArgs e)//button事件点击
{
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "c# Corner Open File Dialog";
fdlg.InitialDirectory = @"c:\";
fdlg.Filter = "All files(*.*)|*.*|All files(*.*)|*.* "; //*FileterIndex属性用于选择了何种文件类型,缺省设置为0,系统取Fileter属性设置第一项
//* 相当于FileterIndex属性设置为1,如果你编了3个文件类型,当FileterIndex = 2 时是指第2个。
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
//如果值为false,那么下一次选择文件的初识目录是上一次你选择的那个目录,不固定;如果值为true,每次打开这个对话框初识目录
//不随你的选择而改变,是固定的
string Path = "";//设置文件路径
if(fdlg.ShowDialog() == DialogResult.OK)
{
Path = System.IO.Path.GetFullPath(fdlg.FileName);//获取文件完整路径
textBox1.Text = Path;
//将EXCEL数据显示到Datagridview,调用ReadFromExcel函数
dataGridView1.DataSource = ReadFromExcel(Path);
}
//调用读取Excel文件函数
ReadFromExcelFile(Path);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
(9)程序运行结果。
测试Excel文件名为data.xlsx,其中的数据是这样的:
点击“选择数据文件”,选择data.xlsx文件,并确定。
测试成功!