warning message while opening the excel file after export from gridview - c#

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

Related

Adding Multiple worksheet with excel while export in mvc

Actually i am looking to export an excel file from dataTable. I managed to do it. But how can i add an empty sheet in the same excel file while exporting from dataTable?
Here is my code :
public void ExportToExcel(DataTable dts)
{
if (dts.Rows.Count > 0)
{
string filename = "2.Dependent Master.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dts;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
Response.End();
}
}
Any help appreciated. Thanks in Advance !!!!
You can't add multiple worksheets with simple HTML.
instead of you can use Closed XML open source library
https://closedxml.codeplex.com/
Sample
var workbook = new XLWorkbook();
var worksheet1 = workbook.Worksheets.Add(PassYourDatatable1);
var worksheet2 = workbook.Worksheets.Add(PassYourDatatable2);
How to add Datatable to worksheet

asp.net export to Excel UTF-8

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

Export Datatable To Excel Format / Extension Error

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.

A dialog box comes when I try to open excel file with .xls as extension

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"

download multiple pdf

I am trying to download multiple pdf's as attachments in my asp.net application.I have created some templates and filling values using pdfstamper(itextsharp). I am able to fill the values but not able to download.
private void FillForm(string path, DataTable BridgeValues, DataTable Comments, DataTable Maintenance,string Newfilename)
{
try
{
string pdfTemplate = path;
string newFile = Newfilename;
string Pathser = "";
if (!System.IO.Directory.Exists(Server.MapPath(#"~/PDF/")))
{
System.IO.Directory.CreateDirectory(Server.MapPath(#"~/PDF/"));
}
if (Directory.Exists(Server.MapPath(#"~/PDF/")))
{
Pathser = Server.MapPath(#"~/PDF/" + Newfilename);
}
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(Pathser, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
DataColumn dc = null;
for (int i = 0; i < BridgeValues.Columns.Count - 1; i++)
{
dc = BridgeValues.Columns[i];
pdfFormFields.SetField(dc.ColumnName.ToString(), BridgeValues.Rows[0][dc].ToString());
}
pdfStamper.FormFlattening = true;
// close the pdf
pdfStamper.Close();
////Response.ContentType = "application/octet-stream";
Response.ContentType = "application/pdf";
////Response.AddHeader("Content-Disposition", "attachment; filename=Report.pdf");
Response.AddHeader("Content-Disposition", "attachment; filename=" + Newfilename + "");
////Response.BinaryWrite(mStream.ToArray());
Response.TransmitFile(Server.MapPath(("~/PDF/"+ Newfilename)));
Response.Clear();
Response.End();
}
catch (System.Threading.ThreadAbortException lException)
{
// do nothing
}
}
First time I tried to create one pdf ,it worked but later when I tried to download multiple files it gave an execption.
Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.
I don't think you can download multiple files by making one request and returning a collection from the action. I would suggest that it you need to allow user to download multiple files you ZIP them and stream the archive down to the browser.
Here is an example of zipping multiple files: http://devpinoy.org/blogs/keithrull/archive/2008/01/25/how-to-create-zip-files-in-c-with-sharpziplib-ziplib.aspx

Categories

Resources