You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过每行按钮导出MudBlazor DataGrid单行数据为CSV文件

MudBlazor DataGrid 单行数据导出为CSV实现方案

实现步骤

1. 注入JS运行时

在组件顶部注入IJSRuntime,用于调用浏览器下载逻辑:

@inject IJSRuntime JSRuntime

2. 编写CSV生成与导出方法

在组件的C#代码块中添加以下方法,负责将单条数据转换为CSV格式,并触发下载:

// 生成单条数据的CSV内容,自动处理表头与特殊字符
private string GenerateSingleRowCsv<T>(T rowData) where T : class
{
    var properties = typeof(T).GetProperties();
    // 生成带引号的表头,避免字段名含特殊字符
    var headers = string.Join(",", properties.Select(p => $"\"{p.Name}\""));
    // 生成数据行,处理逗号、引号等特殊字符
    var values = string.Join(",", properties.Select(p => 
    {
        var value = p.GetValue(rowData)?.ToString() ?? string.Empty;
        if (value.Contains(',') || value.Contains('"'))
        {
            value = $"\"{value.Replace("\"", "\"\"")}\"";
        }
        return value;
    }));
    return $"{headers}\n{values}";
}

// 调用JS触发浏览器下载CSV文件
private async Task ExportRowToCsv<T>(T rowData, string fileName) where T : class
{
    var csvContent = GenerateSingleRowCsv(rowData);
    await JSRuntime.InvokeVoidAsync("downloadCsv", fileName, csvContent);
}

3. 添加浏览器下载的JS代码

在wwwroot/index.html(或Pages/_Host.cshtml)的<body>末尾添加以下JS方法:

<script>
    window.downloadCsv = function(fileName, csvContent) {
        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', fileName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        URL.revokeObjectURL(url);
    }
</script>

4. 在DataGrid中配置导出按钮

修改你的MudDataGrid代码,在列中添加模板列放置导出按钮,点击时传入当前行数据:

<MudDataGrid T="YourDataModel" Items="@yourDataSource">
    <Columns>
        <!-- 替换为你的业务列 -->
        <PropertyColumn Property="x => x.Id" Title="ID" />
        <PropertyColumn Property="x => x.ProductName" Title="产品名称" />
        <PropertyColumn Property="x => x.Price" Title="价格" />
        
        <!-- 导出操作列 -->
        <TemplateColumn Title="操作">
            <CellTemplate>
                <MudButton Variant="Variant.Filled" Color="Color.Primary" 
                           OnClick="@(() => ExportRowToCsv(context.Item, $"row_{context.Item.Id}.csv"))">
                    导出CSV
                </MudButton>
            </CellTemplate>
        </TemplateColumn>
    </Columns>
</MudDataGrid>

注意事项

  • 将YourDataModel替换为你实际使用的数据模型类,yourDataSource替换为绑定的数据源集合
  • 文件名可根据行数据动态生成(示例中用ID命名,避免重复)
  • CSV生成方法已处理特殊字符,确保导出文件格式符合标准

内容的提问来源于stack exchange,提问作者Amal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:02:00