上传者: learn_change_myself
|
上传时间: 2022-01-17 19:07:00
|
文件大小: 1.3MB
|
文件类型: -
引用之后,使用该方法读取excel文件
#region 读取Excel
public static DataTable ImportExcel(string filePath)
{
try
{
//根据路径通过已存在的excel来创建HSSFWorkbook,即整个excel文档
FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
//判断文件后缀名是xls,还是xlsx,如果是xls,使用HSSFWorkbook;如果是xlsx,使用XSSFWorkbook
XSSFWorkbook workbook = new XSSFWorkbook(file);
//获取excel的第一个sheet
ISheet sheet = workbook.GetSheetAt(0);
DataTable table = new DataTable();
//获取sheet的首行
IRow headerRow = sheet.GetRow(0);
if (headerRow == null)
headerRow = sheet.GetRow(1);
//一行最后一个方格的编号 即总的列数
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
ICell cell = headerRow.GetCell(i);
if (cell != null)
{
DataColumn column = new DataColumn(cell.StringCellValue);
table.Columns.Add(column);
}
}
//最后一列的标号 即总的行数
// int rowCount = sheet.LastRowNum;
cellCount = table.Columns.Count;
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null)
continue;
DataRow dataRow = table.NewRow();
bool isAdd = false;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) == null)
continue;
//row.GetCell(j).SetCellType(CellType.STRING);
if (row.GetCell(j) != null)
{
if (row.GetCell(j).CellType == CellType.NUMERIC)
dataRow[j] = (int)(row.GetCell(j).NumericCellValue);
else
dataRow[j] = row.GetCell(j).StringCellValue;
isAdd = true;
}
}
if (isAdd)
table.Rows.Add(dataRow);
}
workbook = null;
sheet = null;
return table;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
return null;
}
}
#endregion