how to Design the exported excel in asp.net? - asp.net

I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this
All gridview data taken dataset ds
-pls give me textbox values and some label or normal text designed code in excel
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = string.Empty;
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].Cells[4].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:'\#,\#\#0\.00';}
.textmode1(mso-number-format:'\#';}
.SSNmode{mso-number-format:'000-00-000';} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();

Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/
Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx
Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)
CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
book.ExcelWorkbook.ProtectWindows = false;
book.ExcelWorkbook.ProtectStructure = false;
var styles = book.Styles;
WorksheetStyle defaultStyle = styles.Add("Default");
var defStyles = defaultStyle;
defStyles.Name = "Normal";
defStyles.Font.FontName = "Calibri";
defStyles.Font.Size = 11;
defStyles.Font.Color = "#000000";
defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;
Worksheet sheet = book.Worksheets.Add("Sheet1");
sheet.Table.DefaultRowHeight = 15f;
sheet.Table.FullColumns = 1;
sheet.Table.FullRows = 1;
DataTable dt = new DataTable(); //= your datatable
//Header
WorksheetRow HeaderRow = sheet.Table.Rows.Add();
foreach (DataColumn col in dt.Columns)
{
HeaderRow.Cells.Add(col.ColumnName.ToString());
}
//Body
foreach (DataRow dr in dt.Rows)
{
WorksheetRow row = sheet.Table.Rows.Add();
foreach (DataColumn cols in dt.Columns)
{
row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
}
}
sheet.Options.Selected = true;
sheet.Options.ProtectObjects = false;
sheet.Options.ProtectScenarios = false;
book.Save("path to file");

Related

Export excel from data table using Open sdk xml

I am exporting data in to excel using open xml sdk. Now i want that data directly export using data table not by using grid view when i give data table directly into wb.Worksheets.Add(dt) it give worksheets name exception,secondly i want to save file into some location rather than downloading my code is below.
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
}
}
using (XLWorkbook 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 (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}

Export Data table With Arabic Data to Excel

I am Having a Data Table which consists of arabic data.
When I am Exporting it to excel I am unable to get the Arabic data correctly.
Currently my code is as below,
public void ExportExcel(DataTable table, string filename)
{
if (table != null && filename != "")
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;attachment;filename=" + filename + ".xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
GridView GrdExcel = new GridView();
GrdExcel.AllowPaging = false;
GrdExcel.DataSource = table;
GrdExcel.DataBind();
for (int i = 0; i < GrdExcel.Rows.Count; i++)
{
GridViewRow row = GrdExcel.Rows[i];
row.Attributes.Add("class", "text");
}
GrdExcel.RenderControl(htmlWrite);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Output.Write(stringWrite.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
}
EDIT 1:
Below is the final code which has worked for me
////If you want the option to open the Excel file without saving than
////comment out the line below
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;attachment;filename=" + filename + ".xls");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite =
new HtmlTextWriter(stringWrite);
DataGrid grdExcel = new DataGrid();
grdExcel.AllowPaging = false;
grdExcel.DataSource = table;
grdExcel.DataBind();
foreach (DataGridItem i in grdExcel.Items)
{
foreach (TableCell tc in i.Cells)
tc.Attributes.Add("class", "text");
}
grdExcel.RenderControl(htmlWrite);
string style = #"<style> .text { mso-number-format:\#; } </style> ";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
This was written by referring few articles from the web .Hope it helps
add this code to your code:
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Every string wrap in Encoding.UTF8.GetString (for ex: Encoding.UTF8.GetString(str))
and in web.config:
<system.web>
<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="he-IL"/>
</system.web>
he-IL is in my case, write your language culture respectively

Passing a grid to a function used to export to excel

I have a method that is used to export the data to excel.Till now I have been passing table to the method.But now I wish to pass the grid data so that I do not have to call the procedures for different instances for getting different filtered data sets.
is there a way to do so?
public void ExportToExcel(DataSet ds)
{
if (ds.Tables[0].Rows.Count > 0)
{
string filename = ds.Tables[1].Rows[0]["filename"].ToString() + ".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 = ds.Tables[0];
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
//Response.ContentType = application/vnd.ms-excel;
Response.Clear();
Response.ClearHeaders();
Response.Charset = "";
Response.AddHeader("content-disposition", String.Concat("attachment;filename=", filename));
Response.AddHeader("Cache-Control", "max-age=0");
Response.ContentType = "application/vnd.xls";
// this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
This is the method that I am using to export to excel.

How to remove paging text in excel sheet while exporting data from GridView to Excelsheet?

I implemented export to excel functionality in asp.net application.Here i export data from Grid-view to excel-sheet.I also applied Paging in Grid-view.
So when i export data from Grid-view to excel sheet,paging text also display in excel sheet as shown in the given image.
How can we remove it
i follow the below approach for exporting data
Code-Behind:
Response.Clear()
Response.ClearHeaders()
Response.AddHeader("content-disposition", "attachment;filename=sample.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"
Dim sb As StringBuilder = New StringBuilder()
Dim objStringWriter As StringWriter = New StringWriter(sb)
Dim objHtmlTextWriter As HtmlTextWriter = New HtmlTextWriter(objStringWriter)
//gvSample is Gridview server control
gvSample.RenderControl(objHtmlTextWriter)
Response.ContentEncoding = Encoding.Unicode
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble())
Response.Write(objStringWriter)
Response.End()
Thanks
Before rendering - disable the paging, bind the data and then render:
gvSample.AllowPaging = false;
gvSample.DataSource = ds; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter)
when ever to get the data from database for show the gridview,before that but the result content in viewstate[""] after the reuse it. when search the data for filter the main content the updated data will present in the viewstate, so you will get correct data to export
gvSample.AllowPaging = false;
gvSample.DataSource = ViewState["vsData"]; //Data Source
gvSample.DataBind();
gvSample.RenderControl(objHtmlTextWriter);
It works using SQL DataSourceID
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
cell.BackColor = GridView1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in GridView1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = GridView1.RowStyle.BackColor;
}
cell.CssClass = "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();
other attached asp coding file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["ondblclick"] = Page.ClientScript.GetPostBackClientHyperlink(GridView1, "Edit$" + e.Row.RowIndex);
e.Row.Attributes["style"] = "cursor:pointer";
}
}

gridview to excel

work on asp.net vs05.when i export gridview to excel than i get the below error
RegisterForEventValidation can only be called during Render();
why i get this error .How to solve it?
public void ToExcel()
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
//-- added to handle special characters in excel
Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());
gvSearch.EnableViewState = false;
//-- added to handle special characters in excel
Add these lines and see if it helps.
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
It's a shot in the dark.
in aspx page, Change the following to false : AllowPaging="False" AllowSorting="False" and remove Pagesize="10".
This Code Help to solve export Gridview to excel related problem
Microsoft.Office.Interop.Excel._Application app = new
Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook =
app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Excel Sheet Name"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < Gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = Gridview.Columns[i - 1].HeaderText;
}
for (int i = 0; i < Gridview.Rows.Count; i++)
{
for (int j = 0; j < Gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] =
Gridview.Rows[i].Cells[j].Value.ToString();
}
}

Resources