Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
||
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[3.145.93.210] |
|
Сообщ.
#1
,
|
|
|
Назначаю рендер таблице(одному контролу), а мне рендерится вся страница. По нажатию на кнопку скачивается файл эксель а в нем вся страница.
Мягко говоря, я не очень понял почему так. взято отсюда http://asp.net-informations.com/excel/asp-excel-export.htm protected void Button1_Click(object sender, EventArgs e) { try { Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=gridviewdata.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter sWriter = new StringWriter(); HtmlTextWriter hWriter = new HtmlTextWriter(sWriter);//hWriter булет писать в sWriter, вроде как. GridView1.RenderControl(hWriter);//отрендерилось в hWriter, вроде как. Response.Output.Write(sWriter.ToString()); Response.Flush(); Response.End(); } catch (Exception ex) { Label1.Text = ex.ToString(); } } |
Сообщ.
#2
,
|
|
|
а что в sWriter.ToString() ?
|
Сообщ.
#3
,
|
|
|
Попробый добавить строку this.EnableViewState = false;
|
Сообщ.
#4
,
|
|
|
Цитата UncleBob @ а что в sWriter.ToString() ? А что должно быть? Я думал, что отрендерилось GridView1 в hWriter ( GridView1.RenderControl(hWriter) ) hWriter записал в sWriter, вроде как потом это все в респонс.... |
Сообщ.
#5
,
|
|
|
Цитата ttiger @ А что должно быть? так для того дебаггер дан нам свыше |
Сообщ.
#6
,
|
|
|
Цитата UncleBob @ так для того дебаггер дан нам свыше Извини, не очень понял. Ты, наверное, понял, что там не так. Можешь прокоментировать решение? |
Сообщ.
#7
,
|
|
|
Цитата ttiger @ Извини, не очень понял. Ставишь точку останова, и смотришь дебаггером значение |
Сообщ.
#8
,
|
|
|
Цитата UncleBob @ а что в sWriter.ToString() ? Интересно.. Можно и без этой строчки. после того, как выполнилось GridView1.RenderControl(hWriter);//отрендерилось в hWriter, вроде как. Цитата MIF @ Попробый добавить строку this.EnableViewState = false; Не помогло. У самого грида EnableViewState давно в false стоял. Что-то я тут не понимаю ( |
Сообщ.
#9
,
|
|
|
***
Приведенный а первом посте код работать не будет. Потому, что вызывается эксепшн. Потому. что в методе Render стоит провенрка на то, что метод вызван из глобального метода Render. Еще хочу заметить, что сайт не майкрософтовский. Упражнение на внимательность. Работает вот это: http://www.sql.ru/forum/571282/eksport-gridview-v-excell Копирую код тут, вдруг понадобится. public class GridViewExportUtil { /// <summary> /// /// </summary> /// <param name="fileName"></param> /// <param name="gv"></param> public static void ToExcel(string fileName, GridView gv) { HttpContext.Current.Response.Clear(); HttpContext.Current.Response.AddHeader( "content-disposition", string.Format("attachment; filename={0}", fileName)); HttpContext.Current.Response.ContentType = "application/ms-excel"; using (StringWriter sw = new StringWriter()) { using (HtmlTextWriter htw = new HtmlTextWriter(sw)) { GridViewWrapper(gv).RenderControl(htw); // render the htmlwriter into the response HttpContext.Current.Response.Write(sw.ToString()); HttpContext.Current.Response.End(); } } } private static Table GridViewWrapper(GridView gv) { // Create a table to contain the grid Table table = new Table(); // include the gridline settings table.GridLines = gv.GridLines; // add the header row to the table if (gv.HeaderRow != null) { GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); table.Rows.Add(gv.HeaderRow); } // add each of the data rows to the table foreach (GridViewRow row in gv.Rows) { GridViewExportUtil.PrepareControlForExport(row); table.Rows.Add(row); } // add the footer row to the table if (gv.FooterRow != null) { GridViewExportUtil.PrepareControlForExport(gv.FooterRow); table.Rows.Add(gv.FooterRow); } return table; } /// <summary> /// Replace any of the contained controls with literals /// </summary> /// <param name="control"></param> private static void PrepareControlForExport(Control control) { for (int i = 0; i < control.Controls.Count; i++) { Control current = control.Controls[i]; if (current is LinkButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); } else if (current is ImageButton) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); } else if (current is HyperLink) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); } else if (current is DropDownList) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); } else if (current is CheckBox) { control.Controls.Remove(current); control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); } if (current.HasControls()) { GridViewExportUtil.PrepareControlForExport(current); } else if (current is TableCell) { TableCell item = (current as TableCell); item.Text = item.Text.Replace(" ", "").Replace("<nobr>", "").Replace("</nobr>", ""); } } } } В "реальной жизни" это все вряд ли пригодится, т.к. есть на свете нормальные отчетники. Но, думаю, такой функционал в приложении тоже имеет право на жизнь, в одном десктопном приложении он у меня использовался с успехом, экономил клики. Добавлено Вопрос решен. Спасибо всем тем, кто помогал в личке. |