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();
Related
I'm trying to read files from my database (varbinary) and add them to a zip file so that users can download all files related to a specific user.
From what I can gather, I need to read the files from the database, create the zip file, read the files into memory and then write that to the file (doing it without this returned a blank zip file).
It will save the files to the zip, but unfortunately the files are all corrupted.
public FileResult DownloadAllDocuments(int userId)
{
// File name
string ZipFilename = DateTime.Now + "_Files.zip";
// Get files from database
List<DocumentVO> Documents = DocumentDAO.DownloadAllDocuments(userId);
var zipFileMemoryStream = new MemoryStream();
using (ZipArchive archive = new ZipArchive(zipFileMemoryStream, ZipArchiveMode.Update, leaveOpen: true))
{
foreach (DocumentVO document in Documents)
{
var entry = archive.CreateEntry(document.fileName, CompressionLevel.Fastest);
using (var entryStream = entry.Open())
{
entryStream.Write(document.File, 0, document.File.Length);
}
}
}
zipFileMemoryStream.Seek(0, SeekOrigin.Begin);
return File(zipFileMemoryStream, "application/octet-stream", ZipFilename);
}
Please try these codes instead of return File line
using (MemoryStream ms = new MemoryStream())
{
zip.Save(ms);
Response.ClearHeaders();
Response.ClearContent();
Response.Charset = "";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + ZipFilename);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/zip";
Response.BinaryWrite(ms.ToArray());
}
I have the data that has to be loaded to an excel file in a byte array and I need to apply password protection on that.
I have tried converting byte[] to datatable/list and tried applying password protection using Excelpackage but I am not able to correctly convert data in byte[] array to any form.My file is getting downloaded but with some weired data. Can anyone please share your knowledge?
response.Clear();
response.Buffer = true;
response.ContentEncoding = System.Text.Encoding.UTF8;
response.ContentType = mimeType;
response.AddHeader("content-disposition", "attachment;filename="
+ Uri.EscapeDataString(fileName));
response.Charset = "";
response.Cache.SetCacheability(HttpCacheability.NoCache);
DataTable dt;
MemoryStream stream;
using (stream = new MemoryStream(fileBytes))
{
BinaryFormatter bin = new BinaryFormatter();
stream.Seek(0, SeekOrigin.Begin);
dt = (DataTable)formatter.Deserialize(stream);
stream.Close();
}
using (ExcelPackage pack = new ExcelPackage())
{
ExcelWorksheet ws = pack.Workbook.Worksheets.Add("heelo");
ws.Cells["A1"].LoadFromDataTable(dt, true);
pack.Save("123");
var ms = new System.IO.MemoryStream();
pack.SaveAs(ms);
ms.WriteTo(HttpContext.Current.Response.OutputStream);
ms.Close();
}
response.Flush();
response.End();
Having a little trouble following you code. Why is response mime type a PDF? I think you would want that to be
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Does response actually have anything to do with the MemoryStreams since I see no reference from one to the other?
In any event, if you have the ExcelPackage available and you want to write to a Stream with a password, you can just call the overload:
pack.SaveAs(ms, "MyPassword")
Here is some more info: Password Protected Excel Download using EPPLUS
I am trying to create dynamically created, downloadable ZIP files. The files are created correctly on the server, however when they are sent to the client using "Response.OutputStream" the file becomes corrupted. This only seems to happen when the zip file is over 4GB. Does anyone have any idea why this is?
The exact code I am using is:
string path = #"C:\temp\vid";
Response.BufferOutput = false; // Disable Buffer Output to start the download immediately
// Set custom headers to force browser to download the file instad of trying to open it
Response.ContentType = "application/x-zip-compressed";
Response.AppendHeader("content-disposition", "attachment; filename=Archive.zip");
ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream, 20000);
zipOutputStream.SetLevel(0); // No compression
zipOutputStream.UseZip64 = UseZip64.On;//Forces Zip64 to be used
zipOutputStream.IsStreamOwner = true;
try
{
foreach (string file in Directory.GetFiles(path, "*.*", SearchOption.AllDirectories))
{
using (var fs = System.IO.File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
ZipEntry entry = new ZipEntry(ZipEntry.CleanName(Path.GetFileName(file))); //Create zip compatible name
zipOutputStream.PutNextEntry(entry); //Adds entry to list
fs.CopyTo(zipOutputStream);
zipOutputStream.CloseEntry();
zipOutputStream.Flush();
Response.Flush();
Response.Clear();
}
}
zipOutputStream.Finish();
zipOutputStream.Close();
Response.End();
Response.Flush();
}
catch
{
Debug.WriteLine("Connection Closed or error");
}
return new HttpStatusCodeResult(HttpStatusCode.OK);
How do i download a file in asp.net?
here is what i did to upload it:
I upload the file into the website and saved the url to it in a database like this:
string CVPath = null;
if (uploadfiles.HasFile)
{
string file = uploadfiles.FileName;
uploadfiles.PostedFile.SaveAs(Server.MapPath(".") + "//CV//" + file);
CVPath = "~//ProfileImages//" + file;
FileName.InnerText = file;
}
else
CVPath = "";
and then I save the "CVPath" in a database
To download a file, first you need to read all the contents to a string.
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("YourString");
tw.Flush();
byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=file.txt");
Response.BinaryWrite(bytes);
Response.End();
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 ?