I'm trying to generate a report from a gridview which contains a complete csv listing as shown on the gridview. I'm able to generate the report however it is only generating first 10 on the list. HEres the code for my "Generate Report" button:
protected void BtnGenerateReports_Click(object sender, EventArgs e)
{
string filename = $"PatientList_{DateTime.Now:yyyyMMdd}.csv";
PopulatePatientList();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", $"attachment;filename={filename}");
Response.Charset = "";
Response.ContentType = "application/text";
GvPatientList.AllowPaging = true;
GvPatientList.DataBind();
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GvPatientList.Columns.Count; k++)
{
columnbind.Append(GvPatientList.Columns[k].HeaderText + ',');
}
columnbind.Append("\r\n");
for (int i = 0; i < GvPatientList.Rows.Count; i++)
{
for (int j = 0; j < GvPatientList.Rows.Count; j++)
{
columnbind.Append(GvPatientList.Rows[i].Cells[j].Text + ',');
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
Change this line of Code and try again
if you have paging in your gridview it will not export all the rows , it will export only the visible rows , so while exporting alone change the below line and export.
GvPatientList.AllowPaging = false;
Link : GridView is not being exported into Excel file
Related
I have a GridView with 75000 records. The data will increase in few days. I have no issues while populating in UI as I am using paging. Now, while exporting to excel all the blogs suggest to remove pagination and then load the grid again to export. But during that process the databind fails with out of memory exception. Please help. I even tried to load to datatable and reload to a new gridview.
(Added my code below, currently this is looping only the final page in the grid multiple times)
try
{
GrdReport.AllowPaging = false;
LoadReportData();
int a = GrdReport.PageIndex;
if (GrdReport.PageCount <= 650)
{
DataTable dt = new DataTable();
for (int i = 0; i < GrdReport.PageCount; i++)
{
GrdReport.PageIndex = i;
//GrdReport.SetPageIndex(a);
if (i == 0)
{
for (int k = 0; k < GrdReport.HeaderRow.Cells.Count; k++)
{
if (GrdReport.HeaderRow.Cells[k].HasControls())
{
if (GrdReport.HeaderRow.Cells[k].Controls[0] is LinkButton)
{
LinkButton headerControl = GrdReport.HeaderRow.Cells[k].Controls[0] as LinkButton;
string headerName = headerControl.Text;
dt.Columns.Add(headerName);
}
}
}
}
foreach (GridViewRow row in GrdReport.Rows)
{
dt.Rows.Add();
for (int j = 0; j < row.Cells.Count; j++)
{
dt.Rows[dt.Rows.Count - 1][j] = row.Cells[j].Text;
}
}
}
int x = dt.Rows.Count;
int y = dt.Columns.Count;
GrdReport.SetPageIndex(a);
Session["New"] = dt;
HttpResponse Response = HttpContext.Current.Response;
Response.Redirect("ExportToExcelHandler.ashx?gv=" + Session["New"], false);
}
else
{
lblErr.Text = "Result exceeds 65000 records. Please modify search criteria to reduce records.";
lblErr.Visible = true;
}
}
And this is the code in handler:
public class ExportToExcelHandler : System.Web.UI.Page, IHttpHandler, IRequiresSessionState
{
public new void ProcessRequest(HttpContext context)
{
GridView grid = new GridView();
this.EnableViewState = false;
grid.DataSource = (DataTable)HttpContext.Current.Session["New"];
grid.DataBind();
HttpResponse Response = HttpContext.Current.Response;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=Results.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter StringWriter = new StringWriter();
HtmlTextWriter HtmlTextWriter = new System.Web.UI.HtmlTextWriter(Response.Output);
grid.RenderControl(HtmlTextWriter);
Response.End();
}
public new bool IsReusable
{
get
{
return false;
}
}
}
An HTML file with XLS extension is not a real MS Excel file. MS Excel only knows how to read them and to display data.
Saving large HTML files leads to high memory allocation and it is time consuming.
You should use an Excel library like EasyXLS that saves xls or xlsx Excel files and has a better memory management.
Check the following links for directions:
Export Gridview to Excel in C#
and
Export large Excel files in C#
I have a datatable in a .Net web app that my customers have the option to export to CSV. A few customers have complained that the CSV is not able to re-import to our application. after further review, I noticed that on some large exports, the file has line breaks in it. is there a way i can prevent this?
here is my export method
DataTable dt = (DataTable)Session["Findings"];
string fileName = "test.csv";
string delimiter = ",";
//prepare the output stream
Response.Clear();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition",
string.Format("attachment; filename={0}", fileName));
//write the csv column headers
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write(dt.Columns[i].ColumnName);
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
//write the data
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
Response.Write("\"" + row[i].ToString() + "\"");
Response.Write((i < dt.Columns.Count - 1) ? delimiter : Environment.NewLine);
}
}
Response.End();
any help would be appreciated.
thanks
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();
}
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.
Hi all i am having a task to export gridview data to excel which i have done using the forums and articles available.
But i would like to display complete excel columns after the data was imported to excel, means expect the place occupied by the grid content i would like to display the remaining columns of the excel as it is.
Sample the normal way of exporting the we do in common is as follows
My requirement is to show as follows
I followed as per here
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
See your code to export you have removed the border of the excel generated in the code.
You can use the following code to do it
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
-->Return only hearder,not view data.Help Me !
Thank you !
Email:tsmcstcd#gmail.com