Asp.net gridview export to excel formatting issue - c#

I have created a simple application while will export data into excel. Now the data is exported to excel successfully but it will show an exception of formatting when I opened the downloaded excel.
public ActionResult ExportOrder()
{
List<OrderItem> data = new List<OrderItem>();
GridView gv = new GridView();
gv.DataSource = data;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=" + Common.GenerateSerialNo() + ".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 RedirectToAction("OrderProducts");
}
This is my formatting issue while opening in Excel.
Format Issue Image
Please suggest me to solve this issue.
I tried but found solutions to use NPOI or other Paid Tools. Can we solve the formatting issue without using any third party tool. I also tried some solutions but it didn't work for me.

You need to set the style on data bound not when doing the export as follows
private void gvPrint_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow) {
e.Row.Cells(0).Attributes.Add("class", "text");
e.Row.Cells(1).Attributes.Add("class", "text");
e.Row.Cells(2).Attributes.Add("class", "text");
e.Row.Cells(6).Attributes.Add("class", "text");
e.Row.Cells(7).Attributes.Add("class", "text");
e.Row.Cells(8).Attributes.Add("class", "text");
}
}

Related

How can I add a new row on top of excel sheet while exporting GridView rows to Excel?

I have a button which helps me export a Gridview to an excel file. Now along with exporting the GridView, I also want the button to add an
empty row on top of the excel file such that the Gridview only starts from the 2nd row. How can I do that? Any help will be greatly appreciated!
So far, I have this snippet which helps me export my Gridview perfectly.
protected void btnOk_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.AppendHeader("content-disposition", "attachment;
filename=Test.xls");
Response.ContentType = "application/excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htw);
Response.Write(stringWriter.ToString());
Response.End();
}

how to export excel without EnableEventValidation="false" because of lock issues in excel

