Hi @Marvelocity ,
In your previous reply (using EPPlus), in the API method, try to return the File object, without the Ok method. Code like this:
return File(fileBytes,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"MyExcel-" + DateTime.Now.ToShortDateString() + ".xlsx");
Then, use Swagger or Postman to check the API method, whether you could download the excel file or not, and whether you can open the excel file or not?
If the excel file still is broken, perhaps the issue relates the file content or the EPPlus.
Besides, I suggest you could refer the following sample to use ClosedXML to export data to excel:
[Route("api/[controller]")]
[ApiController]
public class ToDoController : ControllerBase
{
[HttpGet("exporttoexcel")]
public async Task<ActionResult> ExportToExcel()
{
using (var workbook = new XLWorkbook())
{
var worksheet = workbook.Worksheets.Add("Users");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "Id";
worksheet.Cell(currentRow, 2).Value = "Username";
var users = new List<User>();
for (var i = 1; i < 10; i++)
{
users.Add(new Models.User() { UserId = i, UserName = "User" + i.ToString() });
}
foreach (var user in users)
{
currentRow++;
worksheet.Cell(currentRow, 1).Value = user.UserId;
worksheet.Cell(currentRow, 2).Value = user.UserName;
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(
content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"users.xlsx");
}
}
}
Then, in the main page, use the following hyperlink to call the API method and download excel file:
<a href="~/api/Todo/exporttoexcel" download>Download File</a>
The above code works well on my side, you can refer it.
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best Regards,
Dillion