从 C# MVC 应用程序中的 Excel (XLSX) 文件导入数据涉及使用类似 or 的库来读取和分析文件。在本指南中,我们将使用该库,因为它简单且功能强大。
在开始之前,请确保满足以下条件:
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 != null && 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");
}
}
}
在此代码中:
为上传 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 != null && 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>
}
在此视图中:
在本介绍了如何使用库从 C# MVC 应用程序中的 Excel (XLSX) 文件导入数据。通过创建简单的文件上传表单并分析 Excel 文件,您可以轻松地在 ASP.NET MVC 应用程序中导入和处理数据。