I have a code for exporting excel on button click:
protected void btn_Excel_Click(object sender, EventArgs e)
{
try {
empData1.ShowHeader = true;
bindGrid();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=doc_name.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
foreach (TableCell cell in empData1.HeaderRow.Cells)
{
cell.ForeColor = System.Drawing.ColorTranslator.FromHtml("#fafafa");
cell.BackColor = System.Drawing.ColorTranslator.FromHtml("#ff5d51");
}
empData1.RenderControl(hw);
string style = #"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
catch(Exception exp)
{
string st = exp.Message;
}
}
I was getting error:
RegisterForEventValidation can only be called during Render();
and what i did is:
enableEventValidation="false" on the page_name.aspx page
The export to excel worked fine after this on windows 7.
The issue came on windows 8, when i downloaded the excel on a windows 8 system's browser, though the file did downloaded completely, but on opening the file, it showed up with a error message that the file is corrupted, and i suppose it is because of disabling event validation.
when i checked the properties of that file, then it was locked up due to security reasons. I unlocked it from there, and i could open up the file then.
so is there any way to tackle the error
RegisterForEventValidation can only be called during Render();
without enableEventValidation="false" or tell me if i am missing something.

Export only Gridview Data to Excel format in Asp.net C#

In my page I have two textbox controls, where I am gating the date from the Calendar Extender & in the export to excel Button I am going to export the Gridview data to excel sheet.
When I am gating the excel sheet its show the the textbox & button also from which i am export the excel Sheet.
I have written the export code in the Export Button.
Like:-
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
try
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
Grd_MidData.AllowPaging = false;
bindgriddata();
//Change the Header Row back to white color
Grd_MidData.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < Grd_MidData.HeaderRow.Cells.Count; i++)
{
Grd_MidData.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
Grd_MidData.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
}
catch (Exception ee)
{
}
}
When I am gating the excel sheet it shows the gridview data along with the two text box & the button from where I am doing the filtering.
So any one suggest me, How to show only the gridview data but not show the Textbox & button on the excel sheet.
You have to bind the data to your excel code,
using below code
bindgriddata();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
Grd_MidData.RenderControl(ht);
Response.Write(sw.ToString());
Response.End();
it is working for me.
Here the gridview data is showing along with the From date: To Date: textbox & the button also. So how can i remove these field from the sheet.
you can use close xml to generate excel it will give more functionlity to create excel and formatting.
protected void Export_to_Excel_Click(object sender, EventArgs e)
{
bindgriddata();
Grd_MidData.DataSource = objDS; // Dataset
Grd_MidData.DataBind();
using (XLWorkbook wb = new XLWorkbook())
{
try
{
//creating worksheet
var ws = wb.Worksheets.Add("Report");
//adding columms header
int columnscount = objDS.Tables[0].Columns.Count;
char a = 'A';
for (int j = 1; j <= columnscount; j++)
{
string str = a + "1";
ws.Cell(str).Value = objDS.Tables[0].Columns[j - 1].ColumnName.ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
a++;
}
ws.Columns().AdjustToContents();
//formatting columns header
var rngheaders = ws.Range("A1:J1");
rngheaders.FirstRow().Style
.Font.SetBold()
.Font.SetFontSize(12)
.Font.SetFontColor(XLColor.Black)
.Fill.SetBackgroundColor(XLColor.DeepSkyBlue)
.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Center)
.Border.OutsideBorder = XLBorderStyleValues.Thin;
////adding data to excel
int k = 2;
foreach (DataRow row in objDS.Tables[0].Rows)
{
char b = 'A';
string str = b + "" + k;
for (int i = 0; i < objDS.Tables[0].Columns.Count; i++)
{
ws.Cell(str).Value = row[i].ToString();
ws.Cell(str).Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
ws.Cell(str).Style.Alignment.SetHorizontal(XLAlignmentHorizontalValues.Left);
b++;
str = b + "" + k;
}
k++;
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Customer.xlsx");
}
catch { }
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
I had the same issue when exporting a GridView. I added a try/catch and exported the message to Excel and then realized that it was generating an error. I solved it thanks to the following answer: GridView must be placed inside a form tag with runat="server" even after the GridView is within a form tag

Saving an asp.net chart to file

I have a bar chart containing information on various machines relating to company.
Basically i want to output this chart to png file but i cant seem to get it output properly.
Ive been searching Google for hours trying to find a good tutorial but most of them use weird third party components to download the image and i really dont wanna do that.
this is my code at the moment:
string tmpChartName = "/MachinesByCompanyChart.png";
protected void GenerateBarChartBut_click(object sender, EventArgs e)
{
Chart1.Visible = false;
Chart2.Visible = true;
DataTable table = new DataTable();
dal.getTotalAssetsByCompany("table", TAB1CompanyDDL.SelectedItem.Text);
table = dal.Results.Tables["table"];
DataView dv = table.DefaultView;
Chart2.Series["Series1"].Points.DataBindXY(dv, "AssetType", dv, "Total");
Chart2.Palette = ChartColorPalette.None;
Chart2.PaletteCustomColors = myGreenColorPalette;
string imgPath2 = Server.MapPath(tmpChartName);
Chart2.SaveImage(imgPath2, ChartImageFormat.Png);
}
protected void ExportAssetsByCompanyBut_click(object sender, EventArgs e)
{
Response.Clear();
Response.ContentType = Chart1.ImageType.ToString();
Response.AddHeader("Content-Disposition", "attachment; filename=" + tmpChartName);
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
}
Am i passing the saved image to the writer method properly?
try this,
set this two properties of your chart in aspx.page
EnableViewState="true"
ImageStorageMode="UseImageLocation"
write your code on aspx.cs page
System.IO.MemoryStream imagestream = new System.IO.MemoryStream();
Chart1.SaveImage(imagestream, System.Web.UI.DataVisualization.Charting.ChartImageFormat.Png);
byte[] imageByte = imagestream.ToArray();

exporting gridview to Ms Excel 2007

I am trying to export grid view data into excel 2007 i.e. xlsx format. but its giving error.
i am using following code
protected void Button1_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=text.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.DataSource = Presenter.CurrentModel.BillStatementGlModelRecords;
GridView1.DataBind();
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = GridView1.Rows[i];
//Change Color back to white
row.BackColor = System.Drawing.Color.White;
//Apply text style to each Row
row.Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
but not working properly and on opening the file it gives following error
"Excel cannot open the file 'ChangeRequestList[2].xlsx' because the file
format or file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file"
Can anyone help me?
Thanks
Have a look at this Code - I already used it and it's working.
But it produces plain text (csv I guess) and not xlsx but I think that shouldn't be a problem though.

Categories