Excel 导入导出项目适配方案
文档版本: v1.0 创建日期: 2025-12-22 基于: 02_架构设计方案.md 调整原因: 适配 EDUA 项目实际架构(无仓储层)
📋 核心问题与解决方案
问题1:查询条件复用
现状:
- 列表查询:
GetPageAsync(pageParam, searchParam)- 有分页 - 导出查询:需要相同的筛选条件,但不分页
解决方案:复用 BuildQuestionQuery 方法
csharp
// ✅ 当前已有的设计(保持不变)
private IQueryable<Question> BuildQuestionQuery(QuestionParameter? searchParam)
{
// 统一的筛选逻辑
var q = _context.Set<Question>().AsQueryable();
if (searchParam?.QuestionBankId.HasValue == true)
q = q.Where(x => x.QuestionBankId == searchParam.QuestionBankId.Value);
// ... 其他筛选条件
return q;
}
// ✅ 列表查询(有分页)
public async Task<PaginationList<QuestionDto>> GetPageAsync(
PageParamater pageParam,
QuestionParameter searchParam)
{
_context = _contextFactory.CreateContext(WriteRoRead.Read);
var query = BuildQuestionQuery(searchParam); // 复用
// 排序
var orderBy = !string.IsNullOrWhiteSpace(searchParam.OrderBy)
? searchParam.OrderBy
: "SortOrder,-Id";
query = LinqExtensions.OrderByBatch<Question>(query, orderBy);
// 分页
var page = await PaginationList<Question>.CreateAsync(
pageParam.PageIndex,
pageParam.PageSize,
query
);
var dtoItems = _mapper.Map<List<QuestionDto>>(page.Items);
return PaginationList<QuestionDto>.Create(
page.PageIndex,
page.PageSize,
page.TotalCount,
dtoItems
);
}
// ✅ 导出查询(不分页)
public async Task<List<QuestionDto>> GetAllForExportAsync(
QuestionParameter searchParam)
{
_context = _contextFactory.CreateContext(WriteRoRead.Read);
var query = BuildQuestionQuery(searchParam); // 复用相同的筛选逻辑
// 排序
var orderBy = !string.IsNullOrWhiteSpace(searchParam.OrderBy)
? searchParam.OrderBy
: "SortOrder,-Id";
query = LinqExtensions.OrderByBatch<Question>(query, orderBy);
// 不分页,直接查询全部
var questions = await query.ToListAsync();
return _mapper.Map<List<QuestionDto>>(questions);
}关键点:
- ✅
BuildQuestionQuery只负责筛选条件 - ✅ 分页逻辑在
GetPageAsync中处理 - ✅ 导出直接
ToListAsync(),不分页 - ✅ 两个方法共享相同的筛选和排序逻辑
问题2:导出数量限制
requirements:导出不能有分页限制,但要防止数据量过大
解决方案:在 Service 层添加最大导出数量检查
csharp
/// <summary>
/// 获取题目列表用于导出(带数量限制)
/// </summary>
/// <param name="searchParam">查询参数</param>
/// <param name="maxRows">最大导出行数(默认50000)</param>
/// <returns>题目列表</returns>
public async Task<List<QuestionDto>> GetAllForExportAsync(
QuestionParameter searchParam,
int maxRows = 50000)
{
_context = _contextFactory.CreateContext(WriteRoRead.Read);
var query = BuildQuestionQuery(searchParam);
// 先获取总数
var totalCount = await query.CountAsync();
if (totalCount > maxRows)
{
throw new InvalidOperationException(
$"导出数据量过大({totalCount} 条),超过最大限制({maxRows} 条),请添加筛选条件"
);
}
// 排序
var orderBy = !string.IsNullOrWhiteSpace(searchParam.OrderBy)
? searchParam.OrderBy
: "SortOrder,-Id";
query = LinqExtensions.OrderByBatch<Question>(query, orderBy);
// 查询全部数据
var questions = await query.ToListAsync();
return _mapper.Map<List<QuestionDto>>(questions);
}关键点:
- ✅ 不使用分页参数(
PageParamater) - ✅ 添加
maxRows参数控制最大导出数量 - ✅ 先
CountAsync()检查总数,避免查询大量数据后才报错 - ✅ 默认限制 50000 条,可根据实际情况调整
步骤1总结
修改清单
- QuestionService.cs - 新增方法:
csharp
/// <summary>
/// 获取题目列表用于导出(不分页,带数量限制)
/// </summary>
public async Task<List<QuestionDto>> GetAllForExportAsync(
QuestionParameter searchParam,
int maxRows = 50000)
{
_context = _contextFactory.CreateContext(WriteRoRead.Read);
var query = BuildQuestionQuery(searchParam);
// 检查数量
var totalCount = await query.CountAsync();
if (totalCount > maxRows)
{
throw new InvalidOperationException(
$"导出数据量过大({totalCount} 条),超过最大限制({maxRows} 条),请添加筛选条件"
);
}
// 排序
var orderBy = !string.IsNullOrWhiteSpace(searchParam.OrderBy)
? searchParam.OrderBy
: "SortOrder,-Id";
query = LinqExtensions.OrderByBatch<Question>(query, orderBy);
// 查询全部
var questions = await query.ToListAsync();
return _mapper.Map<List<QuestionDto>>(questions);
}- QuestionController.cs - 新增导出接口:
csharp
/// <summary>
/// 导出题目列表
/// </summary>
[HttpGet("export")]
public async Task<IActionResult> Export([FromQuery] QuestionParameter searchParam)
{
try
{
// 复用相同的查询参数
var questions = await _questionService.GetAllForExportAsync(searchParam);
if (!questions.Any())
{
return BadRequest(new { message = "没有符合条件的数据" });
}
// 调用导出服务(下一步实现)
var result = await _excelExporter.ExportAsync(
questions,
QuestionExportConfig.Columns,
$"题目列表_{DateTime.Now:yyyyMMddHHmmss}"
);
return File(result.Stream, result.ContentType, result.FileName);
}
catch (InvalidOperationException ex)
{
// 数量超限等业务异常
return BadRequest(new { message = ex.Message });
}
catch (Exception ex)
{
_logger.LogError(ex, "导出题目失败");
return StatusCode(500, new { message = "导出失败" });
}
}优势
| 方面 | 说明 |
|---|---|
| 代码复用 | BuildQuestionQuery 被列表和导出共享 |
| 职责分离 | 分页逻辑只在 GetPageAsync 中 |
| 安全性 | 导出前检查数量,防止数据过大 |
| 灵活性 | maxRows 可配置,不同场景不同限制 |
步骤2:架构适配(无仓储层)
问题3:项目架构适配
现状:EDUA 项目架构
edua/Server/
├── API/ # 控制器层
├── Services/ # 服务层(直接使用 DbContext)
├── Model/ # 实体层
└── Common/ # 基础设施层特点:
- ❌ 没有仓储层(Repository)
- ✅ Service 直接使用 DbContext
- ✅ 已有 DbContextFactory
调整后的架构
原方案(有仓储层)
Controller → Service → Repository → DbContext
↓
ExcelService适配方案(无仓储层)
Controller → Service (直接使用 DbContext)
↓
ExcelExporter (基础设施)具体实现
1. 目录结构(适配后)
edua/Server/
├── Common/
│ └── Infrastructure/
│ └── Excel/ # Excel 基础设施
│ ├── Abstractions/
│ │ ├── IExcelExporter.cs
│ │ └── IExcelImporter.cs
│ ├── Services/ # 实现(不叫 Export/Import,避免混淆)
│ │ ├── ExcelExportService.cs
│ │ └── ExcelImportService.cs
│ └── Models/
│ ├── ExportResult.cs
│ ├── ImportResult.cs
│ └── ImportError.cs
├── API/
│ └── Controllers/
│ └── Testing/
│ └── QuestionController.cs
└── Services/
└── Testing/
├── QuestionService.cs # 业务服务(负责数据查询)
└── Config/
├── QuestionExportConfig.cs
└── QuestionImportConfig.cs关键调整:
- ✅ Excel 功能放在
Common/Infrastructure/Excel(基础设施) - ✅ 不创建单独的
Export/Import文件夹,改为Services - ✅ 业务逻辑在
Services/Testing/QuestionService.cs
2. 调用流程(适配后)
┌─────────────────────────────────────────────────────────────┐
│ QuestionController │
│ - 接收导出请求 │
│ - 调用 QuestionService 获取数据 │
│ - 调用 IExcelExporter 生成文件 │
│ - 返回文件流 │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ QuestionService │
│ - 使用 DbContext 查询数据 │
│ - 复用 BuildQuestionQuery(筛选) │
│ - GetAllForExportAsync(不分页) │
│ - 返回 List<QuestionDto> │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ IExcelExporter (基础设施接口) │
│ - ExportAsync<T>(data, columnMapping, fileName) │
│ - 不关心数据来源 │
│ - 只负责生成 Excel │
└─────────────────────────────────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────┐
│ ExcelExportService (MiniExcel 实现) │
│ - 数据格式转换 │
│ - 调用 MiniExcel │
│ - 返回 MemoryStream │
└─────────────────────────────────────────────────────────────┘关键点:
- ✅ Service 层负责数据查询(使用 DbContext)
- ✅ ExcelExporter 只负责生成 Excel(不查询数据)
- ✅ Controller 协调两者
3. 避免平级调用问题
问题:Service 调用 Service 是否合理?
答案:合理,但要注意层次
csharp
// ✅ 正确:Controller 调用多个 Service
public class QuestionController
{
private readonly QuestionService _questionService; // 业务服务
private readonly IExcelExporter _excelExporter; // 基础设施服务
[HttpGet("export")]
public async Task<IActionResult> Export([FromQuery] QuestionParameter param)
{
// 1. 业务服务获取数据
var data = await _questionService.GetAllForExportAsync(param);
// 2. 基础设施服务生成 Excel
var result = await _excelExporter.ExportAsync(
data,
QuestionExportConfig.Columns,
"题目列表"
);
return File(result.Stream, result.ContentType, result.FileName);
}
}
// ❌ errors:Service 调用 Service(平级调用)
public class QuestionService
{
private readonly IExcelExporter _excelExporter; // ❌ 业务服务不应该依赖导出服务
public async Task<FileResult> ExportAsync()
{
var data = await GetAllAsync();
return await _excelExporter.ExportAsync(data, ...); // ❌ 职责混乱
}
}设计原则:
- ✅ Controller 可以调用多个 Service
- ✅ 业务 Service(QuestionService)只负责数据
- ✅ 基础设施 Service(ExcelExporter)只负责技术实现
- ❌ Service 之间不要互相调用(除非明确的依赖关系)
4. 数据权限处理
现状:已有统一的数据权限过滤
csharp
// 参考:edua/docs/复用技术/07_数据权限过滤/02_实现进度.md
// ✅ 当前已实现:在 BuildQuestionQuery 中统一过滤
private IQueryable<Question> BuildQuestionQuery(QuestionParameter? searchParam)
{
var q = _context.Set<Question>().AsQueryable();
// 数据权限已在这里统一处理
// 例如:根据用户角色过滤可见的题目
// 业务筛选条件
if (searchParam?.QuestionBankId.HasValue == true)
q = q.Where(x => x.QuestionBankId == searchParam.QuestionBankId.Value);
return q;
}导出时的权限:
csharp
/// <summary>
/// 导出题目(自动应用数据权限)
/// </summary>
[HttpGet("export")]
[Authorize] // 需要登录
public async Task<IActionResult> Export([FromQuery] QuestionParameter searchParam)
{
// BuildQuestionQuery 会自动应用数据权限
// 用户只能导出自己有权限看到的数据
var questions = await _questionService.GetAllForExportAsync(searchParam);
// ... 导出逻辑
}额外的导出限制(可选):
csharp
/// <summary>
/// 导出配置(可选)
/// </summary>
public class ExportOptions
{
/// <summary>
/// 最大导出行数
/// </summary>
public int? MaxRows { get; set; }
/// <summary>
/// 是否需要管理员权限
/// </summary>
public bool RequireAdmin { get; set; }
}
// 使用示例
[HttpGet("export")]
[Authorize(Roles = "Teacher,Admin")] // 只有教师和管理员可以导出
public async Task<IActionResult> Export([FromQuery] QuestionParameter searchParam)
{
// 普通用户最多导出 1000 条
// 管理员可以导出 50000 条
var maxRows = User.IsInRole("Admin") ? 50000 : 1000;
var questions = await _questionService.GetAllForExportAsync(searchParam, maxRows);
// ... 导出逻辑
}步骤2总结
架构适配要点
| 方面 | 原方案 | 适配方案 |
|---|---|---|
| 数据查询 | Repository | Service 直接用 DbContext |
| Excel 位置 | 独立模块 | Common/Infrastructure/Excel |
| 调用关系 | Controller → Service → Exporter | Controller → Service + Exporter |
| 数据权限 | 在 Repository | 在 Service 的 BuildQuery 中 |
| 职责分离 | 多层 | 简化,但职责清晰 |
优势
- ✅ 适配现有项目结构
- ✅ 不引入额外的仓储层
- ✅ 保持代码简洁
- ✅ 职责清晰(数据 vs 导出)
- ✅ 数据权限统一处理
步骤3:扩展性设计
问题4:多语言支持(预留扩展)
requirements:列标题支持多语言
设计方案:通过配置类支持多语言
csharp
/// <summary>
/// 题目导出配置(支持多语言)
/// </summary>
public static class QuestionExportConfig
{
/// <summary>
/// 获取列映射(根据语言)
/// </summary>
/// <param name="language">语言代码(zh-CN, en-US)</param>
/// <returns>列映射</returns>
public static Dictionary<string, string> GetColumns(string language = "zh-CN")
{
return language switch
{
"en-US" => new Dictionary<string, string>
{
{ nameof(QuestionDto.Id), "Question ID" },
{ nameof(QuestionDto.Type), "Type" },
{ nameof(QuestionDto.Content), "Content" },
{ nameof(QuestionDto.OptionA), "Option A" },
{ nameof(QuestionDto.OptionB), "Option B" },
{ nameof(QuestionDto.OptionC), "Option C" },
{ nameof(QuestionDto.OptionD), "Option D" },
{ nameof(QuestionDto.Answer), "Answer" },
{ nameof(QuestionDto.Analysis), "Analysis" },
{ nameof(QuestionDto.Difficulty), "Difficulty" },
{ nameof(QuestionDto.Score), "Score" },
{ nameof(QuestionDto.Tags), "Tags" },
{ nameof(QuestionDto.CreatedAt), "Created At" }
},
_ => new Dictionary<string, string> // 默认中文
{
{ nameof(QuestionDto.Id), "题目ID" },
{ nameof(QuestionDto.Type), "题型" },
{ nameof(QuestionDto.Content), "题目内容" },
{ nameof(QuestionDto.OptionA), "选项A" },
{ nameof(QuestionDto.OptionB), "选项B" },
{ nameof(QuestionDto.OptionC), "选项C" },
{ nameof(QuestionDto.OptionD), "选项D" },
{ nameof(QuestionDto.Answer), "答案" },
{ nameof(QuestionDto.Analysis), "解析" },
{ nameof(QuestionDto.Difficulty), "难度" },
{ nameof(QuestionDto.Score), "分值" },
{ nameof(QuestionDto.Tags), "标签" },
{ nameof(QuestionDto.CreatedAt), "创建时间" }
}
};
}
}
// 使用示例
[HttpGet("export")]
public async Task<IActionResult> Export(
[FromQuery] QuestionParameter searchParam,
[FromQuery] string language = "zh-CN") // 可选语言参数
{
var questions = await _questionService.GetAllForExportAsync(searchParam);
var result = await _excelExporter.ExportAsync(
questions,
QuestionExportConfig.GetColumns(language), // 根据语言获取列配置
$"题目列表_{DateTime.Now:yyyyMMddHHmmss}"
);
return File(result.Stream, result.ContentType, result.FileName);
}关键点:
- ✅ 不改变核心接口
- ✅ 通过配置类扩展
- ✅ 默认中文,可选其他语言
- ✅ 前端可以传递
language参数
问题5:多格式支持(预留扩展)
requirements:支持 Excel、CSV、PDF 等多种格式
设计方案:接口抽象 + 策略模式
1. 定义通用接口
csharp
namespace Common.Infrastructure.IO.Abstractions
{
/// <summary>
/// 数据导出接口(通用)
/// </summary>
public interface IDataExporter
{
/// <summary>
/// 支持的格式
/// </summary>
string Format { get; }
/// <summary>
/// 内容类型
/// </summary>
string ContentType { get; }
/// <summary>
/// 文件扩展名
/// </summary>
string FileExtension { get; }
/// <summary>
/// 导出数据
/// </summary>
Task<ExportResult> ExportAsync<T>(
IEnumerable<T> data,
Dictionary<string, string> columnMapping,
string fileName);
}
}2. 实现不同格式
csharp
// Excel 导出(当前实现)
public class ExcelExporter : IDataExporter
{
public string Format => "xlsx";
public string ContentType => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
public string FileExtension => ".xlsx";
public async Task<ExportResult> ExportAsync<T>(
IEnumerable<T> data,
Dictionary<string, string> columnMapping,
string fileName)
{
// MiniExcel 实现
// ...
}
}
// CSV 导出(预留)
public class CsvExporter : IDataExporter
{
public string Format => "csv";
public string ContentType => "text/csv";
public string FileExtension => ".csv";
public async Task<ExportResult> ExportAsync<T>(
IEnumerable<T> data,
Dictionary<string, string> columnMapping,
string fileName)
{
// CSV 实现(使用 CsvHelper 或手动实现)
// ...
throw new NotImplementedException("CSV 导出功能待实现");
}
}
// PDF 导出(预留)
public class PdfExporter : IDataExporter
{
public string Format => "pdf";
public string ContentType => "application/pdf";
public string FileExtension => ".pdf";
public async Task<ExportResult> ExportAsync<T>(
IEnumerable<T> data,
Dictionary<string, string> columnMapping,
string fileName)
{
// PDF 实现(使用 iTextSharp 或 QuestPDF)
// ...
throw new NotImplementedException("PDF 导出功能待实现");
}
}3. 导出工厂(策略模式)
csharp
namespace Common.Infrastructure.IO.Factories
{
/// <summary>
/// 导出器工厂
/// </summary>
public class ExporterFactory
{
private readonly IServiceProvider _serviceProvider;
public ExporterFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
/// <summary>
/// 获取导出器
/// </summary>
/// <param name="format">格式(xlsx, csv, pdf)</param>
/// <returns>导出器实例</returns>
public IDataExporter GetExporter(string format)
{
return format.ToLower() switch
{
"xlsx" => _serviceProvider.GetRequiredService<ExcelExporter>(),
"csv" => _serviceProvider.GetRequiredService<CsvExporter>(),
"pdf" => _serviceProvider.GetRequiredService<PdfExporter>(),
_ => throw new NotSupportedException($"不支持的导出格式:{format}")
};
}
}
}4. 注册服务
csharp
// Program.cs
builder.Services.AddScoped<ExcelExporter>();
builder.Services.AddScoped<CsvExporter>();
builder.Services.AddScoped<PdfExporter>();
builder.Services.AddScoped<ExporterFactory>();
// 兼容现有代码:默认使用 Excel
builder.Services.AddScoped<IExcelExporter>(sp => sp.GetRequiredService<ExcelExporter>());5. Controller 使用
csharp
/// <summary>
/// 导出题目(支持多种格式)
/// </summary>
/// <param name="searchParam">查询参数</param>
/// <param name="format">导出格式(xlsx, csv, pdf)</param>
[HttpGet("export")]
public async Task<IActionResult> Export(
[FromQuery] QuestionParameter searchParam,
[FromQuery] string format = "xlsx") // 默认 Excel
{
try
{
// 1. 获取数据
var questions = await _questionService.GetAllForExportAsync(searchParam);
if (!questions.Any())
{
return BadRequest(new { message = "没有符合条件的数据" });
}
// 2. 获取对应格式的导出器
var exporter = _exporterFactory.GetExporter(format);
// 3. 导出
var result = await exporter.ExportAsync(
questions,
QuestionExportConfig.GetColumns(),
$"题目列表_{DateTime.Now:yyyyMMddHHmmss}"
);
return File(result.Stream, result.ContentType, result.FileName);
}
catch (NotSupportedException ex)
{
return BadRequest(new { message = ex.Message });
}
catch (NotImplementedException ex)
{
return BadRequest(new { message = "该格式暂未实现" });
}
catch (Exception ex)
{
_logger.LogError(ex, "导出题目失败");
return StatusCode(500, new { message = "导出失败" });
}
}关键点:
- ✅ 接口抽象,易于扩展
- ✅ 工厂模式,统一管理
- ✅ 当前只实现 Excel,其他格式抛出
NotImplementedException - ✅ 前端可以通过
format参数选择格式
问题6:代码不要写死,便于扩展
设计原则:
1. 使用接口而不是具体类
csharp
// ❌ 写死:直接依赖具体实现
public class QuestionController
{
private readonly ExcelExportService _excelService; // 写死了 Excel
}
// ✅ 灵活:依赖接口
public class QuestionController
{
private readonly IExcelExporter _excelExporter; // 可以替换实现
}2. 配置外部化
csharp
// ❌ 写死:硬编码配置
public async Task<List<QuestionDto>> GetAllForExportAsync(QuestionParameter searchParam)
{
var totalCount = await query.CountAsync();
if (totalCount > 50000) // 硬编码
{
throw new InvalidOperationException("数据量过大");
}
}
// ✅ 灵活:配置参数化
public async Task<List<QuestionDto>> GetAllForExportAsync(
QuestionParameter searchParam,
int maxRows = 50000) // 可配置
{
var totalCount = await query.CountAsync();
if (totalCount > maxRows)
{
throw new InvalidOperationException($"数据量过大,超过最大限制({maxRows} 条)");
}
}3. 使用泛型而不是具体类型
csharp
// ❌ 写死:只能导出 QuestionDto
public async Task<ExportResult> ExportQuestions(List<QuestionDto> questions)
{
// ...
}
// ✅ 灵活:泛型,可以导出任何类型
public async Task<ExportResult> ExportAsync<T>(
IEnumerable<T> data,
Dictionary<string, string> columnMapping,
string fileName)
{
// ...
}4. 策略模式而不是 if-else
csharp
// ❌ 写死:if-else 判断格式
public async Task<IActionResult> Export(string format)
{
if (format == "xlsx")
{
// Excel 导出
}
else if (format == "csv")
{
// CSV 导出
}
else if (format == "pdf")
{
// PDF 导出
}
}
// ✅ 灵活:工厂模式 + 策略模式
public async Task<IActionResult> Export(string format)
{
var exporter = _exporterFactory.GetExporter(format); // 自动选择
var result = await exporter.ExportAsync(...);
return File(result.Stream, result.ContentType, result.FileName);
}步骤3总结
扩展性设计要点
| 方面 | 当前实现 | 扩展方式 |
|---|---|---|
| 多语言 | 中文列标题 | 配置类 + 语言参数 |
| 多格式 | Excel (xlsx) | 接口抽象 + 工厂模式 |
| 配置 | 硬编码 | 参数化、外部配置 |
| 类型 | 具体类型 | 泛型 |
| 策略 | if-else | 工厂模式 |
扩展示例
添加 CSV 导出(未来)
csharp
// 1. 安装包
dotnet add package CsvHelper
// 2. 实现 CsvExporter
public class CsvExporter : IDataExporter
{
public async Task<ExportResult> ExportAsync<T>(...)
{
using var writer = new StringWriter();
using var csv = new CsvWriter(writer, CultureInfo.InvariantCulture);
// 写入数据
await csv.WriteRecordsAsync(data);
var bytes = Encoding.UTF8.GetBytes(writer.ToString());
var stream = new MemoryStream(bytes);
return new ExportResult(stream, fileName);
}
}
// 3. 注册服务(已预留)
// Program.cs 中已有注册代码
// 4. 使用(无需修改 Controller)
// GET /api/question/export?format=csv添加多语言支持(未来)
csharp
// 1. 安装本地化包
dotnet add package Microsoft.Extensions.Localization
// 2. 修改配置类
public static class QuestionExportConfig
{
public static Dictionary<string, string> GetColumns(IStringLocalizer localizer)
{
return new Dictionary<string, string>
{
{ nameof(QuestionDto.Id), localizer["QuestionId"] },
{ nameof(QuestionDto.Type), localizer["QuestionType"] },
// ...
};
}
}
// 3. 使用(Controller 注入 IStringLocalizer)
var columns = QuestionExportConfig.GetColumns(_localizer);最终总结
完整方案概览
| 问题 | 解决方案 | 状态 |
|---|---|---|
| 查询复用 | BuildQuestionQuery 共享筛选逻辑 | ✅ 已设计 |
| 分页限制 | GetAllForExportAsync 不分页 + 数量检查 | ✅ 已设计 |
| 架构适配 | Controller + Service + ExcelExporter | ✅ 已调整 |
| 平级调用 | Controller 协调,Service 不互调 | ✅ 已明确 |
| 数据权限 | 在 BuildQuestionQuery 统一处理 | ✅ 已有 |
| 多语言 | 配置类 + 语言参数 | ✅ 已预留 |
| 多格式 | 接口抽象 + 工厂模式 | ✅ 已预留 |
| 扩展性 | 泛型 + 接口 + 配置参数化 | ✅ 已设计 |
实施优先级
第一阶段(立即实现)
- [x] 安装 MiniExcel
- [x] 创建 IExcelExporter 接口
- [x] 实现 ExcelExportService
- [x] QuestionService 添加 GetAllForExportAsync
- [x] QuestionController 添加 Export 接口
- [x] 创建 QuestionExportConfig
第二阶段(按需实现)
- [ ] 导入功能(IExcelImporter)
- [ ] 模板下载
- [ ] errors文件生成
第三阶段(未来扩展)
- [ ] CSV 导出
- [ ] PDF 导出
- [ ] 多语言支持
- [ ] 异步导出(大数据量)
关键文件清单
edua/Server/
├── Common/Infrastructure/IO/Excel/ # ✅ 实际目录
│ ├── Abstractions/
│ │ ├── IExcelExporter.cs # ✅ 已完成
│ │ └── IExcelImporter.cs # ✅ 已完成
│ ├── Services/
│ │ ├── ExcelExportService.cs # ✅ 已完成
│ │ └── ExcelImportService.cs # ✅ 已完成
│ └── Models/
│ ├── ExportResult.cs # ✅ 已完成
│ └── ImportResult.cs # ✅ 已完成
├── Model/ViewModels/Testing/
│ └── QuestionDto.cs # ✅ 已添加配置类
├── Services/Testing/
│ └── QuestionService.cs # ✅ 已添加方法
├── API/Controllers/Testing/
│ └── QuestionController.cs # ✅ 已添加 3 个接口
└── API/Program.cs # ✅ 已注册服务✅ 实施完成总结
已完成的工作
- [x] 所有代码已开发完成
- [x] 服务已注册(原生 DI)
- [x] MiniExcel 已添加到 Common.csproj
- [x] 配置类已创建(QuestionDto.cs 末尾)
待执行的任务
- [ ] 编译项目:
cd edua/Server/API && dotnet build - [ ] 运行项目:
dotnet run - [ ] 测试导出功能
- [ ] 测试模板下载
- [ ] 测试导入功能
关键差异
- 命名空间:
Common.Infrastructure.IO.Excel(实际多了 IO 层) - 配置位置:QuestionDto.cs 文件末尾(更简洁)
- 注册方式:原生 DI(项目标准)
第一阶段开发完成! 🎉
