In my .net core 2.2 MVC web app, I am currently generating a .docx file using OpenXML SDK Productivity Tool.
Currently, when the user fills in the form on my View and hits Submit, the OpenXML code is triggered and the word doc is generated, and emailed to a user. What I now need is the word document file to be also available to download for that user.
I'm not sure how to re-work my code to get this to work. Below is my [HTTPPost]
method:
[HttpPost]
public ActionResult AddReferralForm(ReferralForm referralForm)
{
try
{
//generate word document of the referral form
var GeneratedClassOpenXML = new OpenXMLGeneratedClass();
var wwwRoot = _env.WebRootPath;
string constructedFilename = DateTime.Now.ToString("yyyyMMdd") + "_"+ DateTime.Now.ToString("HHmm") + "_";
string fileName = referralFormsLocation + constructedFilename+".docx";
var emailaddressToSendForm = _context.ReferralFormEmailAddresses.FirstOrDefault();
//Generate Word Document referral form - uses Open XML SDK
GeneratedClassOpenXML.CreatePackage(fileName, referralForm, LoggedInUser, emailaddressToSendForm.EmailAddress);
//method for user to download the word doc
ExportReferral(fileName);
return RedirectToAction("Index", "Home", new { id = LoggedInUser.Id });
}
catch (Exception ex)
{
throw new Exception("Error when saving a referral - " + ex);
}
}
This method redirects the user back to Home/Index
. The emailing of the generated word document is within GeneratedClassOpenXML.CreatePackage()
.
I thought something like this code could work, with my HTTPPost method above calling this, but this didn't work:
[HttpGet]
public IActionResult ExportReferral(string filePath)
{
var x = System.IO.File.ReadAllBytes(filePath);
return File(System.IO.File.ReadAllBytes(filePath),
contentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
fileDownloadName: "MySheet.docx");
}
I am trying to look for a way to return the user to the home page and return the file content. Any way to achieve this?
Thanks
question from:
https://stackoverflow.com/questions/65904517/how-to-serve-a-downloadable-docx-file-created-with-openxml-sdk-in-net-core 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…