i am exporting gridview to excel,i am exporting successfully.but in my gridview i have some special symbols like ( •, "", ', -,_ ) these types of symbols cannot export, instead of those place i am getting like ( –, “, â€, ’)this.
how can i over come these problem. here is my code for exporting gridview to excel ?
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=demo.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
gvDetails.DataSource = dt1;
gvDetails.DataBind();
for (int i = 0; i < gvDetails.Rows.Count; i++)
{
GridViewRow row = gvDetails.Rows[i];
row.Attributes.Add("class", "textmode");
}
gvDetails.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
You need to specify and provide encoding information.
Response.ContentEncoding = System.Text.Encoding.Unicode; /*c# uses UTF-16 internally*/
...
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble()); /*Include the UTF-16 header so excel will treat this as UTF-16*/
Response.Output.Write(sw.ToString());
...
Note that this is not the best solution, ideally you should use OpenXML or some other library to export to excel.
Please change your content type to below,
Response.ContentType = "application/ms-excel";
Related
I have written the below code to generate the excel file.
private void ExportReport(IList ApproveListData, string fileName)
{
var gv = new GridView();
gv.AllowPaging = false;
gv.DataSource = ApproveListData;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write("<b> Pending approval report </b>");
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
I have checked data in the grid view but excel file is not generating.
Please help.
Thanks in advance.
I have used the below code. importing the data from List<> to excel works fine but it add the Black line border into a excel file.how can I remove that border from excel file ?
if (id != null)
{
int mid = Convert.ToInt32(clsPasswordHelper.Decryptdata(id));
var objMySavedMedicinePricesResults = db.MedicineRequestDownload(mid).ToList();
GridView gv = new GridView();
gv.DataSource = objMySavedMedicinePricesResults;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToShortDateString() + "_MedicinePrice.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
The way you've used generate html output and client open html file as excel.On this way you can't style excel cells and table.
Use ClosedXML library.with this library you can create a valid excel file and you'll able to modify the style of exported excel.
Example code:
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("Sample Sheet");
worksheet.Cell("A1").Value = "Hello World!";
workbook.SaveAs("HelloWorld.xlsx");
I am trying to export Grid View in excel and I get formatting issue like number is not getting proper(e.g -1.523E+11)
also 0 is missing, where value is leading with 0.
Response.ClearContent();
Response.ClearHeaders();
DataTable dtGetReportBank = new DataTable();
dtGetReportBank = objPO.GetReportBank(id);
gridData.DataSource = dtGetReportBank;
gridData.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "BankCMS" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw1 = new StringWriter();
HtmlTextWriter htw1 = new HtmlTextWriter(sw1);
gridData.AllowPaging = false;
dvContent.RenderControl(htw1);
Response.Write(sw1.ToString());
Response.End();
Btn.Visible = false;
Amol,
The best to way to handle this is using OpenXML.
Create a SpreadsheetDocument -> WorkbookPart -> WorksheetPart -> Cell
While creating a Cell, specify the Cell.DataType and you will get whatever you expect.
Once the Document is filled, use SpreadsheetDocument.Save() method to save the same
Hope this helps!
I would like to export data to a .xlsx file, but I can only seem to export to .xls.
What's the easiest way to export a .xlsx file?
This is the code I use to export to a .xls file:
GridView gv = new GridView();
gv.DataSource = listCatalogue.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Catalogue.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
You can use an external library like EPPlus.
Taken from the EPPlus documentation:
private void DumpExcel(DataTable tbl)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(tbl, true);
//Format the header for column 1-3
using (ExcelRange rng = ws.Cells["A1:C1"])
{
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(79, 129, 189)); //Set color to dark blue
rng.Style.Font.Color.SetColor(Color.White);
}
//Example how to Format Column 1 as numeric
using (ExcelRange col = ws.Cells[2, 1, 2 + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
//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());
}
}
I am using following function to export my data to excel sheet:
string filename = "Test.xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
//Get the H`enter code here`TML for the control.
yourGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
Response.Write(tw.ToString());
but excel sheet is not created. Although it shows in chrome browser bottom that excel is downloading. When it finishs downloading, I click it and it says file cant be opened. Please suggest me what is wrong in it?
[EDIT]
Response.Clear();
Response.Buffer = true;
//use Response.AddHeader
Response.AddHeader("content-disposition", "attachment;filename=Test.xlsx");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
gvLogs.RenderControl(hw);
gvLogs.AllowPaging = false;
gvLogs.DataBind(); // bind data
Response.Output.Write(sw.ToString());
//need to call Flush and End methods
Response.Flush();
Response.End();
give same error
Epplus is a good library for excel import/export. You can check it out.
You can try this one
private void ExportToExcel(DataTable dt)
{
if (dt.Rows.Count > 0)
{
string filename = "DownloadReport.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 = dt;
dgGrid.DataBind();
//Get the HTML for the control.
dgGrid.RenderControl(hw);
//Write the HTML back to the browser.
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}
Change the 'Response.ContentType' value in your code as like below.
Response.ContentType = "application/vnd.xls";
Hope this will help you.
check below code
Response.Clear();
Response.Buffer = true;
//use Response.AddHeader
Response.AddHeader("content-disposition", "attachment;filename=Test.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
GridView1.AllowPaging = false;
GridView1.DataBind(); // bind data
Response.Output.Write(sw.ToString());
//need to call Flush and End methods
Response.Flush();
Response.End();