C#NPOI.Excel将EXCEL数据转换到dataGridView中
时间: 2024-02-06 08:11:40 浏览: 152
可以使用C#中的NPOI库和DataGridView控件来将Excel数据转换并显示在DataGridView中。下面是一个示例代码:
```csharp
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.Windows.Forms;
public static class ExcelUtility
{
public static void ExcelToDataGridView(string filePath, DataGridView dataGridView)
{
IWorkbook workbook = null;
ISheet sheet = null;
DataTable data = new DataTable();
using (var file = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
if (filePath.EndsWith(".xls"))
{
workbook = new HSSFWorkbook(file);
}
else if (filePath.EndsWith(".xlsx"))
{
workbook = new XSSFWorkbook(file);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt(0);
if (sheet != null)
{
var firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum;
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
var cell = firstRow.GetCell(i);
if (cell != null)
{
string columnName = cell.ToString();
if (!string.IsNullOrEmpty(columnName))
{
data.Columns.Add(columnName);
}
}
}
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; ++i)
{
var row = sheet.GetRow(i);
if (row != null)
{
bool emptyRow = true;
DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
if (!string.IsNullOrEmpty(dataRow[j].ToString()))
{
emptyRow = false;
}
}
}
if (!emptyRow)
{
data.Rows.Add(dataRow);
}
}
}
}
}
}
dataGridView.DataSource = data;
}
}
```
这段代码会根据文件路径读取Excel文件,将第一个工作表转换为一个DataTable对象,并将该对象作为DataGridView控件的DataSource来显示Excel数据。你只需要将DataGridView控件添加到窗体中即可。
阅读全文