Format column for exporting DataSet / Gridview to Excel - asp.net

I'm exporting data from a DataSet to Excel via GridView. Framework is 2.0. I'm using the following code snippet:
Generate_Sequence_Data_BAL objAttBAL = new Generate_Sequence_Data_BAL();
string PlanId = "";
PlanId = Cryptography.Decrypt(Request.QueryString[0].ToString());
//Get the data from database into datatable
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SequenceData_" + Cryptography.Decrypt(Request.QueryString[0].ToString()) + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
DataSet ds = objAttBAL.GetData(Convert.ToInt32(PlanId));
GridView GridView1 = new GridView();
GridView1.RowDataBound += GridView1_RowDataBound;
GridView1.DataSource = ds.Tables[0];
GridView1.DataBind();
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.Write(sw.ToString());
Response.Flush();
GridView1.Dispose();
Response.End();
I have a column with data like '5E02'. Even after using the above method, it's being exported as '5.00E+02'.
I have tried concatenating (') to it while retrieving from SQL, but then it shows up like ('5E02) instead of (5E02).
Please help. Also suggest any other alternatives for exporting data directly to excel without gridview.
PS: I have already referred this question & it's not working, so it's not a duplicate.

I solved the problem by concatenating Alt+0160 (Non-breaking Space) at the end of the column.
Select <Column Name>+'<Alt+0160>'
Now the column is being exported as '5E02 ' instead of '5.00E+02'.

Related

asp.net export to excel

