asp.net core web的導入導出excel功能


 

這里主要記錄下asp.net core web頁面上進行導入導出excel的操作。

主要是導入,因為現在使用的很多前端框架(例如kendo ui)本身就有導出的功能。

 

這里使用到EPPlus.Core,其實對於excel的導入導出還可以使用NPOI,

這里講解EPPlus的方式

 

1.創建asp.net core web (mvc)項目

效果圖如下

 

 2.在項目上右鍵,進入nuget管理器,安裝EPPlus.Core

 

3.添加一個XlsxController控制器,在其中添加導入和導出功能

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OfficeOpenXml;

namespace EPPlusDemo.Controllers
{
    public class XlsxController : Controller
    {
        //用來獲取路徑相關
        private IHostingEnvironment _hostingEnvironment;

        public XlsxController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// excel導出功能
        /// </summary>
        /// <returns></returns>
        public IActionResult Export()
        {
            string sWebRootFolder = _hostingEnvironment.WebRootPath;
            string sFileName = $"{Guid.NewGuid()}.xlsx";
            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));  //Path.Combine把多個字符串組成一個路徑
            using (ExcelPackage package = new ExcelPackage(file))   //ExcelPackage 操作excel的主要對象
            {
                // 添加worksheet
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");
                //添加頭
                worksheet.Cells[1, 1].Value = "ID";
                worksheet.Cells[1, 2].Value = "Name";
                worksheet.Cells[1, 3].Value = "Url";
                //添加值
                worksheet.Cells["A2"].Value = 1000;
                worksheet.Cells["B2"].Value = "baidu";
                worksheet.Cells["C2"].Value = "https://www.baidu.com/";

                worksheet.Cells["A3"].Value = 1001;
                worksheet.Cells["B3"].Value = "博客園";
                worksheet.Cells["C3"].Value = "https://www.cnblogs.com/";
                worksheet.Cells["C3"].Style.Font.Bold = true;

                package.Save();
            }
            return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        }

     //導入功能 [HttpPost]
public IActionResult Import(IFormFile excelfile) { string sWebRootFolder = _hostingEnvironment.WebRootPath; string sFileName = $"{Guid.NewGuid()}.xlsx"; FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName)); try { //把excelfile中的數據復制到file中 using (FileStream fs = new FileStream(file.ToString(), FileMode.Create)) //初始化一個指定路徑和創建模式的FileStream { excelfile.CopyTo(fs); fs.Flush(); //清空stream的緩存,並且把緩存中的數據輸出到file } using (ExcelPackage package = new ExcelPackage(file)) { StringBuilder sb = new StringBuilder(); ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; int rowCount = worksheet.Dimension.Rows; int ColCount = worksheet.Dimension.Columns; for (int row = 1; row <= rowCount; row++) { for (int col = 1; col <= ColCount; col++) { //sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t"); //這種寫法遇到為null的為報錯 sb.Append(worksheet.Cells[row, col].Value + "\t"); } sb.Append(Environment.NewLine); } return Content(sb.ToString()); } } catch (Exception ex) { return Content(ex.Message); } } }

 

4.在 Xlsx / Index.cshtml 文件上進行如下編輯

@{
    ViewData["Title"] = "Index";
}


<h2>ASP.NET Core 導入導出Excel xlsx 文件</h2>
<a asp-action="Export">導出Excel</a> <hr />

<!--導入--> <form enctype="multipart/form-data" method="post" asp-action="Import"> <input type="file" name="excelfile" /> <input type="submit" value="上傳" /> </form>

 

5.運行程序,效果如下

 

 

最后,附上參考網址:  

 https://www.cnblogs.com/linezero/p/aspnetcoreexcel.html

后續繼續學習網址:

https://github.com/JanKallman/EPPlus/wiki

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM