I generate Excel document in ASP.Net with below code:
if (dataTable.Rows.Count > 0)
{
var tw = new StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new DataGrid();
dgGrid.DataSource = dataTable;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
attachment = "attachment; filename=" + fileName + ".xls";
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", attachment);
outputResponse = tw.ToString();
}
But when I want to open Excel document it gives error:
Error: excel cannot open the file .xls because the file format or
file extension is not valid
How can I solve it?
Either use a reference to the Excel Application object to create an actual excel file, use one of the many codeplex based projects to create an Excel spreadsheet or most easily create a CSV file from your datagrid and return that, which many users computers will prompt them to open in Excel.
Just tried your code, with exception of the last line, which I've changed:
var tw = new StringWriter();
var hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new DataGrid();
dgGrid.DataSource = dataTable;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
var attachment = "attachment; filename=" + fileName + ".xls";
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", attachment);
// outputResponse = tw.ToString();
Response.Output.Write(tw.ToString());
Response.Flush();
Response.End();
My datatable is a 2-col table with simple data (letters and numbers)and it is opened as it should.
You will get the message that says:
The file you are trying to open'yourfilename.xls', is in a different
format thahn specified by the file extension. Verify that the file is
not corrupted and is from a trusted source before opening the file. Do
you want to open the file now?
After clicking OK the file opens just fine.
Related
I'm working on adding Export functionality to an existing site. I've created an Excel file, and I'm able to output it to my local directory, but when I try pushing the file to the user using Response, nothing happens. I've viewed several differnet articles and Stack questions, and none seem to be different from what I have, or work when I apply them.
Here is the code I currently have:
public void Export () {
//Create instance of the database
ExportContext eDB = new ExportContext();
var query = (from x in eDB.EMPLOYEES
select x);
IEnumerable<EMPLOYEES> employees = query.ToList();
//Set filename to Table + date/time
string fileName = "EMPLOYEES" + DateTime.Now.ToShortTimeString() + ".xlsx";
//Create excel package
ExcelPackage excel = new ExcelPackage();
var worksheet = excel.Workbook.Worksheets.Add("Employees");
worksheet.Cells[1, 1].LoadFromCollection(employees, true);
using (var memoryStream = new MemoryStream()) {
//Output the file to the user via download
Response.Buffer = false;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
Response.End();
}
}
Any help will be appreciated. Thanks.
Here is my code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
It just create an excel file, but i have an unicode problem, can't read Georgian charachters. Look at the picture :
Maybe it's a duplicate but no solution worked for me.
Your code doesn't create a real XLSX file, it creates an HTML table with a faked header and extension. Excel will import this file using the end user's default settings and locale.
Instead of faking Excel files, you can easily create a real XLSX file with minimal code using a library like EPPlus. There's even a Web Application example in the Codeplex site. You can use LoadFromCollection instead of LoadFromDataTable in your case:
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
var ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1.
// Print the column names on row 1
var table=ws.Cells["A1"].LoadFromCollection(model, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelDemo.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Note that table is an actual ExcelRange object, that can be given a name, style etc.
Okey i solve the problem :
just change Response.ClearContent() to Response.Clear() and add
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />")
full code :
var model = _db.FacebookInfo.OrderByDescending(f => f.Followers).ToList();
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = (from u in model
select new
{
fullname = System.Text.RegularExpressions.Regex.Replace(u.FullName, "<span .*?>(.*?)", ""),
followers = u.Followers,
friends = u.Friends,
url = u.FbLink
}).ToList();
grid.DataBind();
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Nana bregvadze Friends.xls");
Response.ContentType = "application/excel";
Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
I want to export a list with over 10000 rows to excel using MVC5 C#.
when I export using DataGrid some columns are not shown in the excel file - 3 columns are disapeard in the excel file but all the 10000 rows appeard.
string filename = Guid.NewGuid() + ".xls";
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
List registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id).ToList();
dgGrid.DataSource = registrationsetList;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
If I change DataGrid dgGrid = new DataGrid()
to GridView dgGrid = new GridView();
with list of 600 of rows, the excel looks perfect with all the columns.
the problem is when i export all the list of 10000 rows, the excel file got stuck - i got not responding message.
why ?
Instead of using a DataGrid() try using a WebControl GridView():
string filename = Guid.NewGuid() + ".xls";
var gv = new System.Web.UI.WebControls.GridView();
var registrationsetList = db.RegistrationSet.Where(x => x.QuestionId == TheQuestion.Id);
g.DataSource = registrationsetList;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWiter sw = new StringWriter();
var htw = new System.Web.UI.HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
The problem (with that stucked excel file) was solved with DataGrid. The problem was that the DateGrid doen't show columns of nullable fields in the CLASS in the list that i bound to the GridView.
i have written code to export data but warning message i am facing while opening the excel file and by default file is saving as .html extension
warning - "The file you are opening in a different format than specified by the file extension"
i need with .xls extension to be saved
please help me
private void ExportToExcel(DataTable dt)
{
string fileName = "FileName" + DateTime.Now.ToString("MMddyyyy_HHmmss") + ".xls";
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
//Response.AddHeader("content-disposition", "attachment;filename=Filename .xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
dataExportExcel.ItemDataBound += new DataGridItemEventHandler(dataExportExcel_ItemDataBound);
dataExportExcel.DataSource = dt;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
System.Text.StringBuilder sbResponseString = new System.Text.StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:xlExcel8\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head></head> <body>");
sbResponseString.Append(stringWriter + "</body></html>");
Response.Write(sbResponseString.ToString());
Response.End();
}
Use this one - http://www.gemboxsoftware.com/spreadsheet/overview
Looks like this in use:
// Create new Excel file.
var excelFile = new ExcelFile();
excelFile.Worksheets.Add(dt.TableName).InsertDataTable(dt, 0, 0, true);
// Save Excel file to XLS format.
excelFile.SaveXls(dataSet.DataSetName + ".xls");
I am using the below code for export the data to excel sheet.
private void ExportToExcel(string fileName)
{
fileName = "MyXML.xls";
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
rptLinks.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Everything is working fine but when I try to open the excel file MyXML.xls by double clicking, a popup/dialog box open with the below message :
"The file you are trying to open , MyXML.xls is in different format than specified by the file extension. " etc..
Can we make some changes in code so that no popup/dialog should come?
Hope this helps
http://devblog.grinn.net/2008/06/file-you-are-trying-to-open-is-in.html
change Response.ContentType = "application/vnd.xls"; to Response.ContentType = "application/vnd.ms-excel"