使用IRONXL

如何在ASP.NET中查看Excel

更新 2024年三月31日
分享:

本综合教程将演示如何使用 ASP.NET MVC 和 IronXL 创建 Excel 查看器。该查看器可让用户直接从网页上显示、编辑和浏览 Excel 文件。

什么是 IronXL?

IronXL 是一个功能强大的.NET 库,可提供大量与 Excel 操作相关的功能。它提供了一个简化的应用程序接口,可让 .NET 开发人员编写、操作和使用 Excel。 阅读 Excel 文档 各种文件格式,包括 XLS、XLSX、CSV 等。

使用 IronXL,你可以读取 Excel 文件、 提取数据添加或编辑工作表、 创建或修改行和列申请 公式保存更改等等。所有这些操作都无需在计算机上安装 Microsoft Excel 即可完成。

IronXL 支持图像和样式、 条件格式以及其他复杂的 Excel 功能,使其成为 .NET Excel 操作的全面解决方案。它是处理 ASP.NET MVC 应用程序的数据源和电子表格要求的完美工具。IronXL 库将用于在 ASP.NET Web 应用程序中查看 Excel 文件。

先决条件

  • 基本了解 ASP.NET MVC
  • 计算机上安装了 Visual Studio
  • 安装了 IronXL 库。您可以在其官方文档中找到安装指南。

开始

首先,让我们在 Visual Studio 中创建一个新的 ASP.NET MVC 项目。

1.打开 Visual Studio。

2.单击 文件 > 新建 > 项目

3.在新项目窗口中,选择 ASP.NET Web 应用程序 (.NET框架) 模板。

![如何在 ASP.NET 中查看 Excel,图 1:在 Visual Studio 中创建一个新的 ASP.NET Web 应用程序](/static-assets/excel/blog/asp-net-excel-viewer-tutorial/asp-net-excel-viewer-tutorial-1.webp)

**在 Visual Studio 中创建一个新的 ASP.NET Web 应用程序**

4.将项目命名为 "ExcelViewer",选择项目位置并单击 "创建"按钮。

![如何在 ASP.NET 中查看 Excel,图 2:配置您的项目](/static-assets/excel/blog/asp-net-excel-viewer-tutorial/asp-net-excel-viewer-tutorial-2.webp)

**配置您的项目**

本文将重点介绍在此 ASP.NET MVC 应用程序中实现 Excel 查看器功能。

为项目添加 IronXL

处理 Excel 文件格式 (如 .xls、.xlsx 和 .csv)IronXL 提供加载 Excel 文档、读取、写入甚至修改 Excel 数据的全面功能。它支持公式、图像、格式化等。

1.在解决方案资源管理器中右键单击项目,然后导航到管理 NuGet 包**。

2.在NuGet软件包管理器中,搜索IronXL.Excel

3.点击安装将其添加到项目中。

![如何在 ASP.NET 中查看 Excel,图 3:在 NuGet 软件包管理器用户界面中搜索并安装 IronXL 软件包](/static-assets/excel/blog/asp-net-excel-viewer-tutorial/asp-net-excel-viewer-tutorial-3.webp)

**在 NuGet 软件包管理器用户界面中搜索并安装 IronXL 软件包**

您也可以使用软件包管理器控制台,使用以下命令安装 IronXL:

Install-Package IronXL.Excel

如何在 ASP.NET 中查看 Excel,图 4:从软件包管理器控制台安装 IronXL 软件包

从软件包管理器控制台安装 IronXL 软件包

现在 IronXL 已经安装完毕,让我们进入下一步。

建筑模型

ExcelModel.

第一步是为 Excel 数据创建一个模型。ExcelModel` 类将代表单个 Excel 表,并包含表名和 Excel 表中的数据。

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelModel
    {
        public string SheetName { get; set; }
        public List<string []> Data { get; set; }
    }
}
namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelModel
    {
        public string SheetName { get; set; }
        public List<string []> Data { get; set; }
    }
}
Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelModel
		Public Property SheetName() As String
		Public Property Data() As List(Of String ())
	End Class
End Namespace
VB   C#

ExcelModel "有两个属性:"SheetName "和 "Data"。SheetName "是一个简单的字符串,用于保存每个 Excel 工作表的名称。数据 "是一个字符串数组列表,用于存储 Excel 工作表中每一行的数据。

ExcelViewModel.

接下来,让我们创建 ExcelViewModel。该模型是一个包装器,其中包含一个文件、一条信息和一个 ExcelModel 列表,该列表代表文件中所有工作表的数据。

using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelViewModel
    {
        public IFormFile File { get; set; }
        public string Message { get; set; }
        public List<ExcelModel> ExcelData { get; set; }
    }
}
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace Excel_File_Viewer_IronXL.Models
{
    public class ExcelViewModel
    {
        public IFormFile File { get; set; }
        public string Message { get; set; }
        public List<ExcelModel> ExcelData { get; set; }
    }
}
Imports Microsoft.AspNetCore.Http
Imports System.Collections.Generic

Namespace Excel_File_Viewer_IronXL.Models
	Public Class ExcelViewModel
		Public Property File() As IFormFile
		Public Property Message() As String
		Public Property ExcelData() As List(Of ExcelModel)
	End Class
End Namespace
VB   C#

该类将用作视图模型。它有一个(n) 用于上传文件的 IFormFile 属性,用于显示任何信息的 Message 字符串,以及 `List用于存储检索到的 Excel 数据。

