Change name of sheet in export to excel - asp.net

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.

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();

Format column for exporting DataSet / Gridview to Excel

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'.

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

create excel in ASP.NET

I'm working on an ASP.NET web projec using VS2010,C#, I want my users to get excel file output from table reports, I know how to create CSV files but I'm going to create EXCEL files, for example a button that when clicked, enables user to download table data in EXCEL format, also I'm going to write some unicode text (persian, farsi language) into my excel, what are my options? currently I use following code to generate CSV file:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + "db" + ".csv");
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder sb = new StringBuilder();
sb.Clear();
//append new line
sb.Append("\r\n");
for (int i = 0; i < tblDatabase.Rows.Count; i++)
{
//add separator
for (int j = 0; j < tblDatabase.Rows[0].Cells.Count; j++)
sb.Append(Table3.Rows[i].Cells[j].Text + ",");
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
There is no big change when modifying this code to create Excel file instead of csv.
Just change your extension
Response.AddHeader("content-disposition", "attachment;filename=" + "db" + ".xls");
Change content type
Response.ContentType = "application/vnd.ms-excel";
Here is how to write rows of data in Excel sheet.
Response.Write("<table border='1px' bordercolor='black'>");
Response.Write("<tr>");
// loop through column names to display a header row
foreach (DataColumn dc in tblDatabase.Columns)
{
Response.Write("<td><strong>" + dc.ColumnName + "</strong></td>");
}
Response.Write("</tr>");
int i;
foreach (DataRow dr in tblDatabase.Rows)
{
Response.Write("<tr>");
for (i = 0; i < tblDatabase.Columns.Count; i++)
{
Response.Write("<td>" + dr[i].ToString() + "</td>");
}
Response.Write("</tr>");
}
// end table
Response.Write("</table>");
I have had good results using NPOI, learning curve not too steep
http://npoi.codeplex.com/
Creates native excel files, rather than forcing excel to parse html tables.
The html tables option is ok for some jobs (quicker and easier), but if you have a requirement to make the "real" thing, then try out NPOI.

Send query results to Excel from ASP.NET website

We let users create ad-hoc queries in our website. We would like to have the user select their criteria, then click submit and have the results streamed automatically to Excel. I have the application populating a DataTable, then using the datatable to create a tab delimited string. The problem is getting that to excel.
What is the best way to stream data to Excel? Preferrably, we wouldn't have to make users close an empty window after clicking the submit button.
Change the page's file type to excel, and only stream the HTML necessary to build a table to the page. code from here
//for demo purpose, lets create a small datatable & populate it with dummy data
System.Data.DataTable workTable = new System.Data.DataTable();
//The tablename specified here will be set as the worksheet name of the generated Excel file.
workTable.TableName = "Customers";
workTable.Columns.Add("Id");
workTable.Columns.Add("Name");
System.Data.DataRow workRow;
for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}
//...and lets put DataTable2ExcelString to work
string strBody = DataTable2ExcelString(workTable);
Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");
Response.Write(strBody);
If you create a page that is just a table with the results and set the page's content type to "application/vnd.ms-excel", then the output will be in Excel.
Response.ContentType = "application/vnd.ms-excel";
If you want to force a save, you would do something like the following:
Response.AddHeader("Content-Disposition", "attachment; filename=somefilename.xls");
I got a utils function that does this already. Once you put it into a datatable, you can export it with the Response using
public static void DataTabletoXLS(DataTable DT, string fileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset = "utf-16";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1250");
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.xls", fileName));
HttpContext.Current.Response.ContentType = "application/ms-excel";
string tab = "";
foreach (DataColumn dc in DT.Columns)
{
HttpContext.Current.Response.Write(tab + dc.ColumnName.Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
int i;
foreach (DataRow dr in DT.Rows)
{
tab = "";
for (i = 0; i < DT.Columns.Count; i++)
{
HttpContext.Current.Response.Write(tab + dr[i].ToString().Replace("\n", "").Replace("\t", ""));
tab = "\t";
}
HttpContext.Current.Response.Write("\n");
}
HttpContext.Current.Response.End();
}
I'd recommend using a filehandler (.ashx) The only issue is creating the excel file from the DataTable. There are a lot of third party products that will do this for you (e.g. Infragistics provides a component that does just this).
One thing I highly recommend against is using the Excel interop on your server...it's very heavyweight and isn't supported.
Once you have your Dataset you can convert it to an object[,] and insert it into an Excel document. Then you can save the document to disk and stream it to the user.
//write the column headers
for (int cIndex = 1; cIndex < 1 + columns; cIndex++)
sheet.Cells.set_Item(4, cIndex, data.Columns[cIndex - 1].Caption);
if (rows > 0)
{
//select the range where the data will be pasted
Range r = sheet.get_Range(sheet.Cells[5, 1], sheet.Cells[5 + (rows - 1), columns]);
//Convert the datatable to an object array
object[,] workingValues = new object[rows, columns];
for (int rIndex = 0; rIndex < rows; rIndex++)
for (int cIndex = 0; cIndex < columns; cIndex++)
workingValues[rIndex, cIndex] = data.Rows[rIndex][cIndex].ToString();
r.Value2 = workingValues;
}
I would use a handler for the .xls file extension and a free component to convert the DataTable to native xls format. The component from this site http://www.csvreader.com/ does more that the URL implies. The newest version of excel will complain about an HTML formatted XLS file. Also keep in mind the size of the data being returned. Your web server should use compression for this extension and your code should check if the number of rows returned is greater than what excel can display in one worksheet; multiple sheets may be required. http://www.mrexcel.com/archive2/23600/26869.htm
Kindly use this code to resolve your problem.This code will convert excel sheet to text format.Hope this will solve your problem
grdSrcRequestExport.RenderControl(oHtmlTextWriter);
string s = "";
s=oStringWriter.ToString().Replace("<table cellspacing=\"0\" rules=\"all\" border=\"1\" style=\"border-collapse:collapse;\">", "");
s="<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=us-ascii\"><meta name=ProgId content=Excel.Sheet><meta name=Generator content=\"Microsoft Excel 11\"><table x:str border=0 cellpadding=0 cellspacing=0 width=560 style='border-collapse: collapse;table-layout:fixed;width:420pt'>"+s.ToString()+"</table></body></html>";
//Byte[] bContent = System.Text.Encoding.GetEncoding("utf-8").GetBytes();
Response.Write(s);

Resources