Hello, right now I'm working on a fullstack app (frontend is React.js and backend is .NET Core 3.1 Web API). API is build using CQRS architecture. One of its features is generating an Excel file (in .xlsx format) on backend, which user can download using frontend. My problem is that I have no idea what to put into the controller in order to make it work.
Here is the controller:
[Route("api/[controller]")]
[ApiController]
public class ExcelController : BaseApiController
{
private IMediator _mediator;
public ExcelController(IMediator mediator)
{
_mediator = mediator;
}
[HttpPost]
public async Task<IActionResult> GetAll(GetExcelReportQuery getExcelReportQuery)
{
var files = await _mediator.Send(getExcelReportQuery);
using (MemoryStream ms = new MemoryStream())
{
return File(ms, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "ExcelReports_" + DateTime.Now.ToString() + ".xlsx");
}
}
}
Here is the query:
public class GetExcelReportQuery : IRequest<Dictionary<string, byte[]>>
{
public List<Guid> Ids { get; set; }
public class GetExcelReportQueryHandler : IRequestHandler<GetExcelReportQuery, Dictionary<string, byte[]>>
{
private readonly IReadDbContext _context;
private readonly IXlsxExporter _xlsxExporter;
public GetExcelReportQueryHandler(IReadDbContext context, IXlsxExporter xlsxExporter)
{
_context = context;
_xlsxExporter = xlsxExporter;
}
public async Task<Dictionary<string, byte[]>> Handle(GetExcelReportQuery query, CancellationToken cancellationToken)
{
var projectData = _context.ExcelReports.Where(x => query.Ids.Contains(x.ProjectId));
var result = new Dictionary<string, byte[]>();
var createExcel = _xlsxExporter.GenerateXlsxFileFromData(projectData, true);
result.Add("ExcelData", createExcel);
return result;
}
}
}
And here is frontend function, which is supposed to download the file:
downloadExcel() {
console.log(this.state);
var ids = [];
this.state.projects.map((project) => {
ids.push(project.projectId);
});
var GetExcelReportQuery = {
Ids: ids,
};
console.log(GetExcelReportQuery)
axios({
url: process.env.REACT_APP_API_BASE_URL + "/Excel",
data: GetExcelReportQuery,
method: "POST",
responseType: "blob",
}).then((response) => {
console.log(response.data);
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", "ExcelReports.xlsx");
document.body.appendChild(link);
link.click();
});
}
What I have tried:
I have tried out multiple solutions using MemoryStream, to no success.