fg_yida_2/YiDa_WinForm/Helper/ExcelHelper.cs
2026-01-29 08:39:56 +08:00

104 lines
3.4 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using NPOI.SS.UserModel;
using System;
using System.Data;
using System.IO;
namespace YiDa_WinForm.Utils
{
/// <summary>
/// Excel 解析工具类
/// </summary>
public static class ExcelHelper
{
/// <summary>
/// 读取Excel文件转换为DataTable
/// </summary>
/// <param name="filePath">Excel文件路径</param>
/// <returns>解析后的DataTable</returns>
public static DataTable GetExcelToDataTable(string filePath)
{
if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
{
throw new FileNotFoundException("Excel文件不存在", filePath);
}
IWorkbook workbook = null;
FileStream fileStream = null;
try
{
fileStream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
workbook = WorkbookFactory.Create(fileStream);
DataTable dt = new DataTable();
// 读取第一个Sheet适配你的业务场景如需多Sheet可扩展
ISheet sheet = workbook.GetSheetAt(0);
if (sheet == null) return dt;
// 读取表头构建DataTable列
IRow headerRow = sheet.GetRow(0);
if (headerRow == null) return dt;
for (int i = 0; i < headerRow.LastCellNum; i++)
{
string columnName = headerRow.GetCell(i)?.ToString() ?? $"列{i + 1}";
dt.Columns.Add(columnName);
}
// 读取数据行
for (int rowIndex = 1; rowIndex <= sheet.LastRowNum; rowIndex++)
{
IRow dataRow = sheet.GetRow(rowIndex);
if (dataRow == null) continue;
DataRow dr = dt.NewRow();
for (int colIndex = 0; colIndex < headerRow.LastCellNum; colIndex++)
{
ICell cell = dataRow.GetCell(colIndex);
dr[colIndex] = GetCellValue(cell);
}
dt.Rows.Add(dr);
}
return dt;
}
finally
{
// 手动释放资源
if (fileStream != null)
{
fileStream.Close();
fileStream.Dispose();
}
workbook = null;
}
}
/// <summary>
/// 获取Excel单元格的值处理不同单元格类型
/// </summary>
private static string GetCellValue(ICell cell)
{
if (cell == null) return string.Empty;
switch (cell.CellType)
{
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(cell))
{
return cell.DateCellValue.ToString();
}
else
{
return cell.NumericCellValue.ToString();
}
case CellType.String:
return cell.StringCellValue;
case CellType.Boolean:
return cell.BooleanCellValue.ToString();
default:
return cell.ToString();
}
}
}
}