NPOI读取excel
来源:互联网 发布:100本网络禁书网盘下载 编辑:程序博客网 时间:2024/06/06 21:37
/// <summary>
/// 轉換Excel資料至DataSet
/// </summary>
/// <param name="filePath">Excel檔案路徑</param>
/// <returns>轉換Excel資料至DataSet</returns>
public static DataSet ExcelToDataSetByNPOI(string filePath)
{
DataSet dsData = new DataSet();
if (File.Exists(filePath))
{
FileStream stream = new FileStream(filePath, FileMode.Open);
HSSFWorkbook workbook = new HSSFWorkbook(stream);
stream.Close();
short dateFormat = workbook.CreateDataFormat().GetFormat("yyyy/MM/dd HH:mm:ss");
for (int idx = 0, count = workbook.NumberOfSheets; idx < count; idx++)
{
ISheet sheet = workbook.GetSheetAt(idx);
if (sheet != null)
{
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(0);
if (headerRow != null)
{
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1), rowCount = sheet.LastRowNum; i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
ICell cell = row.GetCell(j);
if (cell != null)
{
dataRow[j] = ParseNPOICellValue(cell, dateFormat);
}
}
}
else
{
for (int j = 0; j < cellCount; j++)
{
dataRow[j] = "";
}
}
table.Rows.Add(dataRow);
}
dsData.Tables.Add(table);
sheet = null;
}
}
}
workbook = null;
}
return dsData;
}
/// <summary>
/// 依欄位資料型態轉換成適當字串
/// </summary>
/// <param name="cell">欄位</param>
/// <param name="dateFormat">日期格式</param>
/// <returns>欄位資料</returns>
private static string ParseNPOICellValue(ICell cell, short dateFormat)
{
string cellValue = cell.ToString();
if (!cellValue.IsEmpty())
{
if (cell.CellType == CellType.NUMERIC)
{
try
{
if (HSSFDateUtil.IsCellDateFormatted(cell))
{
cell.CellStyle.DataFormat = dateFormat;
string val = cell.DateCellValue.ToString("yyyy/MM/dd HH:mm:ss");
if (val.EndsWith(" 00:00:00"))
{
return cell.DateCellValue.ToString("yyyy/MM/dd");
}
return val;
}
else if (cellValue.StartsWith("."))
{
return Convert.ToDecimal(cellValue).ToString();
}
}
catch
{
}
}
return cellValue;
}
return "";
}
#endregion
}
- NPOI读取Excel
- NPOI读取excel数据
- NPOI读取excel
- NPOI读取Excel
- c# NPOI EXcel读取
- C#NPOI读取Excel
- Npoi导出Excel、读取Excel
- NPOI 读取 excel通用类
- c#用npoi读取excel
- NPOI读取Excel笔记总结
- C#用NPOI读取excel
- 使用NPOI读取Excel文件
- Npoi 读取EXCEL 2003 2007
- NPOI读取EXCEL到datagridview
- NPOI操作Excel 002:读取Excel
- [源码分享]NPOI读取Excel到 dataTable
- asp.net C# NPOI 读取 Excel 文件
- NPOI 创建Excel,数据读取与写入
- 多路径(multi-path)安装测试实例
- Mysql中整型的日期格式转换
- 安卓乱码问题
- 使用struts的标签获取后台值需注意
- Struts 2 常量配置文件详解
- NPOI读取excel
- ununtu的root用户密码设置
- cocos2d-x游戏开发系列教程-坦克大战游戏之坦克和地图碰撞的检测下
- “高级系统架构师”即将开课
- mac切换输入法快捷键
- 遇到Unhandled event loop exception No more handles 问题怎么解决
- android软件开发基础课程(一)
- 【C++基础】拷贝构造函数的参数必须是引用类型
- 查看Oracle系统各项参数使用情况的脚本