On my aspx page, I have a Usercontrol which contains a Gridview, whose data is loaded dynamically based on params passed from the aspx page to the UserControl, which I called QuotesReport1.
When the export runs, it only exports the layout into the Spreadsheet, and none of the gridview's data, for example:
<style>
body
{
margin: 0px;
}
</style>
<div>
</div>
My code for the export is:
protected void Page_Load(object sender, EventArgs e)
{
string toDate = "";
string fromDate = "";
toDate = Request.QueryString.Get("toDate");
fromDate = Request.QueryString.Get("fromDate");
QuotesReport1.ToDate = DateTime.Parse(toDate);
QuotesReport1.FromDate = DateTime.Parse(fromDate);
QuotesReport1.Status = QuotesReport.quoteStatus.PENDING_REVIEW;
string attachment = "attachment; filename=Quotes_Pending.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
QuotesReport1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control) { }
Inside the UserControl, a SQL query runs, which returns a DataTable, which is then bound to the Gridview inside the UserControl, something along the lines of:
SQLData da = new SQLData();
GridView1.DataSource = da.SGetDataTable(query);
GridView1.DataBind();
The simplest of the ways i have
public class ExcelUtility
{
public static void ToExcel(object dataSource)
{
GridView grid = new GridView { DataSource = dataSource };
grid.DataBind();
StringBuilder sb = new StringBuilder();
foreach (TableCell cell in grid.HeaderRow.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
foreach (GridViewRow row in grid.Rows)
{
foreach (TableCell cell in row.Cells)
sb.Append(string.Format("\"{0}\",", cell.Text.Trim().Replace(" ", string.Empty)));
sb.Remove(sb.Length - 1, 1);
sb.AppendLine();
}
ExportToExcel(sb.ToString());
}
private static void ExportToExcel(string data)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=Report.csv");
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
HttpContext.Current.Response.ContentType = "text/csv";
HttpContext.Current.Response.Write(data);
HttpContext.Current.Response.End();
}
}
using:
string result = ExcelUtility.ToExcel(_db.FindAll());
ExcelUtility.ExportToExcel(result);
Related
i am come up with scenario that while exporting grid view to excel its not refreshing my grid data source. Below is my code what i have done before. Below code is updating flag in database and then trying to refresh the grid data source in Fill Grid method.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
}
ExportToExcel(Convert.ToInt64(e.CommandArgument));
}
}
Below is the Export to excel method.
public void ExportToExcel(Int64 OGPCode)
{
DataTable dtPickList =GeneralQuery.GetDocumentPickList(OGPCode);
if (dtPickList != null && dtPickList.Rows.Count>0)
{
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dtPickList;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Inbox.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
GridView1.DataSource = null;
Response.Write(Request.RawUrl.ToString());
}
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Please help me what i am doing wrong. Thanks
Finally i found the way to refresh the grid view while exporting the grid view to excel. I just create new web form and put ExportGridToExcel() method in Page_Load and on button click it refresh the grid view data source and open new tab to download excel file. Below is my code.
protected void Process_Command(object sender, CommandEventArgs e)
{
if (Session["Status"] != "Refreshed")
{
if (!string.IsNullOrEmpty(Convert.ToString(e.CommandArgument)))
{
using (var transaction = context.Database.BeginTransaction())
{
DocumentOGP objDocumentOGP = context.DocumentOGPs.Find(Convert.ToInt64(e.CommandArgument));
objDocumentOGP.UpdationDate = DateTime.Now;
objDocumentOGP.DispatchStatusID = 2;
context.DocumentOGPs.Add(objDocumentOGP);
context.Entry(objDocumentOGP).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
transaction.Commit();
FillGrid();
Session["OGPCode"] = Convert.ToString(e.CommandArgument);
}
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "OpenWindow", "window.open('http://localhost:56430/DownLoadExcel','_newtab');", true);
}
}
}
Below is my Download excel file web-form and its implementation
public partial class DownLoadExcel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (!string.IsNullOrEmpty(Convert.ToString(Session["OGPCode"])))
{
ExportToExcel(Convert.ToInt64(Session["OGPCode"]));
Session["OGPCode"] = null;
}
}
}
public void ExportToExcel(Int64 OGPCode)
{
DataTable dt = GeneralQuery.GetDocumentPickList(OGPCode);
//create a new byte array
byte[] bin;
string FileName = "Pick-List-" + DateTime.Now.ToString();
//create a new excel document
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create a new worksheet
ExcelWorksheet ws = excelPackage.Workbook.Worksheets.Add(FileName);
//add the contents of the datatable to the excel file
ws.Cells["A1"].LoadFromDataTable(dt, true);
//auto fix the columns
ws.Cells[ws.Dimension.Address].AutoFitColumns();
//loop all the columns
for (int col = 1; col <= ws.Dimension.End.Column; col++)
{
//make all columns just a bit wider, it would sometimes not fit
ws.Column(col).Width = ws.Column(col).Width + 1;
var cell = ws.Cells[1, col];
//make the text bold
cell.Style.Font.Bold = true;
//make the background of the cell gray
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(ColorTranslator.FromHtml("#BFBFBF"));
//make the header text upper case
cell.Value = ((string)cell.Value).ToUpper();
}
//convert the excel package to a byte array
bin = excelPackage.GetAsByteArray();
}
//clear the buffer stream
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
//set the correct contenttype
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//set the correct length of the data being send
Response.AddHeader("content-length", bin.Length.ToString());
//set the filename for the excel package
Response.AddHeader("content-disposition", "attachment; filename=\"" + FileName + ".xlsx\"");
//send the byte array to the browser
Response.OutputStream.Write(bin, 0, bin.Length);
//cleanup
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
When you update GridView or any control values dynamically you should render and export it to other application.
Sample: check with RenderControl method of GridView.
private void ExportGridToExcel()
{
Response.Clear();
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.Charset = "";
string FileName = "xyz.xls";
StringWriter strwritter = new StringWriter();
HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
GridView1.RenderControl(htmltextwrtter);
Response.Write(strwritter.ToString());
Response.End();
}
I'm using this code to export my gridview data. I have a dropdown in my page and when I select dropdown values the data changes in gridview and I need to export only that present data into excel.
protected void ExporttoExcel(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
I am using paging and when I export initially without having selected dropdown values I need to export all the data, but now only the datas in the first page alone gets exported.
Can anyone correct me where I'm wrong?
I have a custom made method for exporting excels in a formatted style from a Datatable-Gridvieww. You can use it, by assigning to the table variable your Datatable in which you bind the Gridview( the whole datatable before the paging)
private void ExportToExcel(DataTable table, GridView gv)
{
Response.ClearContent();
Response.Charset = your charset//"Windows-1253";
Response.ContentEncoding = your encoding//Encoding.UTF8;
string attachment = "attachment; filename=test.xls";
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
HttpContext.Current.Response.Write(#"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
HttpContext.Current.Response.Write("<font style='font-size:10.0pt; font-family:Calibri;'>");
HttpContext.Current.Response.Write("<BR><BR><BR>");
HttpContext.Current.Response.Write("<Table border='1' bgColor='#ffffff' " +
"borderColor='#000000' cellSpacing='0' cellPadding='0' " +
"style='font-size:10.0pt; font-family:Calibri; background:white;'> <TR>");
int columnscount = table.Columns.Count;
for (int j = 0; j < columnscount; j++)
{
HttpContext.Current.Response.Write("<Td style='background-color: #C0C0C0;' align=" + "center" + ">");
HttpContext.Current.Response.Write("<B>");
HttpContext.Current.Response.Write(table.Columns[j].ToString());
HttpContext.Current.Response.Write("</B>");
HttpContext.Current.Response.Write("</Td>");
}
HttpContext.Current.Response.Write("</TR>");
foreach (DataRow row in table.Rows)
{
HttpContext.Current.Response.Write("<TR>");
for (int i = 0; i < table.Columns.Count; i++)
{
HttpContext.Current.Response.Write("<Td align=" + "center" + ">"); ;
HttpContext.Current.Response.Write(row[i].ToString());
HttpContext.Current.Response.Write("</Td>");
}
HttpContext.Current.Response.Write("</TR>");
}
HttpContext.Current.Response.Write("</Table>");
HttpContext.Current.Response.Write("</font>");
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
You can save the SQL query result in a DataTable and save that DataTable in a ViewState or session. Then when clicking the export button, retrieve the DataTable from the ViewState and create a dummy GridView that will have the DataTable as its source.
Something like this:
protected void ExporttoExcel(object sender, EventArgs e)
{
//First, retrieve the DataTable from ViewState
DataTable Dt = new DataTable();
Dt = (DataTable)ViewState["DtData"];
//Now you have the data, create a dummy GridView that will be used for exporting
GridView grdView = new GridView();
grdView.AllowPaging = false;
grdView.DataSource = Dt;
grdView.DataBind();
//Do the Exporting stuff
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
grdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
This way, each time you change the dropdownlist value, save the selected SQL query result in a datatable and then in the ViewState and export.
Of course, if you can update your question with the dropdownlist code or how are you setting the GridView datasource, I'd update this answer.
Hope this helps.
Disable the GridView paging then render. You may need to do the binding as well.
protected void ExporttoExcel(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
// ************************
GridView1.AllowPaging = false; // <- disable paging then render
// also do the binding
GridView1.DataSource = myDataSource;
GridView1.DataBind();
// ************************
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Edit (working example)
ASPX (GridView and an export Button):
<asp:GridView ID="grd1" runat="server" AllowPaging="true" PageSize="10" AutoGenerateColumns="false" OnPageIndexChanging="grd1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="StudentID" HeaderText="Student ID" />
<asp:BoundField DataField="StudentName" HeaderText="Student Name" />
<asp:BoundField DataField="FatherName" HeaderText="Father Name" />
</Columns>
</asp:GridView>
<asp:Button ID="btnExport" runat="server" Text="Export" OnClick="btnExport_Click" />
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGridView();
}
}
private void BindGridView()
{
using (var dtStudent = this.GetStudentData())
{
this.grd1.DataSource = dtStudent;
this.grd1.DataBind();
}
}
private DataTable GetStudentData()
{
var dtStudent = new DataTable();
dtStudent.Columns.Add("StudentID");
dtStudent.Columns.Add("StudentName");
dtStudent.Columns.Add("FatherName");
for (int i = 0; i < 20; i++)
{
var sIndex = i.ToString("00");
dtStudent.Rows.Add("Student-" + sIndex, "Name-" + sIndex, "Father-" + sIndex);
}
return dtStudent;
}
protected void grd1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
this.grd1.PageIndex = e.NewPageIndex;
this.BindGridView();
}
protected void ExporttoExcel()
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Report.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
// ************************
this.grd1.AllowPaging = false; // <- disable paging then render
this.BindGridView();
// ************************
this.grd1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
//base.VerifyRenderingInServerForm(control);
}
protected override void Render(HtmlTextWriter writer)
{
if (this._Export)
this.ExporttoExcel();
else
base.Render(writer);
}
private bool _Export = false;
protected void btnExport_Click(object sender, EventArgs e)
{
this._Export = true;
}
data transfer grid view to excel in asp dot net code is run but blank sheet generate of excel but data is not loaded in excel sheeet how to solve this type of broblem
protected void btnexcel_Click1(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
Check for data in the gridview, your data is not getting binded. So the excel is empty. Debug and check for data inside the gridview. It should work.
Try with this one
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=ActualsAndBudgets.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
may be problem in data binding in export excel .
check that data properly bin to a gridview or not.
Use this code for export grid view in excel sheet and note that you must add iTextSharp dll in you project.
protected void btnExportExcel_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
// Re-Bind data to GridView
using (CompMSEntities1 CompObj = new CompMSEntities1())
{
Start = Convert.ToDateTime(txtStart.Text);
End = Convert.ToDateTime(txtEnd.Text);
GridViewSummaryReportCategory.DataSource = CompObj.SP_Category_Summary(Start, End);
SP_Category_Summary_Result obj1 = new SP_Category_Summary_Result();
GridView1.DataBind();
GridView1.Visible = true;
ExportTable.Visible = true;
}
//Change the Header Row back to white color
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
GridView1.Style.Add(" font-size", "10px");
//Apply style to Individual Cells
GridView1.HeaderRow.Cells[0].Style.Add("background-color", "green");
GGridView1.HeaderRow.Cells[1].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[2].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[3].Style.Add("background-color", "green");
GridView1.HeaderRow.Cells[4].Style.Add("background-color", "green");
for (int i = 1; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
// row.Attributes.Add("class", "textmode");
//Apply style to Individual Cells of Alternating Row
if (i % 2 != 0)
{
row.Cells[0].Style.Add("background-color", "#C2D69B");
row.Cells[1].Style.Add("background-color", "#C2D69B");
row.Cells[2].Style.Add("background-color", "#C2D69B");
row.Cells[3].Style.Add("background-color", "#C2D69B");
row.Cells[4].Style.Add("background-color", "#C2D69B");
}
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
I need to download selected rows of an asp.net gridview to an excel sheet.
What I am doing is trying the check all at once or just a few selected and then after pressing the download button below, all the selected rows get downloaded as excel. Every thing works fine here when I press download button, but rather all the rows get downloaded ignoring the selection.
Following is my code
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// I Tried using following (but with no success)
//-----Trial Starts----------------
//foreach (GridViewRow gvr in gvProgramList.Rows)
// {
// CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
// if(cbox.Checked)
// gvr.Visible = true;
// else
// gvr.Visible = false;
// }
//--------Trial ends---------------
grdGridView.DataBind();
ClearControls(grdGridView);
// 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(grdGridView);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
foreach (GridViewRow gvr in gvProgramList.Rows)
{
CheckBox cbox = (CheckBox)gvr.FindControl("cboxSelect");
gvr.Visible = true;
}
grdGridView.DataBind();
}
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 btnDownload_Click(object sender, EventArgs e)
{
if (gvProgramList.Rows.Count > 0)
{
ExportGridToExcel(gvProgramList, "ProgramList");
}
}
I can suggest you a logic to do this:
1.Create a dynamic datatable with selected rows of your gridview.
its just looping through gridview rows and fetching and appending selected rows to new datatable.
2.Then write code for converting this new datatable to excel sheets(lots of results for google "Convert datatable to excel")
Try like the below code,hope it helps you..
On the download button click event,call this fn
private void ExportToExcell()
{
DataTable dt = new DataTable();
dt.Columns.Add("Plan ID");
dt.Columns.Add("Plan Name");
dt.Columns.Add("Balance");
foreach (GridViewRow row in gdvBal.Rows)
{
CheckBox chkCalls = (CheckBox)row.FindControl("chkCalls");
if (chkCalls.Checked == true)
{
int i = row.RowIndex;
Label lblPlanId = (Label)gdvBal.Rows[i].FindControl("lblPlanId");
Label lblPlanName = (Label)gdvBal.Rows[i].FindControl("lblPlanName");
Label lblBalance = (Label)gdvBal.Rows[i].FindControl("lblBalance");
DataRow dr = dt.NewRow();
dr["Plan ID"] = Convert.ToString(lblPlanId.Text);
dr["Plan Name"] = Convert.ToString(lblPlanName.Text);
dr["Balance"] = Convert.ToString(lblBalance.Text);
dt.Rows.Add(dr);
}
}
GridView gdvExportxls = new GridView();
gdvExportxls.DataSource = dt;
gdvExportxls.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", string.Format("attachment;filename=BillingForfBalances.xls", "selectedrows"));
Response.Charset = "";
StringWriter stringwriter = new StringWriter();
HtmlTextWriter htmlwriter = new HtmlTextWriter(stringwriter);
gdvExportxls.RenderControl(htmlwriter);
Response.Write(stringwriter.ToString().Replace("<div>", " ").Replace("</div>", " "));
Response.End();
}
I have a listview on my asp page and I need to export it to excel in code behind(c#). However I donĀ“t want all the columns to be exported.
Is it possible to copy the ListView into a new ListView object with fewer columns?
Or is there another way to export the listview with fewer columns into excel?
This is how I am exporting the code to excel in code behind:
protected void ExportToExcel(object sender, EventArgs e)
{
string attachment = "attachment; filename=MyData.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
// How can I render myListView with fewer columns?
myListView.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
Thanks in advance,
class ListViewToCSV
{
public static void ListViewToCSV(ListView listView, string filePath, bool includeHidden)
{
//make header srting
StringBuilder result = new StringBuilder();
WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listView.Columns[i].Text);
//export data rows
foreach (var listItem in listView.Items)
WriteCSVRow(result, listView.Columns.Count, i => includeHidden || listView.Columns[i].Width > 0, i => listItem.SubItems[i].Text);
File.WriteAllText(filePath, result.ToString());
}
private void WriteCSVRow(StringBuilder result, int itemsCount, Func<int, bool> isColumnNeeded, Func<int, string> columnValue)
{
bool isFirstTime = true;
for (int i = 0; i < itemsCount; i++)
{
if (!isColumnNeeded(i))
continue;
if (!isFirstTime)
result.Append(",");
isFirstTime = false;
result.Append(String.Format("\"{0}\"", columnValue(i)));
}
result.AppendLine();
}
}