Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Return Excel File

I have a requriement to upload a file and modify and then return the same. I dont need to save the file to any location but manipulate it and return. However I am not knowing how to return the file.

The below code allows the file to save, I even wrote code with out saving file. only problem is I am getting an error that this file is already open by someother user.

The process cannot access the file 'D:\Places\places\App_Data\877d36d3-ce29-48d1-995a-ea6652a528a7C2.xlsx' because it is being used by another process.

Can you please help me

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult FileUpload(HttpPostedFileBase uploadFile)
{
    if (uploadFile.ContentLength > 0)
    {
        string path = string.Empty;
        var fileName = Path.GetFileName(uploadFile.FileName);
        path = Path.Combine(Server.MapPath("~/App_Data/"), Guid.NewGuid() + fileName);
        uploadFile.SaveAs(path);

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(path);
        Excel._Worksheet xlWorksheet = (Excel._Worksheet)xlWorkbook.Sheets[1];
        Excel.Range xlRange = xlWorksheet.UsedRange;
        int rowCount = xlRange.Rows.Count; int colCount = xlRange.Columns.Count;
        (xlRange.Cells[4, 5] as Excel.Range).Value2 = "asdF";
        (xlRange.Cells[4, 6] as Excel.Range).Value2 = "asdF";
        (xlRange.Cells[4, 7] as Excel.Range).Value2 = "asdF";
        (xlRange.Cells[4, 8] as Excel.Range).Value2 = "asdF";

        releaseObject(xlWorksheet);
        releaseObject(xlWorkbook);
        releaseObject(xlApp);
        GC.Collect();

        uploadFile.InputStream.Dispose();
        return File(path, "application/text");

    }
    else
    {
        return View();
    }
}

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        //MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {enter code here
        GC.Collect();
    }
}
like image 486
user2132124 Avatar asked Nov 22 '25 01:11

user2132124


1 Answers

in the action you can return a FileStreamResult

return new FileStreamResult([memory stream], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

You also might want to close and save the workbook to a temp area before returning. From the error it looks like the file is still open.

like image 181
Stian Standahl Avatar answered Nov 24 '25 22:11

Stian Standahl