Generate .csv UTF8 with ExcelPackage() - c#

I am trying to generate a csv with UTF8 encoding with c#, using ExcelPackage (). Excel is identifying the file as .xlsx and not UTF8. My code:
using (ExcelPackage package = new ExcelPackage())
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("myName");
int y = 1;
foreach (IDictionary<string, string> elemento in losDatos)
{
ws.Cells["A" + y].Value = "+ DisposiciĆ³n de contacto";
ws.Cells["B" + y].Value = "Llamada detallada";
...
...
ws.Cells["AL" + y].Value = "1";
y++;
}
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
I have tried some changes, only in the Response piece, and now the csv recognizes me, but the characters are strangers:
Response.Clear();
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
Response.BinaryWrite(package.GetAsByteArray());
Response.End();

Replace
Response.ContentType = "application/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".csv");
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
with
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=myName" + DateTime.Now.ToString("yyyyMMdd_HHmm") + ".xlsx");
and you are done.
If you want a CSV, use a different package but then do consider adding charset to the Content-Type header. If Open XML is not your thing, then OpenDocument Spreadsheet (.odt, LibreOffice) would be equally better than CSV.

Related

Shows warning message in exported xlsx file

My xlsx file is downloaded but when I open that xlsx file it shows warning as
'We found a problem with some content in'.
Can anyone tell me where I have to fix this? I am using an iFrame to download the file.
using (ClosedXML.Excel.XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt, "Sheet1");
Response.Clear();
Response.Charset = "";
Response.Buffer = true;
Response.BinaryWrite(bytes);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=" + >Model.reportName + "_" + DateTime.Now.ToString("yyyyMMddHH:mm") + "." + extension);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}

Date appears as number while exporting data to excel in C#

string fileName = "test" + DateTime.Now.ToShortDateString();
using (package = new ExcelPackage(newFile, "file"))
{
generateReport();//this function generates a worksheet
package.Workbook.Properties.Title = #"Title of project";
package.Workbook.Properties.Author = "Sri";
package.Workbook.Properties.Subject = #"Report";
byte[] rawData = package.GetAsByteArray();
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".xlsx");
Response.BinaryWrite(rawData);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.Flush();
Response.End();
Hi,when i try to export datatable to excel ,columns which has date appears as numbers in the excel file.When i further check these numbers are DATEVALUE(date)(this function is used in excel) results of excel.

Excel and CSV export does not show Persian characters correctly

When exporting SQL Server data to .csv, phrases in Persian don't show up correctly.
string date = Helper.ToPersianDate(DateTime.Now).Replace("/", "");
date += ".csv";
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + date);
Response.ContentType = "text/csv";
Response.Charset = Encoding.Unicode.ToString();
foreach (DataRow r in ds.Tables[0].Rows)
{
Response.Write(r[0]);
Response.Write("\r\n");
}
Response.End();
string date = Helper.ToPersianDate(DateTime.Now).Replace("/", "");
date += ".csv";
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=" + date);
Response.ContentType = "text/csv";
Response.Charset = Encoding.Unicode.ToString();
Response.ContentEncoding = System.Text.Encoding.Unicode;
/*
save utf-8 with BOM
GetPreamble
*/
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
foreach (DataRow r in ds.Tables[0].Rows)
{
Response.Write(r[0]);
Response.Write("\r\n");
}
Response.End();

Why doesn't asp.net download work?

I am using this code to download a image i.e. I am storing Image name with extension in database and getting it here.
this code throws no error but doesn't download anything. why ?
try {
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
Update:
i tried this but doesn't work.
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath).CopyTo(m);
m.WriteTo(Response.OutputStream);
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
Create a Stream using following code
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);
You're on the right track using TransmitFile. Check this line:
Response.ContentType = ContentType;
It looks like you're setting the ContentType to the page's default.
Try specifying it explicitly:
Response.ContentType = "image/jpeg";

Create Zip in c#

I am actually wondering why when I create a zip file, and I download it just after, I can't open it because it's broken ..
This is the code I am actually using .
string url = ((LinkButton)sender).Tag;
var downloadFileName = string.Format(((LinkButton)sender).ID + ".zip");
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C://inetpub//wwwroot//Files//Wireframes//" + url);
using (ZipFile zip = new ZipFile())
{
zip.AddEntry("C://inetpub//wwwroot//Files//Wireframes//" + url, zip.Name);
zip.AddDirectory("C://inetpub//wwwroot//Files//Wireframes//" + url);
zip.Save(downloadFileName);
}
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Also, I am adding directly all the directories with their files inside.
You are not sending the actual data.
Response.ContentType = "application/zip";
Response.AddHeader("Content-Disposition", "filename=" + downloadFileName);
Response.TransmitFile(downloadFileName);
Response.End();

Categories