I need to export gridview data to excel on button click.
But in gridview one column data need to be changed with data that is another table from database.
For example:
Gridview showing employee ID(empid) from one table but I need to show username in place of empid in excel data.
The export to Excel:
protected void btmexport_Click(object sender, EventArgs e)
{
string attachment = "attachment; filename=Export.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
HtmlForm frm = new HtmlForm();
grd_data.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(grd_data);frm.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
Related
I have a datatable that returns a large amount of Data. I want to export specific columns to specifc cells in excel using c#.
So far I am able to export whole datatable to excel using below code:
protected void btnExcel_Click(object sender, EventArgs e)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
ExportUtility EU = new ExportUtility();
string qry = printPr.Value;
DataTable dtnew =getDataTableFromQuery(qry);
EU.ExportDataTableToWorkbook(dtnew, "DownloadSheet", workbook);
//Response
string saveAsFileName = string.Format("abc" + ".xls");
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",
saveAsFileName));
Response.Clear();
Response.BinaryWrite(EU.GetBytes(workbook));
Response.End();
Response.Clear();
}
How can I export columns to specific columns in Excel ?
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 a page with Gridview and when button clicked I should export data from Gridview to .xls file. I have tried it in many ways. This is my code:
protected void export_Click(object sender, EventArgs e)
{
Response.ClearContent();
//Response.Buffer = true;
//Response.ClearHeaders();
//Response.CacheControl = "no-cache";
//Response.AddHeader("Pragma", "no-cache");
Response.AddHeader("Content-Disposion","attachment; filename=Clients.xls");
Response.ContentType = "application/excel";
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
grid.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}
The problem is when I click the button it is exporting aspx file. I have tried all answers in Stackoverflow and from other sources as well. However, I am not being able to correct it. I need exact reason why it is so and some possible solutions.(I tried Content-type as "application/excel", "application/vn", "application/vn-excel" as well.)
You can just follow following code, it is working fine..
protected void cmdExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=SupplierList.xls");
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter WriteItem = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlText = new HtmlTextWriter(WriteItem);
GridView1.AllowPaging = false;
DataTable dtSupplier = (DataTable)ViewState["dtSupplier"];
GridView1.DataSource = dtSupplier;
GridView1.DataBind();
GridView1.RenderControl(htmlText);
Response.Write(WriteItem.ToString());
Response.End();
}
Hope this will help you.
thanks
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 really appreciate if anyone can help me on how can I enable the filter feature on Excel when exporting the data from gridview.( Excel Autofilter)
public ActionResult ExportToExcel(List<EventViewModel> list)
{
try
{
// Main
GridView gv = new GridView();
gv.DataSource = list.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.Charset = "";
Response.AddHeader("content-disposition", "attachment; filename=filename.xls");//Response.AddHeader("content-disposition", "inline; filename=Excel.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("Index");
}
catch (System.Exception e)
{
return View("Error");
}
}
Your code exports an HTML file with XLS extension. It is not a binary XLS file and you cannot have an Excel autofilter, not using your code.
If you can't use Microsoft.Office.Interop.Excel library, you can search for another Excel library that exports real Excel files.
I use EasyXLS Excel library. This code exports the datatable of the gridview and adds an autofilter and it use this library:
// Create an instance of the class that exports Excel files, having one sheet
ExcelDocument xls = new ExcelDocument(1);
// Get the sheet
ExcelWorksheet xlsWorksheet = (ExcelWorksheet)xls.easy_getSheetAt(0);
// Create a dataset that keeps the gridview datatable
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)gridView.DataSource);
// Insert the dataset into sheet
xlsWorksheet.easy_insertDataSet(dataSet, true);
//Add AutoFilter
ExcelFilter xlsFilter = xlsWorksheet.easy_getFilter();
xlsFilter.setAutoFilter("A1:E1");
// Choose a name for the xls file
string fileName = "filename.xls";
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
Response.ContentType = "application/vnd.ms-excel";
// Export Excel file and prompt the "Open or Save Dialog Box"
xls.easy_WriteXLSFile(Response.OutputStream);
// Dispose memory
xls.Dispose();
Response.End();
For more details on formatting read this link about export gridview to Excel.