I don't understand what is missing here. I am trying to export a file in csv format with extended ASCII characters like ÿ or ü but all i get is �
Do I need to specify something else in the response?
Encoding encoding = Encoding.UTF8;
//ToCSV writes the string correctly
var bytes = encoding.GetBytes("write ÿ or ü please");
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
//TextWriter tw = new TextWriter();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", fileName));
Response.Charset = encoding.EncodingName;
Response.ContentType = "application/text";
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
I believe you should add Response.ContentEncoding = Encoding.Unicode to get right output.
Encoding encoding = Encoding.UTF8;
var bytes = encoding.GetBytes("write ÿ or ü please");
MemoryStream stream = new MemoryStream(bytes);
StreamReader reader = new StreamReader(stream);
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.csv", "filename"));
Response.Charset = encoding.EncodingName;
Response.ContentType = "application/text";
Response.ContentEncoding = Encoding.Unicode;
Response.Output.Write(reader.ReadToEnd());
Response.Flush();
Response.End();
Unfortunately Encoding.Unicode didn't work, using Windows-1252 worked :
Response.Clear();
Response.ContentType = "Application/x-msexcel";
Response.AddHeader("content-disposition", "attachment; filename=\"filename.csv\"");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("Windows-1252");
Response.Write(string.Join(Environment.NewLine, myDataLines));
Response.End();
I'm a Java programmer, are you sure you need a StreamReader? I guess StreamReader(stream) may decode the bytes in a different charset. And, You've already got the bytes, maybe you could write the bytes to response directly.
Related
I can generate the Pdf but I want to save the pdf in folder before show to the view.
I have read many articles but I did not find any proper solution.
Here is my code.
ReportDocument rd = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports"), "BillInformationReport.rpt"));
rd.SetDataSource(ds);
Stream stream = rd.ExportToStream(ExportFormatType.PortableDocFormat);
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
Byte[] fileBuffer = ms.ToArray();
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", fileBuffer.Length.ToString());
Response.BinaryWrite(fileBuffer);
rd.Close();
rd.Dispose();
return null;
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
When I try to convert binary file to PDF the pdf has damaged.
byte[] stream = presenter.getItemTable();
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader ("Content-Disposition", "attachment; filename=PressRelease.pdf");
Response.BinaryWrite(stream);//Entities.EDRSearchResult.ByteStream);
Response.Flush();
Response.End();
However when I convert same binary to Excel it is working fine and can open without any error.
byte[] stream = presenter.getItemTable();
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition","attachment;filename=DataTable.xls");
Response.BinaryWrite(stream);
Response.Flush();
Response.End();
Please help me.
when you try to convert binary file to PDF in this case you write
Response.AddHeader ("Content-Disposition", "attachment; filename=PressRelease.pdf");
Try
Response.AddHeader ("content-disposition", "attachment; filename=PressRelease.pdf");
I had problem with export data to .csv file. I use 2 methods.
Encoding csvEncoding = new UTF8SignatureEncoding();
byte[] csvFile = TestByte(CsvContentDelimiter.NewLine, CsvContentDelimiter.Semicolon, csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
And
public byte[] TestByte(CsvContentDelimiter rowDelimiter, CsvContentDelimiter columnDelimiter, Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.Append("product;");
return encoding.GetBytes(sb.ToString());
}
This code create .csv file, but file have bad Encoding and i see only some "hash"
Here is a fully working example using UTF8 formatting. It uses your own code so shows that it is your Encoding that is causing the issue:
namespace WebApplication1
{
using System;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
protected void btnExport_Click(object sender, EventArgs e)
{
// Use UTF8 encoding
Encoding csvEncoding = Encoding.UTF8;
byte[] csvFile = TestByte(csvEncoding);
string attachment = String.Format("attachment; filename={0}.csv", "docs_inv");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "text/csv";
Response.ContentEncoding = csvEncoding;
Response.AppendHeader("Content-Disposition", attachment);
Response.BinaryWrite(csvFile);
Response.Flush();
Response.End();
}
public byte[] TestByte(Encoding encoding)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("Record1,Fred,Bloggs,26{0}", Environment.NewLine);
sb.AppendFormat("Record2,John,Smith,32{0}", Environment.NewLine);
return encoding.GetBytes(sb.ToString());
}
}
}
What is my issue here? When I write the stream back out to web, open the file it contains some of the content but all malformed and some missing.
Am I experiencing loss of data due to a logic error?
Note: the readstream and writestream below mocks up what a service will be filling in. I will be receiving a stream to read from the service. I'll need to write that stream back out.
MemoryStream writeStream = new MemoryStream();
byte[] buffer = new byte[256];
OrderDocument doc = new OrderDocument();
doc.Format = "xml";
doc.DocumentId = "5555555";
doc.Aid = "ZZ";
doc.PrimaryServerPort = "PORT";
MemoryStream readStream = new MemoryStream(doc.GetDocument());
while (readStream != null && readStream.Read(buffer, 0, buffer.Length) > 0)
{
writeStream.Write(buffer, 0, buffer.Length);
}
writeStream.Flush();
writeStream.Position = 0;
Response.Buffer = true;
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/xml";
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", doc.DocumentId));
Response.AddHeader("Content-Length", writeStream.Length.ToString());
Response.BinaryWrite(writeStream.ToArray());
Response.End();
Am I experiencing loss of data due to a logic error?
Yes probably, you may try simplifying your code a little bit. I don't really see the need of multiple memory streams here:
OrderDocument doc = new OrderDocument();
doc.Format = "xml";
doc.DocumentId = "5555555";
doc.Aid = "ZZ";
doc.PrimaryServerPort = "PORT";
byte[] buffer = doc.GetDocument();
Response.Buffer = true;
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", doc.DocumentId));
Response.OutputStream.Write(buffer, 0, buffer.Length);