我在名爲ListProduct.xls的Excel表中有表。當我導入excel文件時,我希望它能夠在成功頁面中打印表格。索引頁工作正常,我可以點擊瀏覽並讓我選擇excel文件。但是當我點擊導入時,它會在我的產品控制器上給我一個錯誤。將Excel表導入到ASP.NET C#MVC
string path = Server.MapPath("~/Content/" + excelfile.FileName);
它給了我一個錯誤在這一行。它顯示的錯誤是
NotSupportedException由用戶代碼未處理。 'System.NotSupportedException' 類型的異常出現在mscorlib.dll,但在用戶代碼中沒有處理
ProductController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excel = Microsoft.Office.Interop.Excel;
using System.IO;
using ImportExcelFileInASPNETMVC.Models;
namespace ImportExcelFileInASPNETMVC.Controllers
{
public class ProductController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelfile)
{
if (excelfile == null || excelfile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelfile.FileName.EndsWith("xls") || excelfile.FileName.EndsWith("xlsx"))
{
string path = Server.MapPath("~/Content/" + excelfile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelfile.SaveAs(path);
// Read data from excel file
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(path);
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range range = worksheet.UsedRange;
List<Product> listProducts = new List<Product>();
for (int row = 3; row <= range.Rows.Count; row++)
{
Product p = new Product();
p.Name = ((Excel.Range)range.Cells[row, 2]).Text;
listProducts.Add(p);
}
ViewBag.ListProducts = listProducts;
return View("Success");
}
else
{
ViewBag.Error = "File type is incorrect<br>";
return View("Index");
}
}
}
}
}
Index.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Import", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.Raw(ViewBag.Error)
<span>Excel File </span><input type="file" name="excelfile" />
<br />
<input type="submit" value="Import" />
}
</body>
</html>
Success.cshtml
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Success</title>
</head>
<body>
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Name</th>
</tr>
@foreach (var p in ViewBag.ListProducts)
{
<tr>
<td>@p.Name</td>
</tr>
}
</table>
</body>
</html>
您需要退後一步並將這些任務分解爲單獨的功能。也許是一個處理上傳的函數,一個處理excel解析的函數,然後是處理將解析的數據加載到表單中以供顯示的東西。其次,使用Excel Interop會導致各種令人頭痛的問題,這可能是NotSupportedException的來源。我將切換到像ClosedXMl或EPPuls這樣的庫來解析Excel文件。 –
我是新手編程,只是試圖學習,我從網站上得到了這段代碼。我不確定如何使用ClosedXMI或EPPuls。如果你可以花一些你的寶貴時間,編寫或編輯代碼應該看起來像那麼好 – LohithT