5.创建 ExcelController 来加载 Excel 文件以提取数据

然后创建一个新的 ExcelController。神奇的事情就在这里发生! Excel 文件使用 IronXL 的 工作簿载入 函数,循环浏览工作表,提取数据并将其添加到 ExcelViewModel 中。

using Excel_File_Viewer_IronXL.Models;
using IronXL;
using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Linq;

public class ExcelController : Controller
{
    // GET: Excel
    public ActionResult Index()
    {
        var model = new ExcelViewModel();

        // Define the file path
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

    // Replace 'Test.xlsx' with your file name

        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);
            foreach (var worksheet in workbook.WorkSheets)
            {
                data.Add(new ExcelModel
                {
                    SheetName = worksheet.Name,
                    Data = worksheet.Rows.Select(r => r.ToArray().Select(c => c.Value.ToString()).ToArray()).ToList()
                });
            }

            model.ExcelData = data;
            model.Message = "File processed successfully!";
        }
        catch (Exception ex)
        {
            model.Message = $"Error occurred while processing file: {ex.Message}";
        }

        return View(model);
    }
}
using Excel_File_Viewer_IronXL.Models;
using IronXL;
using System.Collections.Generic;
using System.Web.Mvc;
using System;
using System.Linq;

public class ExcelController : Controller
{
    // GET: Excel
    public ActionResult Index()
    {
        var model = new ExcelViewModel();

        // Define the file path
        string filePath = Server.MapPath("~/App_Data/Test.xlsx"); 

    // Replace 'Test.xlsx' with your file name

        List<ExcelModel> data = new List<ExcelModel>();

        try
        {
            // Load workbook directly from a file path
            var workbook = WorkBook.Load(filePath);
            foreach (var worksheet in workbook.WorkSheets)
            {
                data.Add(new ExcelModel
                {
                    SheetName = worksheet.Name,
                    Data = worksheet.Rows.Select(r => r.ToArray().Select(c => c.Value.ToString()).ToArray()).ToList()
                });
            }

            model.ExcelData = data;
            model.Message = "File processed successfully!";
        }
        catch (Exception ex)
        {
            model.Message = $"Error occurred while processing file: {ex.Message}";
        }

        return View(model);
    }
}
Imports Excel_File_Viewer_IronXL.Models
Imports IronXL
Imports System.Collections.Generic
Imports System.Web.Mvc
Imports System
Imports System.Linq

Public Class ExcelController
	Inherits Controller

	' GET: Excel
	Public Function Index() As ActionResult
		Dim model = New ExcelViewModel()

		' Define the file path
		Dim filePath As String = Server.MapPath("~/App_Data/Test.xlsx")

	' Replace 'Test.xlsx' with your file name

		Dim data As New List(Of ExcelModel)()

		Try
			' Load workbook directly from a file path
			Dim workbook = WorkBook.Load(filePath)
			For Each worksheet In workbook.WorkSheets
				data.Add(New ExcelModel With {
					.SheetName = worksheet.Name,
					.Data = worksheet.Rows.Select(Function(r) r.ToArray().Select(Function(c) c.Value.ToString()).ToArray()).ToList()
				})
			Next worksheet

			model.ExcelData = data
			model.Message = "File processed successfully!"
		Catch ex As Exception
			model.Message = $"Error occurred while processing file: {ex.Message}"
		End Try

		Return View(model)
	End Function
End Class
VB   C#

在这里,初始化一个(n) ExcelViewModel",然后加载 工作簿 使用 IronXL 对每个 工作表,并为每个 "工作表 "创建一个(n) 工作表的名称和数据的 ExcelModel 中。然后,"ExcelModel "会被添加到 "ExcelViewModel "的 "ExcelData "列表中。

将加载并显示以下 Excel 文件的数据:

如何在 ASP.NET 中查看 Excel,图 5:Excel 示例文件

Excel 示例文件

6.创建视图

Views/Excel目录下,创建一个新的 HTML 文件 Index.cshtml 来显示 Excel 数据。然后使用 Bootstrap 的 nav-tabs 来表示 Excel 文件中的每个工作表。每个工作表都将是一个单独的标签页,标签页的内容将是该工作表的数据。

@model Excel_File_Viewer_IronXL.Models.ExcelViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Excel File Viewer</h2>

