c#怎么把excel表格数据读取datagridview
思路 是是先把 exce 表内数据 读取到 system.DataTable
再 绑定到 datagridview
Excel 转 system.DataTable 方法如下(需要引入NPOI)dll见附件 部分代码:
public static DataTable ConvertToDataTable(System.IO.Stream excelFileStream)
{
HSSFWorkbook HSSFWorkbook = new HSSFWorkbook(excelFileStream);
DataTable dt = new DataTable();
HSSFSheet sheet = (HSSFSheet)HSSFWorkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
int n = 0;
while (rows.MoveNext())
{
HSSFRow row = (HSSFRow)rows.Current;
if (n == 0)
{
for (int i = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = (HSSFCell)row.GetCell(i);
if (cell == null)
continue;
DataColumn column = new DataColumn(cell.StringCellValue);
dt.Columns.Add(column);
}
}
else
{
DataRow dtRow = dt.NewRow();
string rValue = "";
for (int i = 0, j = 0; i < row.LastCellNum; i++)
{
HSSFCell cell = (HSSFCell)row.GetCell(i);
if (cell == null)
{
dtRow[i] = "";
}
else
{
dtRow[j] = cell.ToString();
rValue = cell.ToString();
j++;
}
}
if (string.IsNullOrEmpty(rValue.Trim()))
break;
dt.Rows.Add(dtRow);
}
n++;
}
return dt;
}