Hello i got 2 pages with exporting to excel , i use something like this :
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "poView.xls"))
Response.ContentEncoding = Encoding.UTF8
Response.ContentType = "application/ms-excel"
Dim tw As New IO.StringWriter()
Dim htw As New HtmlTextWriter(tw)
budgetPlanGrid.RenderControl(htw)
Response.Write(tw.ToString())
Response.[End]()
Now i do manage to export into excel and see the needed grid, but on the more complex page which has alot more stuff in it for some reason beside the gridview i see parts from my masterpage! and it yells at me that i am missing the path for my style.css which has nothing to do with the gridview i am trying to export!.
I used 2 panels to make everything up untill / from the gridview visible = false,
I am kinda clueless what else could have caused that.
I am hoping maybe someone had this sort of issue while using this code and can advice me on what to look for?
Thanks in advanced!
I had that issue using RenderControl - kept asking for missing style sheets and other nonsense.
I used the datatable I would have used to bind the gridview and did this:
HttpContext.Current.Response.Clear();
HttpContacts.Current.Response.AddHeader("content-disposition", attachment):
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
string sTab = "";
foreach (DataColumn dc in dt.Columns)
{
HttpContext.Current.Response.Write(sTab + dc.ColumnName);
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in dt.Rows)
{
sTab = "";
for (i = 0; i < dt.Columns.Count; i++)
{
HttpContext.Current.Response.Write(sTab + dr[i].ToString());
sTab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();

Change name of sheet in export to excel

I have export to excel code which gets data from database then create dynamic gridview and then export that data to excel.
Problem is that i it is taking sheet name same as i mentioned filename. So how do i change sheet name
Here is code i am using
GridView gridView = new GridView();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "SummaryReport " + Helper.GetTime(DateTime.UtcNow).ToString() + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
gridView.DataSource = ReportExecutor.ReportExportData(startDate, endDate);
gridView.DataBind();
//This will change the header background color
gridView.HeaderRow.Style.Add("background-color", "#FFFFFF"); //
//This will apply style to gridview header cells
for (int index = 0; index < gridView.HeaderRow.Cells.Count; index++)
{
gridView.HeaderRow.Cells[index].Style.Add("background-color", "#778899"); //Light Slate Gray
gridView.HeaderRow.Cells[index].Style.Add("foreground-color", "#ffffff"); // White
}
int index2 = 1;
//This will apply style to alternate rows
foreach (GridViewRow gridViewRow in gridView.Rows)
{
gridViewRow.BackColor = Color.White;
if (index2 <= gridView.Rows.Count)
{
if (index2 % 2 != 0)
{
for (int index3 = 0; index3 < gridViewRow.Cells.Count; index3++)
{
gridViewRow.Cells[index3].Style.Add("background-color", "#e6e6fa");// Lavender
}
}
}
index2++;
}
gridView.RenderControl(htmlTextWriter);
//// Response.Write(style);
Response.Write(stringWriter.ToString());
Response.End();
It's not possible to do with StringWriter. You may have to re-open and then rename the sheet once it's successfully written using the StringWriter.
Otherwise, you have to use an alternate method to create the Excel. Here's an example
Export GridView to multiple Excel sheet
I'm afraid you can't change the sheet name of an excel file generated from setting Response content type as excel. Refer accepted answer of SO question and from ASP.NET forum
You could also take a look at EPPlus, which has an option to edit sheetnames in code.

How do I export only a datatable to Excel using only standard .Net and not a 3rd party dll?

I know this has been answered on here and a thousand other sites on the web, but every single one I've tried does not work as I want it to. I want to export ONLY a datatable, not the page I'm running the code from, and I want to do this without having to download a 3rd party dll. Every piece of code I've tried ends up exporting the page I'm running it from. Here's the current iteration I'm using...
Private Sub ExporttoExcel(table As DataTable)
Dim attachment As String = "attachment; filename=file.xls"
Response.ClearContent()
Response.AddHeader("content-disposition", attachment)
Response.ContentType = "application/vnd.ms-excel"
Dim tab As String = ""
For Each dc As DataColumn In table.Columns
Response.Write(tab + dc.ColumnName)
tab = vbTab
Next
Response.Write(vbLf)
Dim i As Integer
For Each dr As DataRow In table.Rows
tab = ""
For i = 0 To table.Columns.Count - 1
Response.Write(tab & dr(i).ToString())
tab = vbTab
Next
Response.Write(vbLf)
Next
Response.End()
End Sub
Can anyone explain why this doesn't work or how I can export ONLY the datatable into Excel?
I usually do this and it has worked for me (ds is a DataSet which has the data I want to push to excel):
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
string filename = "TEMP/ex1.xls";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
this should work with EPPlus
Public Shared Function ExportToExcel(FileName As String, SheetName As String, data As DataTable) As Boolean
Dim pck As ExcelPackage
pck = New ExcelPackage()
Try
Dim ws = pck.Workbook.Worksheets.Add(SheetName)
ws.Cells("A1").LoadFromDataTable(data, True)
Dim excel = pck.GetAsByteArray()
HttpContext.Current.Response.ClearHeaders()
HttpContext.Current.Response.ClearContent()
HttpContext.Current.Response.Clear() 'really clear it :-p
HttpContext.Current.Response.BufferOutput = False
HttpContext.Current.Response.ContentType = "application/octet-stream"
HttpContext.Current.Response.AddHeader("cache-control", "max-age=0")
HttpContext.Current.Response.AddHeader("Pragma", "public")
HttpContext.Current.Response.AddHeader("Content-Length", excel.Length.ToString())
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=""" & FileName & ".xlsx""")
HttpContext.Current.Response.BinaryWrite(excel)
HttpContext.Current.Response.[End]()
Return True
Catch
Return False
Finally
pck.Dispose()
End Try
End Function
The only way to do this without some kind of 3rd party dll is to write a csv file.
Columns separated by semicolon, rows separated by /n

'System.OutOfMemoryException' was thrown when Exporting Data in Excel from .NET code

I have a code to debug where I am attempting to export data in Excel. It works fine for smaller data but when data size increases to several thousands, I get 'Out of Memory exception'. My application is running on IIS 6.0. Any recommendations?
PS: The process usually fails when it takes more than 1.2 GB of memory (looking at the Task Manager)
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
If (IsExportToCSV) Then
Response.Clear()
Response.ContentType = "application/vnd.ms-excel"
Response.ContentType = "a"
'Remove the charset from the Content-Type header.
Response.Charset = ""
'Turn off the view state.
Page.EnableViewState = False
Dim tw As System.IO.StringWriter
tw = New System.IO.StringWriter
Dim hw As HtmlTextWriter = New HtmlTextWriter(tw)
'Get the HTML for the control.
Me.GridView1.AllowPaging = False
Me.GridView1.DataBind()
Me.GridView1.EnableViewState = False
Me.GridView1.AutoGenerateEditButton = False
Me.GridView1.RenderControl(hw)
Response.Write(tw.ToString)
Response.Flush()
Response.End()
Else
MyBase.Render(writer)
End If
End Sub
Perfect Solution!
I've been fighting this one for a while and the solution is so simple: Don't build a string to pass to response write as the string exist in memory, instead put each line directly into the response using multiple Response.Write calls
example for DataTable converted to HTML table and being sent to client as excel...
string contentType = "Reports.xls";
string fileName = "application/msexcel";
Response.Clear();
Response.Buffer = true;
Response.ContentType = contentType;
string attachment = string.Format("attachment; filename=\"{0}\"", fileName);
Response.AddHeader("Content-Disposition: ", attachment);
byte[] preamble = Encoding.UTF8.GetPreamble();
Response.BinaryWrite(preamble);
string strFontSize = "12";
Response.Write("<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" \r\n xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \r\n xmlns=\"http://www.w3.org/TR/REC-html40\">");
Response.Write(#"<head>");
Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=windows-1252\">");
Response.Write("<meta name=ProgId content=Excel.Sheet>");
Response.Write("<meta name=Generator content=\"Microsoft Excel 11\">");
Response.Write(#"</head>");
Response.Write(#"<body>");
Response.Write(#"<table style='width: 100%; font-size:" + strFontSize + ";' border='1'>");
foreach (DataColumn column in dt.Columns)
{
Response.Write(#"<td><b>" + column.ColumnName + "</b></td>");
}
Response.Write(#"</tr>");
int intCell = 0;
string strCell = "";
foreach (DataRow row in dt.Rows)
{
intCell = 0;
Response.Write(#"<tr>");
foreach (DataColumn column in dt.Columns)
{
strCell = row.ItemArray[dt.Columns[column.ColumnName].Ordinal].ToString().Trim();
Response.Write(#"<td>" + strCell + "</td>");
}
Response.Write(#"</tr>");
}
Response.Write(#"</table>");
Response.Write(#"</body>");
Response.Write(#"</html>");
Response.End();
write each line directly info the response stream instead of passing trough the StringWriter

Exporting grid to excel

I used this code for exploring grid to excel.I got this code from net.
protected void Button1_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;
GridView1.DataBind();
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
When I am using this code,grid data get display in excel,but that does not have vertical and horizontal lines.It shows gridview column name as link not normal text.I have not used any theme to gridview and columns are autogenerated.One column say col3 contain more description so it's data get displayed at top when second row start,still it's discription shown in cell2.So I wanted to add vertical and horizontal lines,in that.So it is easy to come to know which data of belong to which id.I want to format col 1 also which is of number format only and decimal places zero.
1 col1 col2 col3
hjhhjhjhjhjhjhjhjhjhjbbv
gfgfgfuiuiuiuiui
2 9.12E+11 gkjj etwtrtrwqtrtttwwtretqwfe
dear member
gffgf
3 565E+11 hghgh
Bind grid data on page load event and then try to export again.. follow this link's code.. may be it will be good rather than others...
Exporting GridView Data to Excel
Code Snippet:
private void ExportGridView()
{
string attachment = "attachment; filename=Contacts.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Note: There are some comments also posted which also have some information..
To Format GridView according to grid controls when you are exporting data to excel then follow the below link:
ASP.Net 2.0: Export GridView to Excel

Resources