当前位置: 代码网 > it编程>编程语言>Asp.net > 使用Blazor框架实现在前端浏览器中导入和导出Excel

使用Blazor框架实现在前端浏览器中导入和导出Excel

2024年05月18日 • Asp.net •我要评论
前言blazor 是一个相对较新的框架,用于构建具有 .net 强大功能的交互式客户端 web ui。一个常见的用例是将现有的 excel 文件导入 blazor 应用程序,将电子表格数据呈现给用户,

前言

blazor 是一个相对较新的框架,用于构建具有 .net 强大功能的交互式客户端 web ui。一个常见的用例是将现有的 excel 文件导入 blazor 应用程序,将电子表格数据呈现给用户,并且能够允许进行任何更改,最后将该数据导出回 excel 文件或将其保存到数据库。

以下是在 blazor 中导入/导出电子表格文件的步骤:

  • 创建 spreadjs blazor 组件
  • 创建 blazor 应用程序
  • 在 blazor 应用程序中导入 excel
  • blazor 应用程序中的 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 api
window.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 href="/" rel="external nofollow"  />
    <link href="css/bootstrap/bootstrap.min.css" rel="external nofollow"  rel="stylesheet" />
    <link href="css/app.css" rel="external nofollow"  rel="stylesheet" />
    <link href="https://cdn.grapecity.com/spreadjs/hosted/css/gc.spread.sheets.excel2013white.16.0.5.css" 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="_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 href="" class=" rel="external nofollow" reload">reload</a>
        <a class="dismiss">??</a>
    </div>
    <script src="_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 所需的全部内容:

blazor excel 导入

前面的代码只是 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的资料请关注代码网其它相关文章!

赞 (0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com