Hi there i have this code to export my data gridview to excel
and my problem is that, the gridview shows a 12hr format but when i export it to excel it shows a 24hr format, how ca i make it into 12 hr format? thank you.
DataSet ds = (DataSet)ViewState["audit"];
DataTable dt = new DataTable();
dt = ds.Tables[0];
Table table = new Table();
AuditTrailGV.AllowPaging = false;
AuditTrailGV.DataSource = (DataSet)ViewState["audit"];
AuditTrailGV.DataBind();
for (int i = 0; i < AuditTrailGV.HeaderRow.Cells.Count; i++)
{
AuditTrailGV.HeaderRow.Cells[i].Style.Add("background-color", "#bfc2c7");
}
AuditTrailGV.HeaderRow.Style.Add("border-color", "#FFFFFF");
int j = 1;
foreach (GridViewRow gvrow in AuditTrailGV.Rows)
{
//gvrow.BackColor = color.White;
gvrow.Style.Add("background-color", "#FFFFFF");
gvrow.Style.Add("border-color", "#bfc2c7");
if (j <= AuditTrailGV.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
else
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("border-color", "#bfc2c7");
}
}
}
j++;
}
foreach (GridViewRow row in AuditTrailGV.Rows)
{
table.Rows.Add(row);
}
TableHeaderCell header = new TableHeaderCell();
header.RowSpan = 1;
header.ColumnSpan = 6;
header.Text = "Inventory Accounting and Control System";
header.Font.Bold = true;
header.HorizontalAlign = HorizontalAlign.Center;
header.VerticalAlign = VerticalAlign.Middle;
header.Font.Size = 20;
TableRow headerrow = new TableRow();
headerrow.Cells.Add(header);
TableHeaderCell header2 = new TableHeaderCell();
header2.RowSpan = 1;
header2.ColumnSpan = 6;
header2.Text = "Audit Trail";
header2.Font.Bold = true;
header2.HorizontalAlign = HorizontalAlign.Center;
header2.VerticalAlign = VerticalAlign.Middle;
header2.Font.Size = 16;
TableRow headerrow2 = new TableRow();
headerrow2.Cells.Add(header2);
TableHeaderCell header3 = new TableHeaderCell();
header3.RowSpan = 1;
header3.ColumnSpan = 6;
header3.Text = DatefromTxtBox.Text + " to " + DatetoTxtBox.Text;
header3.Font.Bold = true;
header3.HorizontalAlign = HorizontalAlign.Center;
header3.VerticalAlign = VerticalAlign.Middle;
header3.Font.Size = 16;
TableRow headerrow3 = new TableRow();
headerrow3.Cells.Add(header3);
table.Rows.AddAt(0, headerrow);
table.Rows.AddAt(1, headerrow2);
table.Rows.AddAt(2, headerrow3);
table.Rows.AddAt(3, AuditTrailGV.HeaderRow);
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "IACSAuditTrail" + "[" + DatefromTxtBox.Text.Replace("/", "") + "_" + DatetoTxtBox.Text.Replace("/", "") + "]" + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
table.RenderControl(htw);
Response.Write(sw.ToString());
Response.End()
This it what it looks
but this is what i looks when i export it to excel :(
The only way to save date format is to pre-format the date field as text and then export to excel. To do this,
string style = #"<style> TD { mso-number-format:\#; } </style> ";
Response.write(style);
//Code to Export Control
Panel1.RenderControl(htmlWrite);
you can refer to below link for more information
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
Related
I have the following code to export data to an Excel sheet. I need your help to know how I can color the sheet columns in other colors?
System.Data.DataTable dit = null;
try
{
dit = BindGrid();
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dit, "Students");
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Download.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
catch (Exception Ex)
{
}
finally
{
dit = null;
}
using Excel = using Microsoft.Office.Interop.Excel
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
string path = excelFilename + ".xlsx";
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
app.Visible = true;
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
}
worksheet.Cells[i + 2, 1].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
}
workbook.SaveCopyAs(path);
workbook.Saved = true;
workbook.Close();
app.Quit();
}
I need to improve performance of the code that maps datatable to excel spreadsheet.
The old code loops through the datatable and creates excel. I created a timer too print out the time it takes to generate the report for this approach:
var watch = System.Diagnostics.Stopwatch.StartNew();
System.Data.DataTable dt = new System.Data.DataTable();
dt = (System.Data.DataTable)Session["ISOReport"];
TableCell td;
TableRow tr;
HyperLink a;
TableHeaderRow thr;
TableHeaderCell thc;
thr = new TableHeaderRow();
thr.BorderStyle = BorderStyle.Solid;
thr.BorderColor = System.Drawing.Color.White;
for (int i = 0; i < dt.Columns.Count; i++)
{
thc = new TableHeaderCell();
thc.Text = dt.Columns[i].ColumnName;
thr.Cells.Add(thc);
}
tblReport.Rows.Add(thr);
for (int j = 0; j < dt.Rows.Count; j++)
{
tr = new TableRow();
tr.BorderStyle = BorderStyle.Solid;
tr.BorderColor = System.Drawing.Color.White;
for (int i = 0; i < dt.Columns.Count; i++)
{
td = new TableCell();
td.Text = dt.Rows[j][i].ToString();
tr.Cells.Add(td);
}
tblReport.Rows.Add(tr);
}
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
lblInfo.Text = ReportName + " Generation Time: " + elapsedMs.ToString();
Then, I created another method using EPPlus approach:
private void NewExport(string name, System.Data.DataTable dt)
{
//DataSet ds = (DataSet)Session["DSIsoReport"];
var watch = System.Diagnostics.Stopwatch.StartNew();
using (pck = new ExcelPackage())
{
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Demo");
ws.Cells["A5"].LoadFromDataTable(dt, true);
ws.DefaultColWidth = 25;
int totalRow = ws.Dimension.End.Row;
int totalCol = ws.Dimension.End.Column;
var startCell = (ExcelRangeBase)ws.Cells["A5"];
var endCell = startCell.Offset(0,0,1,totalCol);
var headerCell = ws.Cells[endCell.ToString()];
headerCell.Style.Fill.PatternType = ExcelFillStyle.Solid;
headerCell.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.BurlyWood);
var headerFont = headerCell.Style.Font;
headerFont.Bold = true;
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
ws.Cells["A4"].LoadFromText(name + " Generation Time: " + elapsedMs.ToString());
}
}
I have a REnder method that actually is responsible for generating excel spreadsheet out of the aspx page:
protected override void Render(System.Web.UI.HtmlTextWriter writer)
{
Response.AddHeader("content-disposition", "inline;filename=" + ReportName + ".xls");
Response.ContentType = "application/vnd.ms-excel";
//Response.BinaryWrite(pck.GetAsByteArray());
base.Render(writer);
}
When running the application and generating the report with old way with looping, elapsed time is 355
But when using the EPPlus, elapsed time is 1676.
Looks like EPPlus is taking much longer time to execute.
From what I researched I thought EPPlus is efficient.
Is there any way to improve the code?
I'm using the below code to export the gridview to excel. When I export the contents are appearing fine with no problems, but I am getting a control label like System.WebControls.UI.Style this in my first cell in A1 cell.
Is there a way to hide this or remove and below is my code.
CS:
protected void Unnamed1_Click(object sender, ImageClickEventArgs e)
{
// ExportToExcel();
if (ViewState["DashboardDetails"] != null)
{
lblError.Text = string.Empty;
lblError.Style.Add("display", "None");
grdHorizontalSeatDashboard.AllowPaging = false;
DataTable dtHorizontalDashboard = (DataTable)ViewState["DashboardDetails"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=HorizontalDashboard.xls");
Response.Charset = "utf-8";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdHorizontalSeatDashboard.AllowPaging = false;
grdHorizontalSeatDashboard.DataSource = (DataTable)ViewState["DashboardDetails"];
grdHorizontalSeatDashboard.DataBind();
grdHorizontalSeatDashboard.HeaderRow.BackColor = Color.White;
//Horizontal Cell
TableCell cell0 = grdHorizontalSeatDashboard.HeaderRow.Cells[0];
cell0.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell0.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[0].Width;
TableCell cell1 = grdHorizontalSeatDashboard.HeaderRow.Cells[1];
cell1.BackColor = ColorTranslator.FromHtml("#96B060");
cell1.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[1].Width;
TableCell cell2 = grdHorizontalSeatDashboard.HeaderRow.Cells[2];
cell2.BackColor = ColorTranslator.FromHtml("#96B060");
cell2.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[2].Width;
TableCell cell3 = grdHorizontalSeatDashboard.HeaderRow.Cells[3];
cell3.BackColor = ColorTranslator.FromHtml("#96B060");
cell3.Width = Unit.Pixel(100);
TableCell cell4 = grdHorizontalSeatDashboard.HeaderRow.Cells[4];
cell4.BackColor = ColorTranslator.FromHtml("#C57838");
cell4.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[4].Width;
TableCell cell5 = grdHorizontalSeatDashboard.HeaderRow.Cells[5];
cell5.BackColor = ColorTranslator.FromHtml("#C57838");
cell5.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[5].Width;
TableCell cell6 = grdHorizontalSeatDashboard.HeaderRow.Cells[6];
cell6.BackColor = ColorTranslator.FromHtml("#C57838");
cell6.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[6].Width;
// Likely $ Impact & Overall Horizontal Utilization
TableCell cell10 = grdHorizontalSeatDashboard.HeaderRow.Cells[10];
cell10.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell10.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[10].Width;
TableCell cell11 = grdHorizontalSeatDashboard.HeaderRow.Cells[11];
cell11.BackColor = ColorTranslator.FromHtml("#9AD6EE");
cell11.Width = grdHorizontalSeatDashboard.HeaderRow.Cells[11].Width;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
}
foreach (TableCell cell in grdHorizontalSeatDashboard.FooterRow.Cells)
{
cell.BackColor = grdHorizontalSeatDashboard.FooterRow.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
}
Style style = new Style();
style.BackColor = Color.White;
Response.Write(style);
grdHorizontalSeatDashboard.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
}
To hide the first column or the first row (A1), just count the current row/column iteration and intercept the first and hide the A1 cell.
var rowCounter = 0;
var cellCounter = 0;
foreach (GridViewRow row in grdHorizontalSeatDashboard.Rows)
{
foreach (TableCell cell in row.Cells)
{
if (rowCounter == 0 && cellCounter == 0)
{
cell.Text = "";
}
cell.BackColor = row.BackColor;
cell.HorizontalAlign = HorizontalAlign.Center;
cell.CssClass = "textmode";
}
cellCounter = 0;
rowCounter++;
}
Im having trouble executing codes after Response.End().
Im using this to export a datatable/ASP Table to MS Excel(.xls).
The export finishes but my Gridview is not loading anymore. The command that I use to load the gridview is written after Response.End().
I tried using HttpContext.Current.ApplicationInstance.CompleteRequest(); but it did not help.
I tried also Response.Redirect("Charges_Trs.aspx", false); still did not work..
Any help please..Here is my code
lblNotif.Text = "Selected items have been posted. Exporting XLS ... (will be saved in your desktop)";
exportToExcel(dt); //calls the function to export the datatable to excel, i passed dt=datatable to this function
timerNotif.Enabled = true;
btnSearch_Click(null, null); //called the event of a button that loads the gridview
here is the function exporttoexcel()
public void exportToExcel(DataTable dt)
{
Table dTable = new Table();
TableRow dTableRow = new TableRow();
//Column Headings
for (int i = 0; i < dt.Columns.Count; i++)
{
TableCell tCell = new TableCell();
tCell.Text = dt.Columns[i].ToString();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
//Rows
for (int i = 0; i < dt.Rows.Count; i++)
{
dTableRow = new TableRow();
for (int j = 0; j < dt.Columns.Count; j++)
{
TableCell tCell = new TableCell();
dTableRow.Cells.Add(tCell);
}
dTable.Rows.Add(dTableRow);
}
if (Response.IsClientConnected)
{
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PostedCharges" + DateTime.Now.ToString("MMddyyyy") + ".xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
dTable.RenderControl(hw);
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
can u try adding the code in the btnSearch click event(hope it is to bind the grid with some data ) after calling export, instead of calling that click event.
Here i am exporting the datatables in a dataset to excel.How to make the header font of the datatable alone look bold.Here is my code
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName + "");
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
DataGrid dataExportExcel = new DataGrid();
foreach (DataTable table in dtInputParameters.Tables)
{
dataExportExcel.DataSource = table;
dataExportExcel.DataBind();
dataExportExcel.RenderControl(htmlWrite);
htmlWrite.WriteLine("<br/>");
// htmlWrite.AddStyleAttribute(System.Web.UI.HtmlTextWriterStyle.FontWeight, "bold");
}
StringBuilder sbResponseString = new StringBuilder();
sbResponseString.Append("<html xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\" xmlns=\"http://www.w3.org/TR/REC-html40\"> <head><meta http-equiv=\"Content-Type\" content=\"text/html;charset=windows-1252\"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>" + worksheetName + "</x:Name><x:WorksheetOptions><x:Panes></x:Panes></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head> <body>");
sbResponseString.Append(stringWriter + "<table width='800' height='100' align='center' style='text-align:center'");
sbResponseString.Append("</table></body></html>");
HttpContext.Current.Response.Write(sbResponseString.ToString());
HttpContext.Current.Response.End();
Any suggestion?
You need to set the HeaderStyle on the DataGrid to use bold font. That's all.
dataExportExcel.HeaderStyle.Font.Bold=true;
Cursor.Current = Cursors.WaitCursor;
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.FileName = "Total Expiry Inventories Data ";
sfd.DefaultExt = "xls";
sfd.Filter = "xlsx files(*.xlsx)|*.xlsx";
if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
Excel.Application ExcelApp = new Excel.Application();
Excel.Workbook workbook = ExcelApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
Excel.Worksheet worksheet1 = (Excel.Worksheet)workbook.Worksheets[1];
worksheet1.Name = "Expiry Data";
for (int i = 1; i < GrdViewData.Columns.Count + 1; i++)
{
worksheet1.Cells[1, i] = GrdViewData.Columns[i - 1].HeaderText;
worksheet1.Cells[1, i].Font.Bold = true;
}
for (int i = 0; i < GrdViewData.Rows.Count; i++)
{
for (int j = 0; j < GrdViewData.Columns.Count; j++)
{
worksheet1.Cells[i + 2, j + 1] = GrdViewData.Rows[i].Cells[j].Value.ToString();
}
}
worksheet1.Rows.Font.Size = 12;
// Excel.Range range_Consolidated = worksheet1.Rows.get_Range("a1", "d1");
// range_Consolidated.Font.Bold = true;
// range_Consolidated.Font.Italic = true;
string ExcelFileName = sfd.FileName;
workbook.SaveAs(ExcelFileName);
workbook.Close(false, ExcelFileName, Missing.Value);
ExcelApp.Quit();
ExcelApp = null;
GC.Collect();
GC.WaitForPendingFinalizers();
MessageBox.Show("File Saved! you can open it from\n '" + sfd.FileName + "'", "EXPORT", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
}