從 C# MVC 應用程式中的 Excel (XLSX) 檔案導入資料涉及使用類似 or 的庫來讀取和分析檔案。在本指南中,我們将使用該庫,因為它簡單且功能強大。
先決條件
在開始之前,請確定滿足以下條件:
- Visual Studio 或任何 C# IDE
- 基本了解 C#、ASP.NET MVC 和 HTML
- 要讀取的 Excel 檔案
設定項目
- 建立新的 ASP.NET MVC 項目:
- 打開 Visual Studio 并建立新的 ASP.NET MVC 項目:
File > New > Project > ASP.NET Web Application > MVC
3. 安裝 EPPlus 庫:
4. 通過 NuGet 包管理器安裝庫。在包管理器控制台中運作以下指令:EPPlus
Install-Package EPPlus
建立模型
首先,建立一個模型類來表示要從 Excel 檔案導入的資料。例如,讓我們建立一個模型:Product
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
建立控制器
接下來,建立一個控制器來處理檔案上傳和資料處理。在此示例中,讓我們建立一個:ProductController
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;
using EPPlusSample.Models;
using OfficeOpenXml;
namespace EPPlusSample.Controllers
{
public class ProductController : Controller
{
// GET: Product
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
if (file != && file.ContentLength > 0)
{
var products = new List<Product>();
using (var package = new ExcelPackage(file.InputStream))
{
var worksheet = package.Workbook.Worksheets[0];
var rowCount = worksheet.Dimension.Rows;
for (int row = 2; row <= rowCount; row++)
{
var product = new Product
{
Id = int.Parse(worksheet.Cells[row, 1].Text),
Name = worksheet.Cells[row, 2].Text,
Price = decimal.Parse(worksheet.Cells[row, 3].Text)
};
products.Add(product);
}
}
// Save products to the database or process them as needed
// For simplicity, we'll just pass the list to the view
return View("Index", products);
}
return View("Index");
}
}
}
在此代碼中:
- 我們定義一個操作來顯示上傳表單。Index
- 該操作處理檔案上傳并使用 .ImportEPPlus
- 我們解析 Excel 資料并建立一個對象清單。Product
- 最後,我們将産品清單傳遞給視圖以進行顯示或進一步處理。
建立視圖
為上傳 Excel 檔案并顯示導入資料的操作建立視圖。在檔案夾中建立一個包含以下内容的檔案:IndexIndex.cshtmlViews/Product
@model IEnumerable<EPPlusSample.Models.Product>
@{
ViewBag.Title = "Import Products";
}
<h2>Import Products</h2>
<form action="/Product/Import" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit">Upload</button>
</form>
@if (Model != && Model.Any())
{
<h3>Imported Products</h3>
<table class="table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
@foreach (var product in Model)
{
<tr>
<td>@product.Id</td>
<td>@product.Name</td>
<td>@product.Price</td>
</tr>
}
</tbody>
</table>
}
在此視圖中:
- 我們建立一個表單來上傳 Excel 檔案。
- 如果模型包含資料(即導入産品清單),我們會将其顯示在表格中。
運作應用程式
- 通過在 Visual Studio 中按或運作項目來啟動應用程式。F5
- 導航到“産品導入”頁面。
- 上傳包含商品資料的 Excel 檔案。
- 檢視表格中顯示的進口産品。
在本介紹了如何使用庫從 C# MVC 應用程式中的 Excel (XLSX) 檔案導入資料。通過建立簡單的檔案上傳表單并分析 Excel 檔案,您可以輕松地在 ASP.NET MVC 應用程式中導入和處理資料。
如果你喜歡我的文章,請給我一個贊!謝謝