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/
Related
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>
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.
In application i have grid view and Ajax Toolkit control linechart i need to export grid view and linechart to excel sheet(open office/Libra office). i tried some code in export button but what happens grid view is exported but line chart is not export to excel. my page appear like this [my chart image]
by clicking the export button then only grid view will export to excel but not linechart it will not export.what i need is chart should be export to excel. how to do this
i tried code is:
.aspx:
<cc1:LineChart ID="LineChart1" runat="server" ChartHeight="300" ChartWidth="900" ChartType="Basic" ChartTitleColor="#0E426C" Visible="true" CategoryAxisLineColor="#D08AD9" ValueAxisLineColor="#D08AD9" BaseLineColor="#A156AB"></cc1:LineChart>
.cs:
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "filename.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.OnPreRender(e);
ScriptManager sm = ScriptManager.GetCurrent(Page);
sm.RegisterScriptControl(LineChart1);
LineChart1.Visible = true;
for (int i = 0; i < grdview1.HeaderRow.Cells.Count; i++)
{
grdview1.HeaderRow.Cells[i];
}
grdview1.RenderControl(htw);
LineChart1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
I added OnPreRender() for Registering the scriptmanager control
protected override void OnPreRender(EventArgs e)
{
/* Verifies that the control is rendered */
base.OnPreRender(e);
ScriptManager scriptManager = ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager = new ScriptManager();
scriptManager.ID = "ScriptManager1";
scriptManager.EnablePartialRendering = true;
Controls.AddAt(0, scriptManager);
}
}
Can anyone help me out how can i export linechart.
Thank you
No, you can not export LineChart.
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();
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