使用Blazor框架實(shí)現(xiàn)在前端瀏覽器中導(dǎo)入和導(dǎo)出Excel
Blazor 是一個相對較新的框架,用于構(gòu)建具有 .NET 強(qiáng)大功能的交互式客戶端 Web UI。一個常見的用例是將現(xiàn)有的 Excel 文件導(dǎo)入 Blazor 應(yīng)用程序,將電子表格數(shù)據(jù)呈現(xiàn)給用戶,并且能夠允許進(jìn)行任何更改,最后將該數(shù)據(jù)導(dǎo)出回 Excel 文件或?qū)⑵浔4娴綌?shù)據(jù)庫。
以下是在 Blazor 中導(dǎo)入/導(dǎo)出電子表格文件的步驟:
創(chuàng)建 SpreadJS Blazor 組件創(chuàng)建 Blazor 應(yīng)用程序在 Blazor 應(yīng)用程序中導(dǎo)入 ExcelBlazor 應(yīng)用程序中的 Excel 導(dǎo)出創(chuàng)建 SpreadJS Blazor 組件SpreadJS 是一個非常強(qiáng)大且可擴(kuò)展的 JavaScript 電子表格組件,它使這個過程變得更加簡單。
在將 SpreadJS 放入 Blazor 應(yīng)用程序之前,我們必須首先創(chuàng)建一個 Blazor 組件來包含 SpreadJS。
在本教程中,我們將使用 Visual Studio 2022 和 SpreadJS V16.0。
要創(chuàng)建組件,首先要創(chuàng)建一個 Razor 類庫:
為簡單起見,您可以將其命名為“SpreadJS_Blazor_Lib”:
創(chuàng)建項(xiàng)目后,我們需要將 SpreadJS 文件復(fù)制到“wwwroot”文件夾:
創(chuàng)建這個項(xiàng)目還應(yīng)該創(chuàng)建一個名為“exampleJSInterop.js”的文件,因此我們需要對其進(jìn)行編輯以添加有助于將 C# 代碼連接到 SpreadJS 的 JavaScript 代碼的邏輯:
// This file is to show how a library package may provide JavaScript interop features// wrapped in a .NET APIwindow.sjsAdaptor = { init: function (host, config) {if (config.hostStyle) { var hostStyle = config.hostStyle; var styles = hostStyle.split(';'); styles.forEach((styleStr) => {var style = styleStr.split(':');host.style[style[0]] = style[1]; }); delete config.hostStyle;}return new GC.Spread.Sheets.Workbook(host, config); }, setValue: function (host, sheetIndex, row, col, value) {var spread = GC.Spread.Sheets.findControl(host);if (spread) { var sheet = spread.getSheet(sheetIndex); sheet.setValue(row, col, value);} }, openExcel: function (host, inputFile) {var spread = GC.Spread.Sheets.findControl(host);if (spread) { var excelIO = new GC.Spread.Excel.IO(); excelIO.open(inputFile.files[0], function (json) {spread.fromJSON(json); })} }};該應(yīng)用程序還應(yīng)該創(chuàng)建一個默認(rèn)的“Component1.razor”文件,我們可以將其重命名為“SpreadJS.razor”。這將是我們將用作包裝器的組件:
@using Microsoft.JSInterop@inject IJSRuntime JSRuntime<div @ref='host'></div>@code { [Parameter] public int SheetCount { get; set; } [Parameter] public string HostStyle { get; set; } private ElementReference host; public void setValue(int sheetIndex, int row, int col, object value) {JSRuntime.InvokeVoidAsync('sjsAdaptor.setValue', host, sheetIndex, row, col, value); } public void OpenExcel(ElementReference inputFile) {JSRuntime.InvokeVoidAsync('sjsAdaptor.openExcel', host, inputFile); } protected override void OnAfterRender(bool firstRender) {if (firstRender){ JSRuntime.InvokeVoidAsync('sjsAdaptor.init', host, new Dictionary<string, object>() {{ 'sheetCount', SheetCount},{ 'hostStyle', HostStyle } });} }}使用 SpreadJS 創(chuàng)建 Blazor 應(yīng)用程序現(xiàn)在我們已經(jīng)使用 SpreadJS 創(chuàng)建了一個組件,我們可以在 Blazor 應(yīng)用程序中使用它。首先,我們可以使用“Blazor WebAssemblyApp”模板添加一個新項(xiàng)目:
要添加 SpreadJS 組件,我們需要在解決方案資源管理器中右鍵單擊這個新項(xiàng)目的依賴項(xiàng),然后單擊“添加項(xiàng)目引用”。我們的 SpreadJS_Blazor_Lib 應(yīng)該列為選項(xiàng)之一:
在這個新項(xiàng)目中,應(yīng)該有一個頁面文件夾,其中包含幾個不同的 razor 文件。在此,我們將要編輯 Index.razor 文件以設(shè)置 HTML 的代碼隱藏:
@page '/'@using SpreadJS_Blazor_Lib<h1>Hello, SpreadJS!</h1><SpreadJS SheetCount='3' HostStyle='@HostStyle' />@code { private string HostStyle { get; set; } = 'width:90wh;height:70vh;border: 1px solid darkgray';}現(xiàn)在我們可以編輯“wwwroot”文件夾中的index.html文件。在這個文件中,我們可以添加對 SpreadJS JavaScript 和 CSS 文件的引用
<!DOCTYPE html><html><head> <meta charset='utf-8' /> <meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no' /> <title>BlazorApp1</title> <base rel='external nofollow' /> <link rel='external nofollow' rel='stylesheet' /> <link rel='external nofollow' rel='stylesheet' /> <link rel='external nofollow' rel='stylesheet' /> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/gc.spread.sheets.all.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.charts.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.shapes.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.slicers.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.print.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.barcode.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.pdf.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/plugins/gc.spread.sheets.tablesheet.16.0.5.min.js'></script> <script type='text/javascript' src='https://cdn.grapecity.com/spreadjs/hosted/scripts/interop/gc.spread.excelio.16.0.5.min.js'></script> <script src='https://www.jb51.net/aspnet/_content/SJS_Blazor_Lib/exampleJsInterop.js' type='text/javascript'></script></head><body> <app>Loading...</app> <div id='blazor-error-ui'>An unhandled error has occurred.<a class=' rel='external nofollow' reload'>Reload</a><a class='dismiss'>??</a> </div> <script src='https://www.jb51.net/aspnet/_framework/blazor.webassembly.js'></script></body></html>我們還可以在“Pages”文件夾下編輯 Index.razor 中的代碼:
@page '/'@using SJS_Blazor_Lib<h1>Hello, SpreadJS!</h1><table> <tr><td> <label>Sheet Index</label> <input @bind-value='@SheetIndex' /></td><td> <label>Row Index</label> <input @bind-value='@Row' /></td><td> <label>Column Index</label> <input @bind-value='@Column' /></td><td> <lable>Value</lable> <input @bind-value='@Value' /></td> </tr> <tr><td> <button @onclick='doSomething'>Update Text</button></td> </tr> <tr><td> <input type='file' @ref='inputFileEle' /></td><td> <button @onclick='ImportExcel'>Import File</button></td> </tr></table><br /><SpreadJS SheetCount='3' HostStyle='@HostStyle' @ref='ss' />@code { private SpreadJS ss; private ElementReference inputFileEle; public int SheetIndex { get; set; } = 0; public int Row { get; set; } = 0; public int Column { get; set; } = 0; public string Value { get; set; } = ''; private string HostStyle { get; set; } = 'width:90wh;height:70vh;border: 1px solid darkgray'; private void doSomething() {ss.setValue(SheetIndex, Row, Column, Value); } private void ImportExcel() {ss.OpenExcel(inputFileEle); }}這就是在 Blazor 應(yīng)用程序中運(yùn)行 SpreadJS 所需的全部內(nèi)容:
前面的代碼只是 SpreadJS 在 Blazor 應(yīng)用程序中的基本用法,但我們可以通過包含一些 Excel 導(dǎo)入功能來添加它。借助 SpreadJS 的強(qiáng)大功能,您可以在 Blazor 應(yīng)用程序中導(dǎo)入自己的 Excel 文件。實(shí)現(xiàn)類似于基本的 SpreadJS Blazor 代碼,但我們需要編輯 Index.razor 文件以添加一些用于設(shè)置值和打開 Excel 文件的代碼:
@page '/'@using SpreadJS_Blazor_Lib<h1>Hello, SpreadJS!</h1><table> <tr><td> <label>Sheet Index</label> <input @bind-value='@SheetIndex' /></td><td> <label>Row Index</label> <input @bind-value='@Row' /></td><td> <label>Column Index</label> <input @bind-value='@Column' /></td><td> <lable>Value</lable> <input @bind-value='@Value' /></td> </tr> <tr><td> <button @onclick='doSomething'>Update Text</button></td> </tr> <tr><td> <input type='file' @ref='inputFileEle' @onchange='ImportExcel' /></td> </tr></table><br /><SpreadJS SheetCount='3' HostStyle='@HostStyle' @ref='ss' />@code { private SpreadJS ss; private ElementReference inputFileEle; public int SheetIndex { get; set; } = 0; public int Row { get; set; } = 0; public int Column { get; set; } = 0; public string Value { get; set; } = ''; private string HostStyle { get; set; } = 'width:90wh;height:70vh;border: 1px solid darkgray'; private void doSomething() {ss.setValue(SheetIndex, Row, Column, Value); } private void ImportExcel() {ss.OpenExcel(inputFileEle); }}一旦我們在 Index.razor 中有了該代碼,它應(yīng)該可以導(dǎo)入,因?yàn)槲覀円呀?jīng)在前面的步驟中為 SpreadJS_Blazor_Lib 項(xiàng)目中的 SpreadJS.razor 和 exampleJsInterop.js 文件添加了代碼。
Blazor Excel 導(dǎo)出此外,我們還可以添加導(dǎo)出Excel文件的功能。為此,我們需要將代碼添加到 exampleJsInterop.js 文件中:
window.sjsAdaptor = { (....) saveExcel: function (host) {var spread = GC.Spread.Sheets.findControl(host);if (spread) { var json = spread.toJSON(); var excelIO = new GC.Spread.Excel.IO(); excelIO.save(json, function (blob) {saveAs(blob, 'export.xlsx'); }, function (e) {console.log(e); });} }};為了使“另存為”功能起作用,我們還需要在 index.html 文件中添加對 FileSaver 庫的引用:
<script type='text/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js'></script>要讓此代碼在頁面上運(yùn)行,我們需要將用于導(dǎo)出的按鈕添加到 Index.razor 代碼中:
@page '/'@using SpreadJS_Blazor_Lib<h1>Hello, SpreadJS!</h1><table> (....)<td> <button @onclick='ExportExcel'>Export File</button></td> </tr></table><br /><SpreadJS SheetCount='3' HostStyle='@HostStyle' @ref='ss' />@code { (....) private void ExportExcel() {ss.SaveExcel(); }}“ss.SaveExcel()”調(diào)用使用 SpreadJS.razor 文件中的代碼,因此我們需要確保在其中添加指向 exampleJsInterop.js 文件中正確函數(shù)的代碼:
@using Microsoft.JSInterop@inject IJSRuntime JSRuntime<div @ref='host'></div>@code { (....) public void SaveExcel() {JSRuntime.InvokeVoidAsync('sjsAdaptor.saveExcel', host); } (....)}以上就是使用Blazor框架實(shí)現(xiàn)在前端瀏覽器中導(dǎo)入和導(dǎo)出Excel的詳細(xì)內(nèi)容,更多關(guān)于Blazor導(dǎo)入導(dǎo)出Excel的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
