This question already has answers here:
How do I export to Excel?
(3 answers)
Closed 6 years ago.
I am trying to import data from excel to mvc
public void DownloadAsExcelOrderReports()
{
try
{
var list = _reportWork.GetList();
GridView gv = new GridView();
gv.DataSource = list;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.UTF32;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
catch (Exception ex)
{
}
}
This is the code I found online.I get an output like this.
Normally it has to fill in the table itself automatically into excel.I can't see, what i missed.
GridView is a WebControl. You put data into it (DataBind) and it emits html (RenderControl) which is supposed to be sent to the browser and the browser will show it as a table (tr and td tags).
In your case you're trying to show that html code within an excel document and that makes no sense.
The best I've found is to use EPPlus, which you can get from NuGet Package Manager. You have to tie together your data to what you want the excel doc to look like. It's a bit fiddly but there's no alternative.
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);
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 am currently formatting a Date for a specific Excel file Export from a DataSet/DataGrid.
The Date is formatted like so:
DateTime date = Convert.ToDateTime(entry.Date);
string formatdate = String.Format("{0:yyyy/MM/dd}", date);
Once creating the DataSet is said and done, I use the following code to Export the DataSet to an Excel file:
public static void ExportDStoExcel(DataSet ds, string filename)
{
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.Charset = "";
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
}
My only problem is once I export this to Excel, Excel Auto-Formats the Dates like this: MM/DD/YYYY instead of YYYY/MM/DD.
I understand this could be achieved manually by opening in Excel, but the Export is being built into an Automated System and needs to be hard coded.
Is there any way of bypassing Excel's DateTime Auto-Formatting?
I had the same issue and solved it by adding a non breaking space ( ) in front of the text. Stopped Excel from auto-formatting. Not the cleanest solution but did the trick for me...
Right now you are just outputting HTML table, that Excel interprets how it likes. You'd have bring yourself down to Excel's level to be able to specify column's properties (set type to Text instead of General).
This means that you need to generate actual xls file (there are various libraries out there for that). Or (if restriction to Office 2010 is acceptable) got with Open XML format which you can write with regular .NET API.
You can style excel cells with mso-number-format
mso-number-format:"\\#"
\# will tell excel to treat all data in text format only. So auto format won't happen.
Please update your code like this:
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
response.Write("<head><style> td {mso-number-format:\\#;} </style></head><body>");
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.Write("</body></html>");
response.End();
}
}
OR
you can try with specific date format also.
Refer: http://cosicimiento.blogspot.in/2008/11/styling-excel-cells-with-mso-number.html
mso-number-format:"yyyy\/mm\/dd"
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.