I want to create a csv file with bold header text.This following code is creating one header row.But i want this header in bold style.
'Add Response header
Response.Clear()
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.csv", "check_"))
Response.Charset = ""
Response.ContentType = "application/vnd.csv"
Try
Dim sb As New StringBuilder()
'Add Header dr.GetName(count)
For count As Integer = 0 To GridView1.Columns.Count - 1
If GridView1.Columns(count) IsNot Nothing Then
sb.Append(GridView1.Columns(count).HeaderText)
End If
If count < GridView1.Columns.count - 1 Then
sb.Append(",")
End If
Next
Response.Write(sb.ToString() + vbLf)
Response.Flush()
Catch ex As Exception
Response.Write(ex.Message)
End Try
Response.[End]()
CSV is plain text seperated by commas (,)
There is no styling attached to it.
As others have already mentioned, a CSV is just text without formatting.
Since i'm assuming that you want the bold header in excel and you're exporting an ASP.NET GridView to a CSV file, there are two other options:
Render the GridView's HTML(a HTML-Table) with a bold header to a file, excel will interpret it correctly
Create a real excel file, i can recommend EPPlus warmly, here's a sample.
Sample for the first approach:
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();
If you run the code as above, it will result in an HttpException as follows:
Control 'GridView1' of type 'GridView' must be placed inside a form
tag with runat=server."
To avoid this error, add the following code:
public override void VerifyRenderingInServerForm(Control control)
{
// yes, it's correct that this is empty
}
Related
I'm using Server.Transfer and in the 2nd place I have a number of labels that are updated with a Request.Form["textbox_text"];
This all works really well, but the problem is I also want to write the content in that textbox to file
like a word document using this method
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=Word.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application / vnd.ms -word";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.Write("<table><h2><b>[ Text ]</b></h2><br>" + TextBox_name.Text + "</table>");
Response.Write(sw.ToString());
Response.End();
But whenever I check the file it will not have anything written on it. I've even tried to save the value of a Request.Form to a static variable and then write that variable but without any success.
How are you using Server.Transfer()? Post that code, make sure you are using the overload that preserves the form values:
Server.Transfer("page.aspx", true);
I am exporting data into Excel from a web page. This should be a no brainer, but there are <p> tags in the data. This causes Excel to create new rows when the data should all be in the same cell. After some research I found that mso-data-placement should do the trick, but it's not working. Excel opens, the data is displayed, but extra uncessary rows are created. Here is the code I use to export the data:
protected void doexcel()
{
string style = #"<style type='text/css'>P {mso-data-placement:same-cell; font-weight:bold;}</style>";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
//set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
Random RandomClass = new Random();
int RandomNumber = RandomClass.Next();
String filename = "a" + RandomNumber + DateTime.Now + ".xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"" );
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
HttpContext.Current.Response.Write(style);
SqlDataSourceEmployeeAssets.ConnectionString = MyObjects.Application.CurrentContext.ConnectionString;
String sql = (string)Session["sql"];
SqlDataSourceEmployeeAssets.SelectCommand = sql;
// lCount.Text = "Query returned " + getCount(query) + " rows.";
DataGrid dge = new DataGrid();
dge.DataSource = SqlDataSourceEmployeeAssets;
dge.DataBind();
dge.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
This is an example of the raw data in the database that is giving me grief:
<P>4/13/2011 : Cheng "Jonathan" Vaing is with BSES Graffiti Unit.</P><P>4/13/2011 : Cheng "Jonathan" Vaing is with</P>
Suggestions?
I tried a couple of other things
I went straight to the data and added the mso-data-placement attribute to the paragraph tag inline. Still didn't work. The data looked like this
<P style="mso-data-placement:same-cell> my data </p>
I tried other mso-* attributes, that didn't work either. For example, I changed my stylesheet to look like this
<style type='text/css'>P {mso-highlight:yellow}</style>";
Why oh why doesn't Excel recognize my mso-* attributes?!?!
There is a solution but it is not clean.
After the dge.DataBind, place the following code. This will encode the text of each cell
foreach (DataGridItem dgi in dge.Items)
{
foreach (TableCell cell in dgi.Cells)
{
cell.Text = WebUtility.HtmlEncode(cell.Text);;
}
}
The Excel file, when opened, should show the raw data with the markup, all in one cell.
I found that this works because Excel actually encodes the text, as well. To see what Excel does in action, do the following:
Create a new workbook in Excel (I am using Office 2013).
In the first cell, paste the raw data (as you have it displayed). Do this by first pressing F2 (insert into cell), then paste the text.
Save the workbook as an HTML file (or web page).
Using windows explorer, go to the folder location of where you saved the file. There should be a hidden folder (i think it is hidden) with the same name as your file. For example, if your workbook is Book1.htm, there should be a folder labeled Book1_files.
In this folder, there should be an HTM file with the name sheet001.htm. Open this file in notepad (or any text editor...not excel or word)
Locate your raw data. You will see that the text is not showing the HTML markup, rather it is showing the encoded version.
Hope this helps.
In ASP.NET 4.0 webforms, I'm trying to export a paged ListView control to an Excel file by un-paging the ListView's (trucks) datasource:
dsTrucks.EnablePaging = false;
For a non-paged ListView control, I can get it to work.
Here's the attempt to "un-page" and then export the ListView control:
// Nuke the current page.
Response.Clear();
// Setup the response header.
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
// Turn off view state.
this.EnableViewState = false;
// Create a string writer.
var stringWriter = new StringWriter();
// Create an HTML text writer and give it a string writer to use.
var htmlTextWriter = new HtmlTextWriter(stringWriter);
// Disable paging so we get all rows.
dsTrucks.EnablePaging = false;
// Render the list view control into the HTML text writer.
listViewTrucks.DataBind();
listViewTrucks.RenderControl(htmlTextWriter);
// Grab the final HTML out of the string writer.
string output = stringWriter.ToString();
// Write the HTML output to the response, which in this case, is an Excel file.
Response.Write(output);
Response.End();
There's no error but the output in the Excel file is still just one page of the ListView control instead of all rows.
Any ideas on where to start to get this to work?
Thanks,
Adam
Just a guess, but it might be that EnablePaging works only on the control's OnInit() and it is too late by the time you call it from your code.
Perhaps you could you set the PageSize some MAXINT value and force all results into one single page?
i m trying to generate an excel file from my web page but i have some issues with Turkish chars such as "İ" "ğ" when i open the file some chars are incorrect (İ seems Ä°) here is my code
gvExpRequests.DataSource = dsExpRequests;
gvExpRequests.DataBind();
gvExpRequests.GridLines = GridLines.Both;
Page.EnableViewState = false;
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=export.xls");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = Encoding.UTF8;
Response.BinaryWrite(Encoding.UTF8.GetPreamble());
StringWriter yaz = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(yaz);
gvExpRequests.RenderControl(htw);
i don't know what's wrong with here i tried a lot of encoding but i got same results every time i want to try something different to do this are there any another way to export a excel file from a gridview
I trying to export an HTML table named Table that is dynamically binded to ViewData.Model in C#. I have a method called export that is called based on another method's actions. so everything before that is set up.. I just don't know how to export the data to a CSV or Excel file.. So when the I step inside the Export method I don't know what next to do to export the table. Can someone help me
public void Export(List<data> List)
{
//the list is the rows that are checked and need to be exported
StringWriter sw = new StringWriter();
//I don't believe any of this syntax is right, but if they have Excel export to excel and if not export to csv "|" delimeted
for(int i=0; i<List.Count;i++)
{
sw.WriteLine(List[i].ID+ "|" + List[i].Date + "|" + List[i].Description);
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
I don't quite understand the whole "export an HTML table named Table that is dynamically binded to ViewData.Model" so I'll just ignore that and focus on your Export(List<data> list) method. Btw, you never really mentioned what was going wrong and where.
I see you had written "if they have Excel export to excel and if not export to csv" - I would personally just export it as a CSV file in both cases because excel can handle csv files no problem.
So with that in mind, here would be my export method based on your code.
public void Export(List<DataType> list)
{
StringWriter sw = new StringWriter();
//First line for column names
sw.WriteLine("\"ID\",\"Date\",\"Description\"");
foreach(DataType item in list)
{
sw.WriteLine(string.format("\"{0}\",\"{1}\",\"{2}\"",
item.ID,
item.Date,
item.Description));
}
Response.AddHeader("Content-Disposition", "attachment; filename=test.csv");
Response.ContentType = "text/csv";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
Response.Write(sw);
Response.End();
}
This is an excellent example, but I think that need a globalization modification.
String ltListSeparator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator;
sw.WriteLine(string.format("{0}" + ltListSeparator + "{1}" + ltListSeparator + "{2}", item.ID, item.Date, item.Description));
I think your controller action method will need to wrap the data items in an html table which you may want to do any way you like, So your html+ data will be stored in a string and then you could do something like below- (its not exacly built for MVC but its easy to modify for it).
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
Response.Write(yourDataAndHtmlAsString);
Response.End();
CSV is a simple format and can be built up easily as a string.
http://en.wikipedia.org/wiki/Comma-separated_values
You could create an excel spreadsheet of what you think the end product should look like, save as CSV, open it in notepad and try and replicate it using a string builder.