Hi all,
I have a problem with exporting to Excel XLSX format using C# and ASP.Net and ClosedXML.Excel
In practice when I execute the stored procedure on the DB I have this output
instead when I export to excel I get this output
Can you help me?
My code below
public static void ExportDataSetToExcel(DataSet ds)
{
string AppLocation = @"D:\inetpub\wwwroot\PUBLIC\ExcelFiles\";
string guid = Guid.NewGuid().ToString().ToUpper().Replace("-", "_");
HttpContext.Current.Response.Cookies["guid"].Value = guid.ToString();
HttpContext.Current.Response.Cookies["guid"].Expires = DateTime.Now.AddMinutes(3);
string filepath = AppLocation + "Export_" +
DateTime.Now.ToString("ddMMyyyyHHmm") + "_" +
HttpContext.Current.Response.Cookies["guid"].Value + ".xlsx";
using (XLWorkbook wb = new XLWorkbook())
{
for (int i = 0; i < ds.Tables.Count; i++)
{
wb.Worksheets.Add(ds.Tables[i], ds.Tables[i].TableName);
}
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
wb.SaveAs(filepath);
wb.Dispose();
}
Thread.Sleep(3000);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentType = "application/force-download";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; " +
"filename=Export_" +
DateTime.Now.ToString("ddMMyyyyHHmm") + "_" +
HttpContext.Current.Response.Cookies["guid"].Value + ".xlsx");
HttpContext.Current.Response.TransmitFile(@"D:\inetpub\wwwroot\PUBLIC\ExcelFiles\Export_" +
DateTime.Now.ToString("ddMMyyyyHHmm") + "_" +
HttpContext.Current.Response.Cookies["guid"].Value + ".xlsx");
HttpCookie cookie = new HttpCookie("ExcelDownloadFlag")
{
Value = "Flag",
Expires = DateTime.Now.AddDays(1)
};
HttpContext.Current.Response.AppendCookie(cookie);
HttpContext.Current.Response.End();
}
protected void btnxlsx_Click(object sender, ImageClickEventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
using (MySqlConnection con =
new MySqlConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (MySqlCommand cmd =
new MySqlCommand("sProc_20241009", con))
{
cmd.CommandTimeout = 2147483;
cmd.Connection.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Clear();
cmd.Parameters.AddWithValue("@ID", id.Text.ToString());
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(ds);
ExportDataSetToExcel(ds);
}
}
}