使用Blazor框架實現在前端瀏覽器中導入和導出Excel
Blazor 是一個相對較新的框架,用于構建具有 .NET 強大功能的交互式客戶端 Web UI。一個常見的用例是將現有的 Excel 文件導入 Blazor 應用程序,將電子表格數據呈現給用戶,并且能夠允許進行任何更改,最后將該數據導出回 Excel 文件或將其保存到數據庫。
以下是在 Blazor 中導入/導出電子表格文件的步驟:
創建 SpreadJS Blazor 組件創建 Blazor 應用程序在 Blazor 應用程序中導入 ExcelBlazor 應用程序中的 Excel 導出創建 SpreadJS Blazor 組件SpreadJS 是一個非常強大且可擴展的 JavaScript 電子表格組件,它使這個過程變得更加簡單。
在將 SpreadJS 放入 Blazor 應用程序之前,我們必須首先創建一個 Blazor 組件來包含 SpreadJS。
在本教程中,我們將使用 Visual Studio 2022 和 SpreadJS V16.0。
要創建組件,首先要創建一個 Razor 類庫:
為簡單起見,您可以將其命名為“SpreadJS_Blazor_Lib”:
創建項目后,我們需要將 SpreadJS 文件復制到“wwwroot”文件夾:
創建這個項目還應該創建一個名為“exampleJSInterop.js”的文件,因此我們需要對其進行編輯以添加有助于將 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); })} }};該應用程序還應該創建一個默認的“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 創建 Blazor 應用程序現在我們已經使用 SpreadJS 創建了一個組件,我們可以在 Blazor 應用程序中使用它。首先,我們可以使用“Blazor WebAssemblyApp”模板添加一個新項目:
要添加 SpreadJS 組件,我們需要在解決方案資源管理器中右鍵單擊這個新項目的依賴項,然后單擊“添加項目引用”。我們的 SpreadJS_Blazor_Lib 應該列為選項之一:
在這個新項目中,應該有一個頁面文件夾,其中包含幾個不同的 razor 文件。在此,我們將要編輯 Index.razor 文件以設置 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';}現在我們可以編輯“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 應用程序中運行 SpreadJS 所需的全部內容:
前面的代碼只是 SpreadJS 在 Blazor 應用程序中的基本用法,但我們可以通過包含一些 Excel 導入功能來添加它。借助 SpreadJS 的強大功能,您可以在 Blazor 應用程序中導入自己的 Excel 文件。實現類似于基本的 SpreadJS Blazor 代碼,但我們需要編輯 Index.razor 文件以添加一些用于設置值和打開 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 中有了該代碼,它應該可以導入,因為我們已經在前面的步驟中為 SpreadJS_Blazor_Lib 項目中的 SpreadJS.razor 和 exampleJsInterop.js 文件添加了代碼。
Blazor Excel 導出此外,我們還可以添加導出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>要讓此代碼在頁面上運行,我們需要將用于導出的按鈕添加到 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()”調用使用 SpreadJS.razor 文件中的代碼,因此我們需要確保在其中添加指向 exampleJsInterop.js 文件中正確函數的代碼:
@using Microsoft.JSInterop@inject IJSRuntime JSRuntime<div @ref='host'></div>@code { (....) public void SaveExcel() {JSRuntime.InvokeVoidAsync('sjsAdaptor.saveExcel', host); } (....)}以上就是使用Blazor框架實現在前端瀏覽器中導入和導出Excel的詳細內容,更多關于Blazor導入導出Excel的資料請關注好吧啦網其它相關文章!