码迷,mamicode.com
首页 > Web开发 > 详细

.net 读取excel表格数据

时间:2019-10-14 10:24:22      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:xlsx   目录   table   读取   cts   gets   erro   代码   datatable   

 

文件格式.xls

代码展示:

//集合列表

IList<ProjectStatuStat> projectStatuStats = new List<ProjectStatuStat>();

//取根目录下的excel

string absPath = HttpContext.Current.Server.MapPath("~/TemplateFiles/台账.xls");

//取excel的sheet的命名
DataTable dt = ExcelNPOIHelper.Import(absPath, "总清单");

//循环excel表格数据
foreach (DataRow row in dt.Rows)
{
ProjectStatuStat pss = new ProjectStatuStat();
pss.ProjectNumber = row[0].ToString().Trim();excel第一列
pss.ProjectName = row[1].ToString().Trim();excel第二列

projectStatuStats.Add(pss);

}

 

/// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">文件全路径</param>
/// <param name="sheetName">sheetName</param>
/// <returns></returns>
public static DataTable Import(string strFileName,string sheetName)
{
DataTable dt = new DataTable();

HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheet(sheetName);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();

IRow headerRow = (HSSFRow)sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;

for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}

for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = (HSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow();

for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}

dt.Rows.Add(dataRow);
}
return dt;
}

 

文件格式不支持.xlsx  .若读取该格式可参考:https://www.cnblogs.com/wobuchifanqie/p/7685038.html

.net 读取excel表格数据

标签:xlsx   目录   table   读取   cts   gets   erro   代码   datatable   

原文地址:https://www.cnblogs.com/suqq/p/11669916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!