Export DataSet for Excel 2007 EPPlus
I am trying to export a DataSet for Excel 2007, I cannot use the normal code that is used to export using mime types in contenttype, for example this application Response.ContentType = "/ ms-excel"; "If I use the mime type for xls, I get a warning when ai tries to export, I cannot get this error because of clients, so I started using EPPlus, but now I have pending errors like" ArgumentNullException was unhandled user code ". When I debbuging I noticed that the ds variable in the btnExportClick method is zero, I think that's where erros is, but I can't figure out where, here is the complete code:
namespace PortalFornecedores
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
public void BindGrid()
{
using (DataSet ds = new DataSet())
{
ds.ReadXml(Server.MapPath("~/Customers.xml"));
GridFornecedor.DataSource = ds;
GridFornecedor.DataBind();
}
}
public void btnExportClick(object sender, EventArgs e)
{
DataTable ds = GridFornecedor.DataSource as DataTable;
ExportExcel(ds);
}
public void ExportExcel(DataTable ds)
{
using (ExcelPackage pck = new ExcelPackage())
{
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("SearchReport");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(ds, true);
//prepare the range for the column headers
string cellRange = "A1:" + Convert.ToChar('A' + ds.Columns.Count - 1) + 1;
//Format the header for columns
using (ExcelRange rng = ws.Cells[cellRange])
{
rng.Style.WrapText = false;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
rng.Style.Font.Bold = true;
rng.Style.Fill.PatternType = ExcelFillStyle.Solid; //Set Pattern for the background to Solid
rng.Style.Fill.BackgroundColor.SetColor(Color.Gray);
rng.Style.Font.Color.SetColor(Color.White);
}
//prepare the range for the rows
string rowsCellRange = "A2:" + Convert.ToChar('A' + ds.Columns.Count - 1) + ds.Rows.Count * ds.Columns.Count;
//Format the rows
using (ExcelRange rng = ws.Cells[rowsCellRange])
{
rng.Style.WrapText = false;
rng.Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
}
//Read the Excel file in a byte array
Byte[] fileBytes = pck.GetAsByteArray();
//Clear the response
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ExcelReport.xlsx\"; " +
"size=" + fileBytes.Length.ToString() + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client
Response.BinaryWrite(fileBytes);
Response.End();
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */`enter code here`
}
}
source to share
A couple of things. This is not an apple problem, a more general network.
First, you set the DataSource of the grid to the dataSET here:
using (DataSet ds = new DataSet())
{
ds.ReadXml(Server.MapPath("~/Customers.xml"));
GridFornecedor.DataSource = ds;
but later move on to the datasheet here:
DataTable ds = GridFornecedor.DataSource as DataTable;
when you must first overlay on a dataset then get the first table of your table collection.
But that won't solve the problem yet, because you have a class level object that won't issue messages via postbacks. You need to use session or viewstate variable like this:
public void BindGrid()
{
using (DataSet ds = new DataSet())
{
ds.ReadXml(Server.MapPath("~/Customers.xml"));
GridFornecedor.DataSource = ds;
GridFornecedor.DataBind();
ViewState["GridDataSource"] = ds;
}
}
public void btnExportClick(object sender, EventArgs e)
{
//DataTable ds = GridFornecedor.DataSource as DataTable;
var ds = ViewState["GridDataSource"] as DataSet;
var dt = ds.Tables[0];
ExportExcel(dt);
}
source to share