NPOI 官網(wǎng) http://npoi.codeplex.com/ 百度云: http://pan.baidu.com/s/1skV0LdV下載 NPOI組件 解壓后 得到 !
psb.jpg
第一步在項(xiàng)目中引用 (我的項(xiàng)目是4.0 ,所以引用 Net40文件夾下面的dll)
Paste_Image.png
這5個(gè)dll都需要引用, 缺少某一個(gè)都會(huì)報(bào)錯(cuò)( 缺少依賴項(xiàng) )第二步上代碼拉 asp.net MVC項(xiàng)目的方法
/// <summary>
/// 導(dǎo)入excel
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public ActionResult ImportCompanyModel(HttpPostedFileBase file)
{
dynamic dy;
if (file == null || file.ContentLength <= 0)
{
dy = new { code = -1, msg = "沒有要導(dǎo)入的文件!", imcount = 0, errorcount = 0};
return Json(dy);
}
try
{
string[] fileex = {".xls",".xlsx"};
string extension = Path.GetExtension(file.FileName);
if (!fileex.Contains(extension))
{
return Json(new { code = -2, msg = "只能導(dǎo)入excel文件!", imcount = 0, errorcount = 0});
}
DataTable dt = ExcelHelper.GetExcelList(file.InputStream);
int imcount;
int errorcount;
AgentCompanyBll.ImportExcel(dt, LoginInfo.Loginid.ToInt(), out imcount, out errorcount);
dy = new { code = 0, msg = "導(dǎo)入完成!", imcount, errorcount };
}
catch (Exception ex)
{
WebExceptionHelper.AsyncProcessWebException(ExceptionModuleType.FuLuKeTrialWebsite, ex);
dy = new { code = -2, msg = "導(dǎo)入數(shù)據(jù)異常!", imcount = 0, errorcount = 0 };
}
return Json(dy);
}
ExcelHelper.cs
/// <summary>
/// 將Excel轉(zhuǎn)成table
/// </summary>
/// <param name="stream">文件流</param>
/// <returns></returns>
public static DataTable GetExcelList(Stream stream)
{
DataTable table = new DataTable();
//導(dǎo)入excel 自動(dòng)區(qū)分 xls 和 xlsx
IWorkbook workbook = WorkbookFactory.Create(stream);
ISheet sheet = workbook.GetSheetAt(0);//得到里面第一個(gè)sheet
//獲取Excel的最大行數(shù)
int rowsCount = sheet.PhysicalNumberOfRows;
//為保證Table布局與Excel一樣喧务,這里應(yīng)該取所有行中的最大列數(shù)(需要遍歷整個(gè)Sheet)献酗。
//為少一交全Excel遍歷介评,提高性能沪曙,我們可以人為把第0行的列數(shù)調(diào)整至所有行中的最大列數(shù)棺棵。
int colsCount = sheet.GetRow(0).PhysicalNumberOfCells;
for (int i = 0; i < colsCount; i++)
{
//將第一列設(shè)置成表頭
table.Columns.Add(sheet.GetRow(0).GetCell(i).ToString());
}
for (int x = 0; x < rowsCount; x++)
{
if (x == 0) continue; //去掉第一列
DataRow dr = table.NewRow();
for (int y = 0; y < colsCount; y++)
{
dr[y] = sheet.GetRow(x).GetCell(y).ToString();
}
table.Rows.Add(dr);
}
return table;
}
完成啦 剩下的數(shù)據(jù)自己去處理吧