I had written a code to first get an SSRS report and write to excel and save in a folder on server , manipulate the same excel through code and then save it again and then render it in excel for download.
The code was working fine but then suddenly I started getting the error:
The process cannot access the file 'G:\TestEnvironment\
TestSite_ForDeveloper\
Reports\10697696.xls' because it is being used by another process.
What could be the issue?
Following is the code used:
//Getting SSRS report
//code
//Saving SSRS report result in excel
try
{
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet NwSheet;
appExl = new Microsoft.Office.Interop.Excel.Application();
string serverPath = Server.MapPath(".");
string filenameToLoad = serverPath + "\\Page1Reports\\" + Session["UserAccentureID"].ToString() + ".xls";
FileStream fileStream = new FileStream(filenameToLoad, FileMode.Create, FileAccess.ReadWrite, FileShare.Read);
fileStream.Write(result, 0, result.Length);
fileStream.Close();
//Manipulation of file
//Done something
workbook.Save();
workbook.Close();
appExl.Quit();
System.IO.FileInfo file = new System.IO.FileInfo(filenameToLoad);
//Rendering again to excel download
if (file.Exists)
{
string lblrptname = "Page1SLScoreCardReport_" + ddlFiscalWeek.SelectedValue.ToString();
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.ContentType = "Application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=" + lblrptname + ".xls");
Response.AddHeader("Cache-Control", "max-age=0");
Response.WriteFile(file.FullName);
}
}
catch (Exception ex)
{
AlnErrorHandler.HandleError(ex);
}
finally
{
if (appExl != null )
appExl.Quit();
}
maybe check Processes under Task Manager to see if any extra EXCEL.EXE processes are running? Excel will run in the background and hold on to your file if not exited properly and cause all kinds of confusion (at least it did for me ;) ).
Related
I have an excel file template, and then add dropdown data to excel using C#, everthing is fine in my local machine, i can download it but when i put it in server is always getting error
and actually, this error file still can be used, but its really annoying especially for user
i,m using NPOI for processing this excel file
XSSFWorkbook hssfwb;
string path = Server.MapPath("~/Content/Uploads").ToString() + ConfigurationManager.AppSettings["PathAllocationRuleTemplate"].ToString();
string newpath = Server.MapPath("~/Content/Uploads").ToString() + ConfigurationManager.AppSettings["PathAllocationRule"].ToString();
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
hssfwb = new XSSFWorkbook(file);
file.Close();
}
> some code for filling data
**downloading part**
using (FileStream file = new FileStream(newpath, FileMode.Create, FileAccess.Write))
{
hssfwb.Write(file);
file.Close();
}
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
response.AddHeader("Content-Disposition", "attachment; filename=Allocation Rule Template.xlsx");
response.TransmitFile(newpath);
response.Buffer = true;
response.Flush();
response.End();
I'm working on adding Export functionality to an existing site. I've created an Excel file, and I'm able to output it to my local directory, but when I try pushing the file to the user using Response, nothing happens. I've viewed several differnet articles and Stack questions, and none seem to be different from what I have, or work when I apply them.
Here is the code I currently have:
public void Export () {
//Create instance of the database
ExportContext eDB = new ExportContext();
var query = (from x in eDB.EMPLOYEES
select x);
IEnumerable<EMPLOYEES> employees = query.ToList();
//Set filename to Table + date/time
string fileName = "EMPLOYEES" + DateTime.Now.ToShortTimeString() + ".xlsx";
//Create excel package
ExcelPackage excel = new ExcelPackage();
var worksheet = excel.Workbook.Worksheets.Add("Employees");
worksheet.Cells[1, 1].LoadFromCollection(employees, true);
using (var memoryStream = new MemoryStream()) {
//Output the file to the user via download
Response.Buffer = false;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
Response.End();
}
}
Any help will be appreciated. Thanks.
I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
I have tried the below coding for generating excel file on serverside.
C# CODING:
public void ReadandOpenExcel(DirectoryInfo outputDir)
{
//FileInfo newFile = new FileInfo(outputDir.FullName + #"\New Microsoft Excel Worksheet.xlsx");
var ExistFile = Server.MapPath("~/excelsample.xlsx");
var File = new FileInfo(ExistFile);
using (ExcelPackage package = new ExcelPackage(File))
{
package.Load(new FileStream(ExistFile, FileMode.Open));
ExcelWorksheet workSheet = package.Workbook.Worksheets["Sheet1"];
workSheet.Cells["A8"].Value = "kevin";
package.Save();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment; filename=ProposalRequest.xslx");
**Response.BinaryWrite(package.GetAsByteArray());**
// myMemoryStream.WriteTo(Response.OutputStream); //works too
Response.Flush();
Response.Close();
}
}
While running the above code i got an error as : " Package object was closed and disposed, so cannot carry out operations on this object or any stream opened on a part of this package."
ERROR On This Line:
Response.BinaryWrite(package.GetAsByteArray());
Make some way for this coding to move on.
Thanks in advance.
Does it work if you get the bytes before you do the Save ?
Byte[] bin = package.GetAsByteArray();
package.Save();
And then use that value in the Binarywrite;
Response.BinaryWrite(bin);
Maybe it is getting closed on the .Save() call ?
I've been searching around the internet, but couldn't find any useful answer.
I have an ASP.NET web site, which is deployed on server.
The ASP.NET web site on the server can access a directory called W:/ .
The clients in the company can access the web site. The web site lists in a ListBox all the PDF files from the W:/ directory. The client should be able to select PDF files from the listbox and save them to it's local PC by selecting a location for it.
Something like save as file on web pages.
Could you provide me some solution or work around ?
Finally I've found an article, which Prompts a Save Dialog Box to Download a File from ASP.NET
I post it here, might help somebody else as well and save some time.
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
This is an extension to user1734609's solution that gets a file locally.
To download a file from the server to client:
public void DownloadFile()
{
String FileName = "201604112318571964-sample2.txt";
String FilePath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/Uploads/" + FileName;
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
}
The correct keywords are "File Browser asp.net" to find a lot of examples with source code.
Here is one from codeproject:
http://www.codeproject.com/Articles/301328/ASP-NETUser-Control-File-Browser
Get file contents in byte[] from W drive and write it to local file.
byte[] data = File.ReadAllBytes(WDriveFilePath)
FileStream file = File.Create(HttpContext.Current.Server.MapPath(MyLocalFile));
file.Write(data, 0, data.Length);
file.Close();
I have done something like this to get the file .
protected void btnExportFile_Click(object sender, EventArgs e)
{
try
{
Thread newThread = new Thread(new ThreadStart(ThreadMethod));
newThread.SetApartmentState(ApartmentState.STA);
newThread.Start();
// try using threads as you will get a Current thread must be set to single thread apartment (STA) mode before OLE Exception .
}
catch (Exception ex)
{
}
}
static void ThreadMethod()
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}