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