Aspose.Cells實現excel預覽

Sqsdhc發表於2022-11-24


在WEB專案中經常遇到excel文件線上預覽的需求,基本的解決思路有以下幾大類:excel文件轉PDF、excel文件直接轉html、後臺讀取excel資料返回給前端利用Excel效果的表格外掛如(HandsonTable)將資料進行展示、部署微軟Office Online服務(office web apps)實現線上預覽、線上的office預覽服務(如谷歌docs、微軟officeapps)。

EXCEL轉HTML

excel轉html可以透過第三方工具openoffice、微軟office或者第三方類庫如POI/NPOI、aspose.cell等轉換為html檔案。其中POI元件是開源免費的,Java版本叫POI,C#版本叫NPOI。但是轉換的效果不是很好,有多個sheet頁面的時候,POI會將所有sheet表格展示在一個網頁裡面,表格頂部會顯示sheet名稱,如果sheet很多的話頁面會很長,出現捲軸頁面樣式不是很美觀。

aspose.cells是收費元件,支援java、.net、.net core,免費使用時候轉換出的html頁面會有水印“Evaluation Only. Created with Aspose.Cells”如果excel存在多個sheet,aspose轉換出來的網頁會帶選項卡,點選選項卡會展示對應的sheet頁面內容,展示效果比POI轉換出的html效果的好。

首先在後臺使用aspose讀取excel檔案並返回轉換好的html檔案目錄返回給前臺

private readonly ILogger _logger;
private readonly IWebHostEnvironment _webHostEnvironment;

    public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
    {
        _logger = logger;
        _webHostEnvironment = webHostEnvironment;
    }
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult Privacy()
    {
        return View();
    }

    [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
    public IActionResult Error()
    {
        return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
    }
    /// <summary>
    /// 返回html地址
    /// </summary>
    /// <returns></returns>
    public string ExcelToHtml()
    {
        //程式根目錄
        string rootpath = _webHostEnvironment.ContentRootPath;
        //程式下webroot根目錄
        string webRootPath = _webHostEnvironment.WebRootPath;
        string filepath = webRootPath + "\\excelFile\\test.xlsx";
        //讀取模板路徑
        Workbook book = new Workbook(filepath);
        //filePath為儲存檔案的地址,需要服務端底下可以正常訪問的路徑
        book.Save(webRootPath+ "\\excelFile\\test.html", SaveFormat.Html);
        return  "\\excelFile\\test.html";
    }

前端接收到後臺返回的地址進行一個展示

點選檢視程式碼
@{
    ViewData["Title"] = "Home Page";
}
<script type="text/javascript">
    //預覽excel
    function ExcelToHtml() {
        $.ajax({
            url: "/Home/ExcelToHtml",
            data: "",
            type: "get",
            async: false,
            success: function (data) {
                debugger
                console.log(data)
                //獲得視窗的垂直位置
                var iWidth = 1400;
                var iHeight = 800;
                var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
                //獲得視窗的水平位置
                var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
                window.open(data, '_blank', 'height=' + iHeight + ',innerHeight=' + iHeight + ',width=' + iWidth + ',innerWidth=' + iWidth + ',top=' + iTop + ',left=' + iLeft + ',status=no,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=0,titlebar=no');
            },error(err)
            {
                debugger
            }
        });
    }
</script>
<div class="text-center">
    <h1 class="display-4">Welcome</h1>
    <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    <button onclick="ExcelToHtml()">預覽excel</button>
</div>

效果如下

相關文章