I have a GridView and a few columns are literal:
<asp:TemplateField HeaderText="Next Service Date">
<ItemTemplate>
<asp:Literal ID="litNextSvcDate" runat="server">/asp:Literal>
</ItemTemplate>
I want to convert this GridView to an Excel spreadsheet and all the boundfield columns display on the spreadsheet but not the literals. Here is the code to convert the Grid to Excel:
protected void ToExcel(GridView grid, string Name, string FileName)
{
if (!FileName.Contains(".xls"))
{
FileName = FileName + ".xls";
}
string style = "<style><!--table#page{mso-header-data:\"&C" + Name + " Date/: &D/ Page &P\"; mso-page-orientation:landscape; mso-page-scale:89;} br {mso-data-placement:same-cell;} --></style>";
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
this.EnableViewState = false;
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write(style);
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\">");
Response.Write("<!--[if gte mso 9]>");
Response.Write("<xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>" + Name + " Table</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Panes>");
Response.Write("</x:Panes>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("<x:Scale>89</x:Scale>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]-->");
Response.Write("</head>");
Response.Write("<body>");
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
List<int> HiddenCols = new List<int>();
for(int i = 0; i < grid.Columns.Count; i++)
{
if (!grid.Columns[i].Visible)
{
HiddenCols.Add(i);
}
}
for (int i = 0; i < grid.HeaderRow.Cells.Count; i++)
{
if(HiddenCols.Contains(i))
grid.HeaderRow.Cells[i].Visible = false;
}
ClearControls(grid);
grid.RenderBeginTag(oHtmlTextWriter);
grid.HeaderRow.RenderControl(oHtmlTextWriter);
foreach (GridViewRow row in grid.Rows)
{
for (int i = 0; i < row.Cells.Count; i++)
{
if (HiddenCols.Contains(i))
row.Cells[i].Visible = false;
}
row.RenderControl(oHtmlTextWriter);
}
grid.FooterRow.RenderControl(oHtmlTextWriter);
grid.RenderEndTag(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.Write("</body>");
Response.Write("</html>");
Response.End();
}
Related
I read a few posts around here but couldn't find the answer so far.
I'm using the following code to export my GridView into Excel file:
protected void btnExportClick(object sender, EventArgs e)
{
StringBuilder builder = new StringBuilder();
string strFileName = "Report_" + DateTime.Now.ToShortDateString() + ".csv";
builder.Append("Firld1,Filed2,Field3,Field4,Field5" + Environment.NewLine);
foreach (GridViewRow row in gvMOSS2Merchants.Rows)
{
string f1= row.Cells[0].Text;
string f2= row.Cells[1].Text;
string f3= row.Cells[2].Text;
string f4= row.Cells[3].Text;
string f5= row.Cells[4].Text;
builder.Append(f1+ "," + f2+ "," + f3+ "," + f4+ "," + f5+ Environment.NewLine);
}
Response.Clear();
Response.ContentType = "text/cvs";
Response.AddHeader("Content-Disposition", "attachment;filename=" + strFileName);
Response.Write(builder.ToString());
Response.End();
}
When clicking on the button, the file is being created, but it has only headers and no data inside.
What can be wrong with that logic?
The following code works for me
this was called in button onclick event
OnClick="ExportExcel"
EXCEL EXPORT CODE
protected void ExportExcel(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=YourFileName" + DateTime.Now.ToString() + ".csv");
Response.Charset = "UTF8";
Response.ContentType = "application/text";
gridviewID.AllowPaging = false;
loadgrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Columns[k].HeaderText.ToString() + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int k = 0; k < gridviewID.Columns.Count; k++)
{
//add separator
sb.Append(gridviewID.Rows[i].Cells[k].Text.Replace(",", " & ").Replace("\n", " ").Replace("\r", " ").ToString() + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
I'm working on a C# asp.net project and can't seem to get the "exporting to a .txt file from a grid view" to work.
protected void ExportGridToText() {
BindGridView();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
StringBuilder Rowbind = new StringBuilder();
Response.ContentType = "application/text";
Response.AddHeader("Content-Disposition", "attachment;filename=GlogData.txt");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Cache.SetCacheability(HttpCacheability.NoCache);
gvLog.DataBind();
for (int i = 2; i < gvLog.Columns.Count; i++)
{
Rowbind.Append("\"" + gvLog.Columns[i].HeaderText + "\"" + ',');
}
Rowbind.Append("\n");
for (int j = 0; j < gvLog.Rows.Count; j++)
{
for (int k = 0; k < gvLog.Columns.Count; k++)
{
Rowbind.Append("\"" + gvLog.Rows[j].Cells[k].Text + "\"" + ',');
Rowbind.Replace("<", "<");
Rowbind.Replace(">", ">");
}
Rowbind.Append("\n");
}
gvLog.AllowPaging = false;
Response.Output.Write(Rowbind.ToString());
Response.Flush();
Response.End();
}
Evrytime I run the code I get a error message:
Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed
Why is it giving me this error?
How do I fix it?
Is it possible to get the data from the source... This is under the get Button that populates the GridView:
protected void GetLogBtn_Click(object sender, EventArgs e)
{
string sBeginDate = BeginDate.Text;
string sEndDate = EndDate.Text;
JObject vResultJson = new JObject();
FKWebCmdTrans cmdTrans = new FKWebCmdTrans();
DateTime dtBegin, dtEnd;
if (sBeginDate.Length > 0)
{
try
{
dtBegin = Convert.ToDateTime(sBeginDate);
sBeginDate = FKWebTools.GetFKTimeString14(dtBegin);
vResultJson.Add("begin_time", sBeginDate);
}
catch
{
BeginDate.Text = "";
}
}
if (sEndDate.Length > 0)
{
try
{
dtEnd = Convert.ToDateTime(sEndDate);
sEndDate = FKWebTools.GetFKTimeString14(dtEnd);
vResultJson.Add("end_time", sEndDate);
}
catch
{
EndDate.Text = "";
}
}
try
{
string sFinal = vResultJson.ToString(Formatting.None);
byte[] strParam = new byte[0];
cmdTrans.CreateBSCommBufferFromString(sFinal, out strParam);
mTransIdTxt.Text = FKWebTools.MakeCmd(msqlConn, "GET_LOG_DATA", mDevId, strParam);
Session["operation"] = GET_LOG_DATA;
GetLogBtn.Enabled = false;
ClearBtn.Enabled = false;
Timer.Enabled = true;
}
catch (Exception ex)
{
StatusTxt.Text = "Fail! Get Log Data! " + ex.ToString();
}
}
This is under the BindGridView:
private void BindGridView()
{
try
{
string mTransid = mTransIdTxt.Text;
string strSelectCmd = "SELECT COUNT(*) FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlCommand sqlCmd = new SqlCommand(strSelectCmd, msqlConn);
SqlDataReader sqlReader = sqlCmd.ExecuteReader();
if (sqlReader.HasRows)
{
if (sqlReader.Read())
nCount = sqlReader.GetInt32(0);
}
sqlReader.Close();
sqlCmd.Dispose();
{
DataSet dsLog = new DataSet();
strSelectCmd = "SELECT * FROM tbl_fkcmd_trans_cmd_result_log_data where trans_id = '" + mTransid + "'";
SqlDataAdapter da = new SqlDataAdapter(strSelectCmd, msqlConn);
// conn.Open();
da.Fill(dsLog, "tbl_fkcmd_trans_cmd_result_log_data");
DataView dvLog = dsLog.Tables["tbl_fkcmd_trans_cmd_result_log_data"].DefaultView;
gvLog.DataSource = dvLog;
gvLog.DataBind();
StatusTxt.Text = " Total Count : " + Convert.ToString(nCount) + " Current Time :" + DateTime.Now.ToString("HH:mm:ss tt");
}
}
catch (Exception ex)
{
StatusTxt.Text = ex.ToString();
}
}
I hope this helps
Thanks in advance
Following Code is For Excel Mainly...but its successfully converting gridview to .txt file just need a little workaround..
public void ExportToExcel(System.Web.UI.WebControls.GridView controlname, string sheetname)
{
HttpContext context = HttpContext.Current;
context.Response.ClearContent();
context.Response.Buffer = true;
context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".txt"));
context.Response.ContentType = "application/text";
// context.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", sheetname + ".xls"));
// context.Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
//Change the Header Row back to white color
controlname.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < controlname.HeaderRow.Cells.Count; i++)
{
controlname.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in controlname.Rows)
{
gvrow.BackColor = Color.White;
if (j <= controlname.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
controlname.RenderControl(htw);
context.Response.Write(sw.ToString());
context.Response.End();
}
Here is the table structure:
enter image description here
Here is the code:
protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader)
{
StringBuilder builder = new StringBuilder();
List<string> columnNames = new List<string>();
List<string> rows = new List<string>();
for (int i = 0; i < oDataReader.FieldCount; i++)
{
string tmpColumnName = oDataReader.GetName(i);
columnNames.Add(tmpColumnName);
}
builder.Append(string.Join(",", columnNames.ToArray())).Append("\n");
List<string> currentRow = new List<string>();
while (oDataReader.Read())
{
////base.WriteLog(oDataReader.FieldCount + "fieldcount");
for (int i = 0; i < oDataReader.FieldCount; i++)
{
object item = oDataReader[i];
currentRow.Add(item.ToString());
}
}
//builder.Append(string.Join("\n", rows.ToArray())).Append("\n");
rows.Add(string.Join(",", currentRow.ToArray()));
builder.Append(string.Join(",", rows.ToArray())).Append("\n");
Response.Clear();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=pretestscore.csv");
Response.Write(builder.ToString());
Response.End();
}
The problem is that while output is begin returned, the
while (oDataReader.Read())
function the value are being returned just like
281063,70,7091,85,TEST,200,test,NULL
How to get actually data from the table?
Where is the mistake in my code?
Any suggestions?
protected void Write_CSV_From_Recordset2(SqlDataReader oDataReader)
{
string strCSV = string.Empty;
for (int i = 0; i < oDataReader.FieldCount; i++)
{
string tmpColumnName = oDataReader.GetName(i);
strCSV += tmpColumnName + ',';
}
strCSV += "\r\n";
while (oDataReader.Read())
{
for (int i = 0; i < oDataReader.FieldCount; i++)
{
object item = oDataReader[i];
strCSV += item.ToString().Replace(",", ";") + ',';
}
strCSV += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=pretestscore.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(strCSV);
Response.Flush();
Response.End();
}
You can directly write code with comma separated with for loop or while loop.
You can refer this code and you will get idea
string s;
while (reader.Read())
{
if(!String.IsNullOrEmpty(s)){
s += ", ";
}
s += reader["name"].ToString();
}
I use this code to export datagridview to excel
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
string fileName = "TRAIL" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
form.Controls.Add(AuditTrailGV);
this.Controls.Add(form);
form.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
the problem is this code also catches the formatting/borders of my gridview
here are the sample screen shots
This is my gridview in asp.net
and this is what appears in my excell
as you can see it transformed all of the lines like the gridview, i do not want it to happen, as much as possible if i can only retain the gridlines for the rows with data only, if its not possible, remove all the gridlines..
any help? i really do not like those gridlines in my excell
VB
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
'base.VerifyRenderingInServerForm(control);
'This remains empty
End Sub
Protected Sub btnExcel_Click(sender As Object, e As ImageClickEventArgs) Handles btnExcel.Click
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = "application/vnd.ms-excel"
Dim stringWrite As New System.IO.StringWriter()
Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
htmlWrite.Write("<html xmlns:o=""urn:schemas-microsoft-com:office:office"" ")
htmlWrite.Write("xmlns:x=""urn:schemas-microsoft-com:office:excel"" ")
htmlWrite.Write("xmlns=""http://www.w3.org/TR/REC-html40""> ")
htmlWrite.Write("<head> ")
htmlWrite.Write("<!--[if gte mso 9]><xml> ")
htmlWrite.Write("<x:ExcelWorkbook> ")
htmlWrite.Write("<x:ExcelWorksheets> ")
htmlWrite.Write("<x:ExcelWorksheet> ")
htmlWrite.Write("<x:Name>Sheet1</x:Name> ")
htmlWrite.Write("<x:WorksheetOptions> ")
htmlWrite.Write("<x:Selected/> ")
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ")
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ")
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ")
htmlWrite.Write("</x:WorksheetOptions> ")
htmlWrite.Write("</x:ExcelWorksheet> ")
htmlWrite.Write("</x:ExcelWorksheets> ")
htmlWrite.Write("</x:ExcelWorkbook> ")
htmlWrite.Write("</xml><![endif]--> ")
htmlWrite.Write("</head>")
htmlWrite.WriteLine("")
gridView.HeaderStyle.Reset()
gridView.FooterStyle.Reset()
gridView.AlternatingRowStyle.Reset()
gridView.RowStyle.Reset()
gridView.BackColor = Color.Transparent
gridView.GridLines = GridLines.None
gridView.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.[End]()
End Sub
C#
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
//This remains empty
}
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
htmlWrite.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" ");
htmlWrite.Write("xmlns:x=\"urn:schemas-microsoft-com:office:excel\" ");
htmlWrite.Write("xmlns=\"http://www.w3.org/TR/REC-html40\"> ");
htmlWrite.Write("<head> ");
htmlWrite.Write("<!--[if gte mso 9]><xml> ");
htmlWrite.Write("<x:ExcelWorkbook> ");
htmlWrite.Write("<x:ExcelWorksheets> ");
htmlWrite.Write("<x:ExcelWorksheet> ");
htmlWrite.Write("<x:Name>Sheet1</x:Name> ");
htmlWrite.Write("<x:WorksheetOptions> ");
htmlWrite.Write("<x:Selected/> ");
htmlWrite.Write("<x:ProtectContents>False</x:ProtectContents> ");
htmlWrite.Write("<x:ProtectObjects>False</x:ProtectObjects> ");
htmlWrite.Write("<x:ProtectScenarios>False</x:ProtectScenarios> ");
htmlWrite.Write("</x:WorksheetOptions> ");
htmlWrite.Write("</x:ExcelWorksheet> ");
htmlWrite.Write("</x:ExcelWorksheets> ");
htmlWrite.Write("</x:ExcelWorkbook> ");
htmlWrite.Write("</xml><![endif]--> ");
htmlWrite.Write("</head>");
htmlWrite.WriteLine("");
gridView.HeaderStyle.Reset();
gridView.FooterStyle.Reset();
gridView.AlternatingRowStyle.Reset();
gridView.RowStyle.Reset();
gridView.BackColor = Color.Transparent;
gridView.GridLines = GridLines.None;
gridView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
You can try below code and custom the color of the downloaded data. It will also not color the Column and rows other then the data.
protected void DownloadExcel_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)
{
//gvrow.BackColor = color.White;
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();
}
I Have A gridView with data contain Arabic letters On My website When I Export To Csv File
on localhost It works Fine when i purplish on server the Arabic letters appear like ????????
where the problem
this is my code
protected void btn_SaveCSV_Click(object sender, EventArgs e)
{
// Response.Clear();
HttpContext.Current.Response.Clear();
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
//Response.ContentType = "application/text";
Response.ContentType = "text/csv; charset-UTF-8";
Response.ContentEncoding = System.Text.Encoding.Default;
Grid_offlineMessages.AllowPaging = false;
FillGrid();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < Grid_offlineMessages.Rows.Count; i++)
{
for (int k = 0; k < Grid_offlineMessages.Columns.Count; k++)
{
//add separator
sb.Append(Grid_offlineMessages.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
Try setting the encoding to UTF-8 like this:
Response.ContentEncoding = System.Text.Encoding.UTF8;