1.需先下载相关dll档
NPOI.dll,NPOI.OOXML.dll,NPOI.OpenXml4Net.dll,NPOI.OpenXmlFormats.dll,ICSharpCode.SharpZipLib.dll
2.新建一个winform项目,将所读到的EXCEL内容放入datagridView中
3.项目当中添加引用
4.这边有在app.config中设定一个参数去控制是否设定excel中第一行为datagridView的列标题
配置档设定
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="isColumnName" value="Y"/> <!--是否设定第一行为列标题-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
读取app.config设定
//读取app.config
public static string GetConfig(string key)
{
string _value = string.Empty;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
_value = config.AppSettings.Settings[key].Value;
}
return _value;
}
5.程序主逻辑
namespace Excel_read
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btn_path_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "选择excel";
fileDialog.Filter = "(*.xlsx)|*.xlsx|(*.xls)|*.xls";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
lbl_path.Text = fileDialog.FileName;
}
}
private void btn_read_Click(object sender, EventArgs e)
{
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null; //接收打开的excel文档
ISheet sheet = null; //接收打开的excel文档中的sheet
IRow row = null;
ICell cell = null;
int startRows = 0; //从第几行开始
string isColumnName = GetConfig("isColumnName");
try
{
using (FileStream fs = new FileStream(lbl_path.Text,FileMode.Open))
{
if (lbl_path.Text.IndexOf("xlsx") > 0)
{
workbook = new XSSFWorkbook(fs);
}
else
{
workbook = new HSSFWorkbook(fs);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt(0); //这里指的是读取打开excel的第几个sheet
DataTable datatable = new DataTable();
if (sheet != null)
{
int row_num = sheet.LastRowNum; //选取的sheet中数据行数
if (row_num > 0 )
{
IRow firstRow = sheet.GetRow(0); //第一行
int col_num = firstRow.LastCellNum; //第一行的总列数
if (isColumnName == "Y")
{
startRows = 1;
for (int i = firstRow.FirstCellNum; i < col_num; i++)//利用循环设定列名
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
datatable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < col_num; i++)
{
column = new DataColumn("column" + (i + 1));
datatable.Columns.Add(column);
}
}
for (int i = startRows; i <= row_num; i++)
{
row = sheet.GetRow(i);
if (row == null)
{
continue;
}
dataRow = datatable.NewRow();
for (int j = row.FirstCellNum; j < col_num; j++)
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.String:
dataRow[j] = cell.StringCellValue;
break;
case CellType.Numeric:
dataRow[j] = cell.NumericCellValue;
break;
}
}
}
datatable.Rows.Add(dataRow);
dataGridView1.DataSource = datatable;
}
}
}
}
}
}
catch (Exception ex)
{
string msg = ex.ToString();
MessageBox.Show(msg);
}
}
//读取app.config
public static string GetConfig(string key)
{
string _value = string.Empty;
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings[key] != null)
{
_value = config.AppSettings.Settings[key].Value;
}
return _value;
}
}
}
6.实现效果
excel文档内容
7.借鉴链接
C#中NPOI操作excel之读取和写入excel数据