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
Related
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
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 am using the below code to download the excel file:
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MBQ.xls"));
Response.ContentType = "application/ms-excel";
DataTable dt = BindDatatable();
string str = string.Empty;
foreach (DataColumn dtcol in dt.Columns)
{
Response.Write(str + dtcol.ColumnName);
str = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
}
Response.End();
In my case, the table has more than 800k records. I am applying more filters before downloading the excel sheet. What is the best way to download a excel sheet from the datatable which has hundreds of thousands of rows?
Firstly since that isn't an excel spreadsheet but a tab-separated-values file (which can be opened in excel and does what you want), then don't lie in the header as that can only bring confusion:
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "MBQ.csv"));
Response.ContentType = "text/tab-separated-values";
(Strictly ".csv" is an extension normally defined as being for comma-separated-values rather than tab, but it's more commonly set up to open in Excel, LibreOffice Calc, or whatever spreadsheet program people have installed, and they'll generally consider CSV and TSV as variants of each other).
Secondly, don't buffer. You have Response.Buffer = true; set to explicitly make sure you keep masses of data in memory before sending it, you want to do the opposite, so Response.Buffer = false; is the way to go.
You might find it better still to explicitly call Response.Flush() every couple of hundred or thousand rows:
int rowCount = 0;
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
if (unchecked(++rowCount % 1024 == 0))
Response.Flush();
}
Experiment with higher or lower values than 1024. Higher sends larger chunks which is inefficient in needing more memory to hold it, but efficient in the actual sending of the chunk is snappier, so the optimal value will be a matter of finding the best balance between those two factors.
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
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.