Im having trouble executing codes after Response.End().
Im using this to export a datatable/ASP Table to MS Excel(.xls).
The export finishes but my Gridview is not loading anymore. The command that I use to load the gridview is written after Response.End().
I tried using HttpContext.Current.ApplicationInstance.CompleteRequest(); but it did not help.
I tried also Response.Redirect("Charges_Trs.aspx", false); still did not work..
Any help please..Here is my code
lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview
here is the function exporttoexcel()
public void exportToExcel(DataTable dt)
{
Table dTable = new Table();
TableRow dTableRow = new TableRow();
//Column Headings
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = dt.Columns[i].ToString();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
//Rows
for (int i = 0; i < dt.Rows.Count; i++)
{
dTableRow = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell tCell = new TableCell();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
}
if (Response.IsClientConnected)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
dTable.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
can u try adding the code in the btnSearch click event(hope it is to bind the grid with some data ) after calling export, instead of calling that click event.
Related
I followed this guide : Export Multi-Level Nested GridView to Excel using OpenXml in ASP.Net
And modified the code for my case as follows:
protected void ExportExcel(object sender, EventArgs e)
{
var dt = new DataTable("GridView_Data");
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
grvPayrollDetails.AllowPaging = false;
}
foreach (TableCell cell in grvPayrollDetails.HeaderRow.Cells)
{
if (cell.Text != " ")
{
dt.Columns.Add(cell.Text);
}
}
foreach (GridViewRow row in grvPayroll.Rows)
{
var grvPayrollDetailscell = (row.FindControl("grvPayrollDetails") as GridView);
for (var j = 0; j < grvPayrollDetailscell.Rows.Count; j++)
{
dt.Rows.Add(row.Cells[1].Text, row.Cells[2].Text, grvPayrollDetailscell.Rows[j].Cells[1].Text,
grvPayrollDetailscell.Rows[j].Cells[2].Text);
}
}
using (var wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=GridView.xlsx");
using (var MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
No error occurred, but the export file just contain the header , all cells are empty. The export excel file with exactly the header name and the number of rows. Why? Please help!
Here is the picture:
Exported File
Below is the code :
private void ExportarDataGridViewExcel(DataGridView grd)
{
SaveFileDialog fichero = new SaveFileDialog();
fichero.Filter = "Excel (*.xls)|*.xls";
if (fichero.ShowDialog() == DialogResult.OK)
{
Microsoft.Office.Interop.Excel.Application aplicacion;
Microsoft.Office.Interop.Excel.Workbook libros_trabajo;
Microsoft.Office.Interop.Excel.Worksheet hoja_trabajo;
aplicacion = new Microsoft.Office.Interop.Excel.Application();
libros_trabajo = aplicacion.Workbooks.Add();
hoja_trabajo = (Microsoft.Office.Interop.Excel.Worksheet)libros_trabajo.Worksheets.get_Item(1);
for (int i = 0; i < grd.Rows.Count - 1; i++)
{
for (int j = 0; j < grd.Columns.Count; j++)
{
hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();
}
}
libros_trabajo.SaveAs(fichero.FileName,
Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal);
libros_trabajo.Close(true);
aplicacion.Quit();
}
}
Its works fine, with few data's, but when I use it with a lot more, the program stop working and say this:
No se controló COMException
Excepción de HRESULT: 0x800AC472
In this part:
for (int j = 0; j < grd.Columns.Count; j++)
{
//PROBLEM// hoja_trabajo.Cells[i + 1, j + 1] = grd.Rows[i].Cells[j].Value.ToString();//PROBLEM
}
Please Help.
Create One Page Without Master Page Integration (In case if you are using Master Page in Asp.Net).
Then Bind all the Stuff on Page Load Event to grid Which ever Data You Required and Add This
public void CerateExcel()
{
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("content-disposition", "attachment;filename=Name.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
form1.RenderControl(hw); //form1 it's name of you .aspx page (a form name with runat='server' tag)
Response.Write(sw.ToString());
Response.Flush();
Response.End();
}
Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I am new to asp.net and need to create a project. My requirement is I have a table where I will store data. This is my main table. Under each id I have a separate table:
Msg_id Src Dest
701 RADAR MSC
702 MSC RADAR
Msg_id Message_size Mgs_desc
701 256 PFM_Load
Like that it continues... I have 3 dropdown lists. The 1st one is msg_id, the 2nd is src and the 3rd is dest. I also have a submit button the user can select any one of the dropdown lists and the corresponding table should be displayed in MS-Word.
You will need to create report of this data in .NET
Use EnableRenderExtension( "HTML4.0", "MS Word" ); for this purpose.
Then will have to export that report into word file.
Follow link:
http://www.codeproject.com/Articles/35225/Advanced-Report-Viewer
Or
Step by Step Approach:
http://www.accelebrate.com/sql_training/ssrs_2008_tutorial.htm
Hope Its helpful.
u can use this:
THis code for export into csv formate which can open in both msword&msexcel:
private void OutPutFileToCsv(DataTable dt, string fileName, string seperator)
{
StringWriter stringWriter = new StringWriter();
Int32 iColCount = dt.Columns.Count;
for (Int16 i = 0; i < iColCount; i++)
{
stringWriter.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
stringWriter.Write(dr[i].ToString().Trim());
}
if (i < iColCount - 1)
{
if (seperator.Contains(";"))
stringWriter.Write(";");
else
stringWriter.Write(",");
}
}
stringWriter.Write(stringWriter.NewLine);
}
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", fileName));
Response.ContentEncoding = Encoding.GetEncoding("iso-8859-1");
//Response.BinaryWrite(Encoding.Unicode.GetPreamble());
Response.Write(stringWriter.ToString());
Response.End();
}
just pass your datatable in function and get grid data in ms-word.
private void ExportToWord(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadReport.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/msword";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Hope it helps you.
TableRow tr = new TableRow();
TableCell yrs = new TableCell();
yrs.BorderWidth = 1;
yrs.BorderColor = System.Drawing.Color.Black;
yrs.Text = year.Substring(4);
tr.Cells.Add(yrs);
TableCell fname = new TableCell();
fname.BorderWidth = 1;
fname.BorderColor = System.Drawing.Color.Black;
fname.Text = test;
tr.Cells.Add(fname);
TableCell lname = new TableCell();
lname.BorderWidth = 1;
lname.BorderColor = System.Drawing.Color.Black;
lname.Text = test1.ToString();
tr.Cells.Add(lname);
TABULAR.Rows.Add(tr);
Response.Write(TABULAR);
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=test123.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter swWriter = new StringWriter();
HtmlTextWriter htwWriter = new HtmlTextWriter(swWriter);
TABULAR.RenderControl(htwWriter);
Response.Write(swWriter.ToString());
Response.End();
The problem here is you're dealing with a Table object which specifically:
Displays a table on a Web page.
and does not in any way represent an Excel 'table' or anything else.
Claiming it is an Excel file by modifying the response headers only tricks the browser, you do not have a valid Excel file