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());
}
}
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 generate an excel file using the following code but I don't see any grids or lines in the excel file. I have my data but no lines. Any idea how to get the lines/regular grid?
Table oTable = new Table();
//Add data to table.
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename="test.xls"");
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.Html32TextWriter oHtmlTextWriter = new System.Web.UI.Html32TextWriter(oStringWriter);
oTable.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
Can someone please help!?
You can see grid lines in Excel if you add a Border attribute to the Table:
Table oTable = new Table();
oTable.Attributes.Add("Border", "1");
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";
i have develop an application for online store in which different store keep there catalog online. but i have to develop an functionality for download there catalog in xls file for that i have my data in datatable which i have to write in dynamically generated xls file and download it.
for that i have try fallowing :
DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT * FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1");
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment;filename=Catalog.xls");
Response.ContentType = "application/excel";
Response.Write(ProductDetails);
Response.End();
i refer it here
but am not getting any thing
please help to get out of it.
I use the EPPlus package, which you can install via Nuget. It allows you to load data onto an Excel worksheet directly from your datatable, and it includes support for things like formatting on the worksheet (fonts, column widths etc). See their
documentation page here on using it inside a web application.
For your case, I would suggest something like:
DataTable ProductDetails = sql.ExecuteSelectCommand("SELECT * FROM Products_Details_View WHERE Supp_Id = " + Session["SuppID"].ToString() + " and Is_Available = 1");
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(ProductDetails, true);
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ProductDetails.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
}
Try this
string attachment = "attachment; filename=xxxx" + DateTime.Now + ".xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
ProductDetails.RenderControl(htextw);
GridView dg = new GridView(); //Create an empty Gridview to bind to datatable.
dg.AutoGenerateColumns = true;
dg.DataSource = ProductDetails;
dg.DataBind();
dg.RenderControl(htw);
Response.Write(stw.ToString());
stw.Close();
Response.End();