Firstly, here is my code:
DataTable usersReport = reportsService.GenerateUsersReport();
var grid = new GridView();
grid.DataSource = usersReport;
grid.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=UsersReport.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
As you can see, I just generate in simply way report about users. When I open this file in excel, there is a problem with special chars, like ś,ż,ź,ó,ę,ą etc.
Instead of Imię I can see ImiÄ™.
The same issue with Gyżyński
How can I resolve it?
EDIT:
Add that lines:
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Now Imię looks like Imiê. In conclusion - still nothing
Did you try this? It could be that the header of the excel file missing the Byte Order Mark(BOM) sequence, try using GetPreamble
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=UsersReport.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
After a little investigation I discover a solution. Important is <meta> tag for source HTML.
so that line:
Response.Output.Write(sw.ToString());
should looks like:
Response.Output.Write("<meta http-equiv='Content-Type' content='application/vnd.ms-excel; charset=utf-8'>" + sw.ToString());
Following code will Wrk for Speical char and remove null from Excel to
From datatable we are creating Excel which Write Special charater also
The main trick is making it UTF-32 and applying BinaryWrite
public void DataTableToExcel(DataTable dt)
{
string attachment = "attachment; filename=download.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentEncoding = System.Text.Encoding.UTF32;
Response.BinaryWrite(System.Text.Encoding.UTF32.GetPreamble());
Response.ContentType = "application/vnd.xls";
string tab = "";
foreach (DataColumn dc in dt.Columns) // table col
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int i;
string content = "";
foreach (DataRow dr in dt.Rows) // Data Row by row
{
tab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
content = dr[i].ToString();
content = content.Replace(System.Environment.NewLine, " ");
Response.Write(tab + content);
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
Related
I have a working method, that export to excel, but the issue is file extension is not support and being not format. This is not user friendly, how can I improve this from not allow a user to see this issue?
// controller
public void ExportToExcel()
{
var v = new GridView();
v.DataSource = this.GetExtractionViewModels();
v.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=ExtractionRecords.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(objStringWriter);
v.RenderControl(htmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
//return View("DataResult");
}
I have trying to export my data from my data access layer
but nothing happens no error and not exported.
it is kinda hard to know whats wrong because there's no error
I have tried this:
if (dt.Rows.Count > 0){
dgv.DataSource = dt;
dgv.DataBind();
Response.ClearContent();
Response.AppendHeader("content-disposition","attachement;filename=transaction.xls");
Response.ContentType = "application/excel";
StringWriter stringWritter = new StringWriter();
HtmlTextWriter htmlTextWritter = new HtmlTextWriter(stringWritter);
dgv.RenderControl(htmlTextWritter);
Response.Write(stringWritter.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
butnothing happens.
i have tried this but also nothing:
StringWriter osStringWritter = new StringWriter();
Html32TextWriter osHtmlTextWritter = new Html32TextWriter(osStringWritter);
DataTable dt = new DataTable();
DataGrid dgv = new DataGrid();
Response.Clear();
Response.Buffer = false;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", "TransactionReport"));
Response.Charset = "";
dgv.DataSource = dt;
dgv.DataBind();
dgv.RenderControl(osHtmlTextWritter);
Response.Write("Report Datw:" + DateTime.Now);
Response.Write(osStringWritter.ToString());
//Response.End();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
dgv = null;
osStringWritter = null;
osHtmlTextWritter = null;
What i'm doing wrong ?
Try this may resolve your issue
dgv.DataSource = dt;
dgv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename = Export to Excel.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
dgv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
I have tried many things to just to export data only from the gridview. But it always export gridview formatting as well. Below is my code
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string fileName = "QAFormNotReceived" + DateTime.Now.ToString("yyyy-MM-dd") + ".xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
gvInsQANotReceived.HeaderStyle.Reset();
gvInsQANotReceived.FooterStyle.Reset();
gvInsQANotReceived.AlternatingRowStyle.Reset();
gvInsQANotReceived.RowStyle.Reset();
gvInsQANotReceived.BackColor = Color.Transparent;
gvInsQANotReceived.GridLines = GridLines.None;
gvInsQANotReceived.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
This the Excel spreadsheet
Spreadsheet I require
Any help is appreciated. I know next option is to try to use a string builder and write the rows one by one.
Thanks
I am exporting a GridView to an Excel file, but when I open
the file, first I get an error regarding the fact that
the format type and extension don't match, and when I open it
the whole page is brought into the Excel file, not just the grid view.
I'm not using an Update Panel. I tried with the button inside the GridView and outside
and the same result, so it seems it might be something from the code-behind which
looks like this:
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView3.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
You can try this method:
void ExportDataSetToExcel(GridView grdData, string filename)
{
grdData.BorderStyle = BorderStyle.Solid;
grdData.BorderWidth = 1;
grdData.BackColor = Color.WhiteSmoke;
grdData.GridLines = GridLines.Both;
grdData.Font.Name = "Verdana";
grdData.Font.Size = FontUnit.XXSmall;
grdData.HeaderStyle.BackColor = Color.DimGray;
grdData.HeaderStyle.ForeColor = Color.White;
grdData.RowStyle.HorizontalAlign = HorizontalAlign.Left;
grdData.RowStyle.VerticalAlign = VerticalAlign.Top;
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename+ "\"");
using (var sw = new StringWriter())
{
using (var htw = new HtmlTextWriter(sw))
{
grdData.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
USE this code: This will work fine..
aspx code::
<%# Page Language="C#" AutoEventWireup="true" CodeFile="default.aspx.cs" Debug ="true" enableEventValidation ="false" Inherits="default"%>
Here is the aspx code :
protected void ConvertToExcel_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Report.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
{
GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
int j = 1;
foreach (GridViewRow gvrow in GridView1.Rows)
{
if (j <= GridView1.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Solved !!!
your code is correct only problem with Response.Flush(); using in the code
instead of Response.Flush(); you should use Response.End();
Below is the working code:
Response.Clear();
Response.Buffer = true;
string filename = "GridViewExport_" + DateTime.Now.ToString() + ".xls";
Response.AddHeader("content-disposition",
"attachment;filename=" + filename);
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView3.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.End();
// Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
I want to export grid data from ASP.Net webpage to Excel without using any third party dll.
can anybody tell me how to do it ?
I suggested you if u use any Control in Template Field of GridView Like Bullted List, RadioButtonList , CheckBoxList and you want to export in Excel as it is then only use following code ...
public void ExportToExcel(GridView gv, string filename)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", filename + ".xls"));
HttpContext.Current.Response.ContentType = "application/ms-excel";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// Create a table to contain the grid
Table table = new Table();
// include the gridline settings
table.GridLines = gv.GridLines;
// add the header row to the table
if (gv.HeaderRow != null)
{
// PrepareControlForExport(gv.HeaderRow);
table.Rows.Add(gv.HeaderRow);
}
//Make Header Coloruful
for (int j = 0; j
Otherwise I would like to suggest DataTable which u bind Grid use that to export data in Excel.. And to do that use following Code.
public void ExportToExcel(DataTable dt, string fileName)
{
try
{
//**************************Excel Generation starts***************************
string attachment = "attachment; filename="+fileName+".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
string tab = "";
foreach (DataColumn dc in dt.Columns)
{
Response.Write(tab + dc.ColumnName);
tab = "\t";
}
Response.Write("\n");
int ik;
foreach (DataRow dr in dt.Rows)
{
tab = "";
for (ik = 0; ik
Hi PLease use below code to export to excel:
FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1; //This is the same dataTable by which you are binding your grid
DataGrd.DataBind();
DataGrd.RenderControl(htmlWrite);
string directory = Path.Substring(0, Path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.StreamWriter vw = new System.IO.StreamWriter(Path, true);
stringWriter.ToString().Normalize();
vw.Write(stringWriter.ToString());
vw.Flush();
vw.Close();
WriteAttachment(FI.Name, "application/vnd.ms-excel", stringWriter.ToString());
The above code uses a WriteAttachment function which pushes the attachment to the user in the Response object. The following code shows the implementation of WriteAttachment:
public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
For more detail please Click Here