Export to Excel file name - asp.net

I wrote this codes for export GridView to Excel :
System.Web.HttpContext.Current.Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = System.Text.Encoding.UTF8.EncodingName;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
string FileName = Title + ".xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
but file name does not show correctly for non english names(Such as Arabic). How I can save file with non english names?
thanks

Wrap file name With
Server.UrlEncode
for example:
string FileName = Server.UrlEncode(Title + ".xls");
and it works!!!!

Related

How to Remove default underscore in asp.net while downloading the file

protected void DownloadFile(object sender, EventArgs e)
{
string param = Request.QueryString["id"];
//int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
SqlCommand cd = DbCon._dbConnection.CreateCommand();
cd.CommandType = CommandType.Text;
cd.CommandText = "select id from student_registration where id = '" + param + "'";
cd.ExecuteNonQuery();
SqlCommand cmd = DbCon._dbConnection.CreateCommand();
cmd.CommandText = "select books_pdf from books where id = '" + param + "'";
// cmd.Parameters.AddWithValue("#Id", param);
String s1 = cmd.ExecuteScalar().ToString();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
//bytes = (byte[])sdr["Data"];
//contentType = sdr["ContentType"].ToString();
fileName = sdr["books_pdf"].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "/";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
//Response.AppendHeader("Content-Disposition", "attachment; filename=" +fileName);
// Response.TransmitFile(Server.MapPath("~/Files/"+ fileName));
// Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
This is the code where I have written to download the file. but the result what am getting correct file but '/' is replaced with 'underscore;
My question is how to remove that underscore and add '/' in place of underscore I have attached the image please check that and please help me in finding the solutionenter image description here
enter image description here
image shows the path stored in database and error what I am facing to download
fileName = "../librarian/" + sdr["books_pdf"].ToString();
}
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(fileName) + "\"");
byte[] data = req.DownloadData(Server.MapPath(fileName));
response.BinaryWrite(data);
response.End();
Proper Selection of File was not given later i corrected proper file location than i got proper output

ASP.Net Open office XML Set the values of a cell

I am using ASP.Net and Open office XML and I have been able to set the headers of the excel file.
However, I want to set the value to cells from say D2 to D1000 in a drop down fashion i.e. that the user can only select from a predefined list of values as in a drop down list.
How do I accomplish this?
The code for creating the excel is
List<ExcelExport> mpList = new List<ExcelExport>();
DataTable dt = ListToDataTable(mpList);
string attachment = string.Format("attachment;filename={0}-{1}.xlsx", ddlHealthFacility.SelectedItem.Text + " Excel export ", " ");
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Monthly Plan");
ws.Cells["A1"].LoadFromDataTable(dt, true);
Byte[] fileBytes = pck.GetAsByteArray();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", attachment);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
Response.BinaryWrite(fileBytes);
Response.End();
}

Download Gridview Error data

I am working on a project, where I want to download gridview row data, but it is not working for me. Here is the code i used for download:
string fileName = "chhattisgarhishafte" + DateTime.Now.ToString() + ".doc";
GridView1.DataSource = dtD;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-word ";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderBeginTag(hw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
GridView1.RenderEndTag(hw);
Response.Flush();
Response.End();
stD is datatble which stores the gridview selected rows.
The errror is:
Control 'ctl00_ContentPlaceHolder1_GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Please use in form tag in the master page use runat="server"
use this code,its working in my application
if (gv.Rows.Count > 0)
{
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
//Get the HTML for the control.
gv.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName);
EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}

How could i export gridview data to ms word

I am working on asp.net 4.0 web application development using c#. I am trying to export the Gridview data to ms word document. I have used the following code.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=MyWord.doc");
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.ContentType = "application/vnd.word";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.GridView1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();
Response.End();
The application is running without problems but it returns the data in word like
+ADw-div+AD4- +ADw-table cellspacing+AD0AIg-0+ACI- cellpadding+AD0AIg-4+ACI- id+AD0AIg-GridView1+ACI- style+AD0AIg-color:+ACM-333333+ADs-border-collapse:collapse+ADsAIgA+- +ADw-tr style+AD0AIg-color:White+ADs-background-color:+ACM-507CD1+ADs-font-weight:bold+ADsAIgA+- +ADw-th scope+AD0AIg-col+ACIAPg-FileId+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-PortalId+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-FileName+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Extension+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Size+ADw-/th+AD4APA-th scope+AD0AIg-col+ACIAPg-Width+ADw-
I know it is much similar to html but how could i convert this into actual one. guide me.
this is works for me it requires itextsharp.dll
string FName = "filename.doc";
mygrid.AllowPaging = false;
mygrid.DataSource = datasource();
mygrid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", FName));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
mygrid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();

How to export an mschart chart to excel?

I have created a chart with Mschart.I want to export the created chart to excel.
I'm using following code but when I open it in excel I just see some unknown code instead of chart.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Hope this helps.
I also came across such scenario in one of my project.
Here is the solution.
http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html
Add this code for your globalization, this works for me.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8

Resources