@if (Model.ExcelData != null)
{
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <li class="nav-item">
                <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)">
                    @Model.ExcelData [i].SheetName
                </a>
            </li>
        }
    </ul>
    <div class="tab-content" id="myTabContent">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i">
                <table class="table table-bordered">
                    @foreach (var row in Model.ExcelData [i].Data)
                    {
                        <tr>
                            @foreach (var cell in row)
                            {
                                <td>@cell</td>
                            }
                        </tr>
                    }
                </table>
            </div>
        }
    </div>
}
@model Excel_File_Viewer_IronXL.Models.ExcelViewModel

@{
    ViewBag.Title = "Index";
}

<h2>Excel File Viewer</h2>

@if (Model.ExcelData != null)
{
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <li class="nav-item">
                <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)">
                    @Model.ExcelData [i].SheetName
                </a>
            </li>
        }
    </ul>
    <div class="tab-content" id="myTabContent">
        @for (int i = 0; i < Model.ExcelData.Count; i++)
        {
            <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i">
                <table class="table table-bordered">
                    @foreach (var row in Model.ExcelData [i].Data)
                    {
                        <tr>
                            @foreach (var cell in row)
                            {
                                <td>@cell</td>
                            }
                        </tr>
                    }
                </table>
            </div>
        }
    </div>
}
model ReadOnly Property () As Excel_File_Viewer_IronXL.Models.ExcelViewModel
	ViewBag.Title = "Index"
End Property

'INSTANT VB TODO TASK: The following line could not be converted:
(Of h2) Excel File Viewer</h2> [if](Model.ExcelData != Nothing)
If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <ul class="nav nav-tabs" id="myTab" role="tablist"> for(int i = 0; i < Model.ExcelData.Count; i++)
	"myTab" role="tablist"> [for](Integer i = 0; i < Model.ExcelData.Count; i)
		If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <ul class="nav nav-tabs" id="myTab" role
	"nav nav-tabs" id="myTab" role
	<ul class="nav nav-tabs" id
	i += 1
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected="@(i == 0)"> @Model.ExcelData [i].SheetName </a> </li>
			"content-@i" aria-selected="@(i == 0)"> Model.ExcelData (i).SheetName </a> </li>
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls="content-@i" aria-selected
			"tab" aria-controls="content-@i" aria-selected
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role="tab" aria-controls
			"#content-@i" role="tab" aria-controls
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href="#content-@i" role
			"tab" href="#content-@i" role
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle="tab" href
			"tab-@i" data-toggle="tab" href
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle
			"nav-link @(i == 0 ? "active" : "")" id="tab-@i" data-toggle
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <li class="nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id
			"nav-item"> <a class="nav-link @(i == 0 ? "active" : "")" id
			<li class="nav-item"> <a class
		End If
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: </ul> <div class="tab-content" id="myTabContent"> for(int i = 0; i < Model.ExcelData.Count; i++)
	"tab-content" id="myTabContent"> [for](Integer i = 0; i < Model.ExcelData.Count; i)
		If True Then
	</ul> <div class="tab-content" id
	i += 1
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i"> <table class="table table-bordered"> foreach(var row in Model.ExcelData [i].Data)
			"tab-@i"> <table class="table table-bordered"> foreach(var row in Model.ExcelData (i).Data)
					If True Then
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby="tab-@i"> <table class
			"tabpanel" aria-labelledby="tab-@i"> <table class
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role="tabpanel" aria-labelledby
			"content-@i" role="tabpanel" aria-labelledby
'INSTANT VB WARNING: An assignment within expression was extracted from the following statement:
'ORIGINAL LINE: <div class="tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role
			"tab-pane fade @(i == 0 ? "show active" : "")" id="content-@i" role
			<div class="tab-pane fade @(i == 0 ? "show active" : "")" id
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'						(Of tr) @foreach(var cell in row)
'							{
'								<td> @cell</td>
'							}
						</tr>
					End If
				</table> </div>
		End If
	</div>
End If
VB   C#

在此代码示例中,"nav nav-tabs "将生成一个标签页列表,每个标签页代表 Excel 文件中的一个工作表。相应的标签页内容将以表格格式显示相应工作表的数据。通过一些更改,添加了一个浏览按钮,以便手动选择 Excel 文件。

运行程序

完成所有步骤并正确设置项目后,就可以运行程序了。你会看到一个网页,上面有以 Excel 文件中工作表名称命名的选项卡。点击标签页将以表格形式显示相应工作表的数据。

如何在 ASP.NET 中查看 Excel,图 6:Excel 查看器

Excel 浏览器

结论

您刚刚使用 IronXL 创建了一个 ASP.NET Excel 查看器! 这个功能强大的库能让用户以更高效、更易于管理的方式处理 Excel 文件。在 IronXL 的帮助下,在 .NET 环境中处理 Excel 文件变得前所未有的简单。

IronXL 提供了 免费试用,让您无需任何前期费用即可探索和了解其丰富的功能。一旦您经过测试发现它是满足您需求的完美解决方案,许可证的起价为 $749。

< 前一页
如何在C#中将XLS转换为XLSX文件
下一步 >
如何在C#中写入CSV文件数据

准备开始了吗? 版本: 2024.10 刚刚发布

免费NuGet下载 总下载量: 1,039,965 查看许可证 >