Exporting the contents of a gridview to Excel 2007+ - c#

Hi , I'm having a little trouble with exporting my gridview to Excel using the code below. It appears to work OK, apart from when i come to open the file it tells me that its not in the specified format for the extension, however if ignore it it opens anyway. I'm newish to coding and am not sure of the best approach to get it in to an xl format properly (the above happens on the live or MO server).
Also on my local VS2012 when i run in debug mode (local host) and click the button, i seem to get the program throw and exception
sender {Text = Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} object {System.Web.UI.WebControls.Button}
#region Event to Export the table to MS Excel when the export button is clicked
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
try
{
DataTable dt1 = (DataTable)ViewState["dtList"];
if (dt1 == null)
{
throw new Exception("No Records to Export");
}
string Path = "c:\\OrderTrackerExportsFromTP\\CircuitsOrderTrackFor_" + DateTime.Now.ToString("yyyyMMdd Hmmss") + ".xls";
FileInfo FI = new FileInfo(Path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid DataGrd = new DataGrid();
DataGrd.DataSource = dt1;
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());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//Push the attachment to the user with the response object from the button click event
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();
}
#endregion

Related

The excel report Settings pop-up doesn't show on getting an excel report

I use Stimulsoft 2017. Once I click on the excel report's option nothing appears, which was supposed to show export settings as it is shown below.And it just download the excel report all of a sudden.
I use this code to generate excel,but these settings don't make any effect on exported excel files.
void StiReportViewer_ReportExport(object sender, StiExportDataEventArgs e)
{
try
{
if (e.Settings.GetExportFormat() == StiExportFormat.Excel || e.Settings.GetExportFormat() == StiExportFormat.Excel2007)
{
// this.StiReportViewer.ExportResponse = false;
Stimulsoft.Report.Export.StiExcelExportSettings stiExcelExportSettings = new Stimulsoft.Report.Export.StiExcelExportSettings();
stiExcelExportSettings.ExportDataOnly = true;
stiExcelExportSettings.UseOnePageHeaderAndFooter = true;
stiExcelExportSettings.ExportPageBreaks = false;
stiExcelExportSettings.ExportObjectFormatting = false;
MemoryStream xlsMemoryStream = new MemoryStream();
e.Report.ExportDocument(StiExportFormat.Excel, xlsMemoryStream, stiExcelExportSettings);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/ms-excel";
Response.BinaryWrite(xlsMemoryStream.ToArray());
Response.End();
}
}
catch (Exception ex)
{
}
Finally,I figure out that it runs with js, and there is a line of code that should change this way.
<Sti:StiWebViewer ID="StiReportViewer" runat="server" Width="100%" RenderMode="AjaxWithCache"
ButtonsImagesPath="Images" ToolBarBackColor="WhiteSmoke" OnGetReportData="StiReportViewer_GetReportData" ButtonImagesPath="Images/ReportViewer/" ShowExportDialog="false">
</Sti:StiWebViewer>
should change this way as show below:
<Sti:StiWebViewer ID="StiReportViewer" runat="server" Width="100%" RenderMode="AjaxWithCache"
ButtonsImagesPath="Images" ToolBarBackColor="WhiteSmoke" OnGetReportData="StiReportViewer_GetReportData" ButtonImagesPath="Images/ReportViewer/" ShowExportDialog="true">
</Sti:StiWebViewer>

how to export excel without EnableEventValidation="false" because of lock issues in excel

I have a code for exporting excel on button click:
protected void btn_Excel_Click(object sender, EventArgs e)
{
try {
empData1.ShowHeader = true;
bindGrid();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=doc_name.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
foreach (TableCell cell in empData1.HeaderRow.Cells)
{
cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#fafafa");
cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#ff5d51");
}
empData1.RenderControl(hw);
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
catch(Exception exp)
{
string st = exp.Message;
}
}
I was getting error:
RegisterForEventValidation can only be called during Render();
and what i did is:
enableEventValidation="false" on the page_name.aspx page
The export to excel worked fine after this on windows 7.
The issue came on windows 8, when i downloaded the excel on a windows 8 system's browser, though the file did downloaded completely, but on opening the file, it showed up with a error message that the file is corrupted, and i suppose it is because of disabling event validation.
when i checked the properties of that file, then it was locked up due to security reasons. I unlocked it from there, and i could open up the file then.
so is there any way to tackle the error
RegisterForEventValidation can only be called during Render();
without enableEventValidation="false" or tell me if i am missing something.

ASP.NET Gridview to Export to Excel

I am using Visual Studio 2015, Entity Framework 6 and C#.
I am trying to get my gridview to export to excel. I think I have everything, but when clicking the button my gridview disappears and nothing ever goes to a file.
My gridview is:
gvExOr
The Excel Export code is:
public partial class _Default : Page
{
private void BindFiles()
{
DirectoryInfo di = new DirectoryInfo(tbPath.Text);
gvExOr.DataSource = di.GetFiles();
try {
gvExOr.DataBind();
}
catch { }
}
protected void btnExportToExcel_Click(object sender, EventArgs e)
{
ExportToExcel();
}
//Export to Excel from a GridView
protected void ExportToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application / vnd.ms - excel";
Response.AddHeader("content - disposition", "attachment; filename = MyFiles.xls");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
gvExOr.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
protected void Page_Load(object sender, EventArgs e)
{
BindFiles();
}
}
How do I get the gridview to export to excel?
Looks like you used code from this post https://stackoverflow.com/a/10412559/5786449
I tried the example from that post and it works for me. The only difference I can see is in your Response.ContentType and Response.AddHeader. Try getting rid of the white spaces in those parameters:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
One more thing, your code doesn't actually give you an Excel spreadsheet. It just writes out the GridView HTML markup. Many Excel programs are not expecting HTML in an XLS file and will throw an error when opening the file. If you want an actual Excel spreadsheet I would recommend looking into utilities like EPPlus http://epplus.codeplex.com/

Saving an asp.net chart to file

I have a bar chart containing information on various machines relating to company.
Basically i want to output this chart to png file but i cant seem to get it output properly.
Ive been searching Google for hours trying to find a good tutorial but most of them use weird third party components to download the image and i really dont wanna do that.
this is my code at the moment:
string tmpChartName = "/MachinesByCompanyChart.png";
protected void GenerateBarChartBut_click(object sender, EventArgs e)
{
Chart1.Visible = false;
Chart2.Visible = true;
DataTable table = new DataTable();
dal.getTotalAssetsByCompany("table", TAB1CompanyDDL.SelectedItem.Text);
table = dal.Results.Tables["table"];
DataView dv = table.DefaultView;
Chart2.Series["Series1"].Points.DataBindXY(dv, "AssetType", dv, "Total");
Chart2.Palette = ChartColorPalette.None;
Chart2.PaletteCustomColors = myGreenColorPalette;
string imgPath2 = Server.MapPath(tmpChartName);
Chart2.SaveImage(imgPath2, ChartImageFormat.Png);
}
protected void ExportAssetsByCompanyBut_click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = Chart1.ImageType.ToString();
Response.AddHeader("Content-Disposition", "attachment; filename=" + tmpChartName);
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
}
Am i passing the saved image to the writer method properly?
try this,
set this two properties of your chart in aspx.page
EnableViewState="true"
ImageStorageMode="UseImageLocation"
write your code on aspx.cs page
System.IO.MemoryStream imagestream = new System.IO.MemoryStream();
Chart1.SaveImage(imagestream, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Png);
byte[] imageByte = imagestream.ToArray();

nested gridview export to excel, asp.net c#

I want to export the parent grid view and nested gridview to an excel.
I have a code that only work to export a normal simple gridview.
Tried to debug the code, found there is no error or whatsoever.
It is just after i click the export button, it doesnt export to excel.
here is my code
protected void asd()
{
string title = "";
string attempt = "SELECT * FROM Poll Where PollID = '" + Session["abc"] + "'";
cmd = new SqlCommand(attempt, con);
dr = cmd.ExecuteReader();
while (dr.Read())
{
title = dr["PollTitle"].ToString();
}
string filename = String.Format(title + " RESULTS. " + "{0}_{1}.xls",
DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
ClearControls(GridView3);
// Throws exception: Control 'ComputerGrid' of type 'GridView'
// must be placed inside a form tag with runat=server.
// ComputerGrid.RenderControl(htmlWrite);
// Alternate to ComputerGrid.RenderControl above
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView3);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
protected void Export_buttonClick(object sender, EventArgs e)
{
asd();
}
this code is working for a normal gridview, but not the one with nested gridview.
I've experienced the 'must be placed inside a form tag with runat=server' error in the past and resolved the issue by adding the following override method in my page codebehind:
public override void VerifyRenderingInServerForm(Control control) {}
More info on MSDN.
For reference, I also used this code for exporting my GridViews:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=your_file.xls");
Response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
your_GridView.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

Categories