在参与“吉林省普通高等学校本科专业信息评价系统”项目遇到了关于.net的Excel文件导入的问题,与窗体类似,不过读取Excel的方式不同,具体如下
dt = NPOIReader.ReadExcel(fpath);
NPOIReader.cs
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Hosting;
//namespace要一致
namespace QualificationSearch
{
public class NPOIReader
{
public static string filePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["EXCELName"]);
public static DataTable ReadExcel()
{
DataTable dt = new DataTable();
//string filePath = "";
if (filePath != null)
{
// filePath = basePath;//HostingEnvironment.MapPath((basePath.ToString() + fileName));
dt = ImportExcelFile();
}
//文件是否存在
if (System.IO.File.Exists(filePath))
{
}
return dt;
}
public static DataTable ImportExcelFile()
{
HSSFWorkbook hssfworkbook;
#region//初始化信息
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
#endregion
NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
DataTable dt = new DataTable();
rows.MoveNext();
HSSFRow row = (HSSFRow)rows.Current;
for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++)
{
dt.Columns.Add(row.GetCell(j).ToString());
}
while (rows.MoveNext())
{
row = (HSSFRow)rows.Current;
DataRow dr = dt.NewRow();
for (int i = 0; i < row.LastCellNum; i++)
{
NPOI.SS.UserModel.ICell cell = row.GetCell(i);
if (cell == null)
{
dr[i] = null;
}
else
{
dr[i] = cell.ToString();
}
}
dt.Rows.Add(dr);
}
return dt;
}
}
}
有关引用:共6个
注:该方法仍存在Excel导入的兼容性问题,改为FPOI似乎可以。