work on asp.net vs05.when i export gridview to excel than i get the below error
RegisterForEventValidation can only be called during Render();
why i get this error .How to solve it?
public void ToExcel()
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
}
//-- added to handle special characters in excel
Response.ContentEncoding = Encoding.Unicode;
Response.BinaryWrite(Encoding.Unicode.GetPreamble());
gvSearch.EnableViewState = false;
//-- added to handle special characters in excel
Add these lines and see if it helps.
StringWriter stw = new StringWriter();
HtmlTextWriter htextw = new HtmlTextWriter(stw);
gvSearch.RenderControl(htextw);
Response.Write(stw.ToString());
Response.End();
}
It's a shot in the dark.
in aspx page, Change the following to false : AllowPaging="False" AllowSorting="False" and remove Pagesize="10".
This Code Help to solve export Gridview to excel related problem
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["Excel Sheet Name"];
worksheet = workbook.ActiveSheet;
worksheet.Name = "Exported from gridview";
for (int i = 1; i < Gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = Gridview.Columns[i - 1].HeaderText;
}
for (int i = 0; i < Gridview.Rows.Count; i++)
{
for (int j = 0; j < Gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] =
Gridview.Rows[i].Cells[j].Value.ToString();
}
}
Related
I have this code to export my GridViews to Excel, it works in localhost but after deploying it does not work. The error I received upon clicking my export button is Runtime Error.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
String DATA1 = "DATA1";
String DATA2 = "DATA2";
ExportToExcel(app, workbook, DATA_1, DATA1);
workbook.Worksheets["Sheet1"].Delete();
workbook.Worksheets["Sheet2"].Delete();
workbook.Worksheets["Sheet3"].Delete();
ExportToExcel(app, workbook, DATA_2, DATA2);
string FolderPath = ServerName + DirectoryLocation + DirectoryFolder + ExportsFolder;
var filename = #"EXCEL_" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx";
workbook.SaveAs(FolderPath + filename, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close();
app.Quit();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=" + filename + ";");
Response.TransmitFile(FolderPath + filename);
Response.Flush();
Response.End();
}
public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook, GridView gridview, string SheetName)
{
// see the excel sheet behind the program
app.Visible = false;
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets.Add();
// changing the name of active sheet
worksheet.Name = SheetName;
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Text.ToString();
}
}
}
I solved my question using EPPLUS, EPPlus is a .net library that reads and writes Excel 2007/2010 files using the Open Office Xml format (xlsx). It does not require excel to be installed on the server machines. thanks.
The codes below is an reference:
protected void ExportToExcel_Click(object sender, EventArgs e)
{
var products = GetProducts();
GridView1.DataSource = products;
GridView1.DataBind();
ExcelPackage excel = new ExcelPackage();
var workSheet = excel.Workbook.Worksheets.Add("Products");
var totalCols = GridView1.Rows[0].Cells.Count;
var totalRows = GridView1.Rows.Count;
var headerRow = GridView1.HeaderRow;
for (var i = 1; i <= totalCols; i++ )
{
workSheet.Cells[1, i].Value = headerRow.Cells[i - 1].Text;
}
for (var j = 1; j <= totalRows; j++ )
{
for (var i = 1; i <= totalCols; i++)
{
var product = products.ElementAt(j-1);
workSheet.Cells[j + 1, i].Value = product.GetType().GetProperty(headerRow.Cells[i - 1].Text).GetValue(product, null);
}
}
using (var memoryStream = new MemoryStream())
{
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=products.xlsx");
excel.SaveAs(memoryStream);
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
'Microsoft.Office.Interop.Excel' means that Microsoft Office Runtime must be installed to make this code work.
Exporting data using Microsoft.Office.Interop.Excel is avoided, since it needs application installation on server, is poorly scalable, and is against MS Office licence conditions.
I suggest other ways, like text-csv exporting that will meet better performance on a server.
protected void EXPORT_BUTTON_Click(object sender, EventArgs e)
{
...
StringBuilder sb = new StringBuilder();
// storing header part in Excel
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
sb.Append (gridview.Columns[i - 1].HeaderText);
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
// storing Each row and column value to excel sheet
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
sb.Append (gridview.Rows[i].Cells[j].Text.ToString());
stringBuilder.Append(",");
}
sb.Append(Environment.NewLine);
}
WriteToCSV(sb.ToString();
}
public static void WriteToCSV(string text, string fileName)
{
string attachment = "attachment; filename="+fileName+DateTime.Now.ToString("yy-MM-dd")+".csv";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "text/csv;charset=utf8";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.Write('\uFEFF'); //this is BOM
HttpContext.Current.Response.Write(text);
HttpContext.Current.Response.End();
}
The reason it is failing is you don't have Excel installed. There are other options here (such as converting to CSV file), but if you want to use your code as is, the simplest way is to probably just install Excel on the server !
I am using asp.net C#, currently doing export excel file. I wish to export in .xlsx. everything seems fine until I open it. The code below is my code for export.
DataTable dt = GetData(sqlcommand);
if(dt.Rows.Count >0){
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=InventoryReport.xlsx");
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].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();
The image below is the error I got after open the .xlsx file.
I hope someone could help on my work. Thanks!! really appreciate if yo could help me on this.. much appreciate!
use my code
using OfficeOpenXml;
using System.Data;
namespace Managed_Leverage_BAL
{
public static class ExcelExportHelper
{
public static void CreateExcelFromDataSet(this DataSet dsReportData, string strFileNameWithPath, int[] DateFormatColumnNumbers = null)
{
if (File.Exists(strFileNameWithPath)) File.Delete(strFileNameWithPath);
FileInfo newFile = new FileInfo(strFileNameWithPath);
using (ExcelPackage pck = new ExcelPackage(newFile))
{
for (int tableIndex = 0; tableIndex < dsReportData.Tables.Count; tableIndex++)
{
DataTable tbl;
tbl = dsReportData.Tables[tableIndex];
ExcelWorksheet ws = pck.Workbook.Worksheets.Add(dsReportData.Tables[tableIndex].TableName);
ws.Cells["A1"].LoadFromDataTable(tbl, true);
if (tableIndex == 0)
for (int i = 0; i < DateFormatColumnNumbers.Count(); i++)
{
using (ExcelRange col = ws.Cells[DateFormatColumnNumbers[i], 1, DateFormatColumnNumbers[i] + tbl.Rows.Count, 1])
{
col.Style.Numberformat.Format = "dd-MMM-yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
}
string endHeader = "A";
for (int i = 0; i < tbl.Columns.Count - 1; i++)
{
endHeader = IncrementAlphabeticCounter(endHeader);
}
using (ExcelRange rng = ws.Cells["A1:" + endHeader + "1"])
{
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);
}
}
pck.Save();
}
}
public static char[] CheckZ(char[] cCounter, int iPos)
{
if (iPos >= 0)
{
if (cCounter[iPos] >= 'Z')
{
cCounter[iPos] = 'A';
if (iPos == 0)
{
char[] array = new char[cCounter.Length + 1];
cCounter.CopyTo(array, 1);
cCounter = array;
cCounter[0] = 'A';
return cCounter;
}
cCounter = CheckZ(cCounter, iPos - 1);
return cCounter;
}
cCounter[iPos] = (char)(cCounter[iPos] + '\x0001');
}
return cCounter;
}
public static string IncrementAlphabeticCounter(string sCounter)
{
if (sCounter == "")
{
return sCounter;
}
char[] cCounter = sCounter.ToCharArray();
return new string(CheckZ(cCounter, cCounter.Length - 1));
}
}
in page
private void Download(DataSet ds)
{
String strPath = Server.MapPath("~/Docs/") + "your path";
ds.CreateExcelFromDataSet(strPath);
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=your file name.xlsx");
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.TransmitFile(strPath);
Response.Flush();
Response.End();
}
you will need epplus dll,get it here
http://download-codeplex.sec.s-msft.com/Download/Release?ProjectName=epplus&DownloadId=813458&FileTime=130743526623500000&Build=21028
I am trying to export data in a Gridview to Excel and store that file in a folder on server.
I have done this part. The only thing I want to do is,
I want to prevent downloading the Excel file.
Please find my code below.
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "order.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();
Thanks in advance.
Use this code by editing as per your need :
private void webBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e)
{
e.Cancel = true;
WebClient client = new WebClient();
client.DownloadDataCompleted += new DownloadDataCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadDataAsync(e.Url);
}
void client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
string filepath = textBox1.Text;
File.WriteAllBytes(filepath, e.Result);
MessageBox.Show("File downloaded");
}
Hope this will help you.
I got the answer.
Code
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gridX.AllowPaging = false;
bindX();
gridX.HeaderRow.Style.Add("background-color", "#FFFFFF");
for (int i = 0; i < gridX.HeaderRow.Cells.Count; i++)
{
gridX.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gridX.RenderControl(htw);
//Response.Write(sw.ToString());
string renderedGridView = sw.ToString();
string path = Server.MapPath("~/Order/od/x");
System.IO.File.WriteAllText(path + "/order" + lblF.Text + ".xls", renderedGridView);
sw.Close();
htw.Close();
Please provide me a dll or a way to convert Sql stored procedure output(Contains huge records nearly 10lakhs) into a CSV file in asp.net windows service.Thanks in advance
protected void btnExportCSV_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridView1.AllowPaging = false;
GridView1.DataBind();
StringBuilder sb = new StringBuilder();
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Columns[k].HeaderText + ',');
}
//append new line
sb.Append("\r\n");
for (int i = 0; i < GridView1.Rows.Count; i++)
{
for (int k = 0; k < GridView1.Columns.Count; k++)
{
//add separator
sb.Append(GridView1.Rows[i].Cells[k].Text + ',');
}
//append new line
sb.Append("\r\n");
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
Refer the above code
kindly see the below link
http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I am exporting gridview data to excel but that excel file add the some lable text and textbox values and format also taken , pls give how to design the excel code in asp.net. I am writing like this
All gridview data taken dataset ds
-pls give me textbox values and some label or normal text designed code in excel
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = ds;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition",
"attachment;filename=DataTable.xls");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
////Apply text style to each Row
GridView1.Rows[i].Cells[4].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:'\#,\#\#0\.00';}
.textmode1(mso-number-format:'\#';}
.SSNmode{mso-number-format:'000-00-000';} </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
Take a look at this awesome tool: http://www.carlosag.net/Tools/ExcelXmlWriter/
Futhermore, the author also created a code generator, which generates .net code from a provided excel sheet(formatting, layout and so on)
http://www.carlosag.net/Tools/ExcelXmlWriter/Generator.aspx
Here's some code that generates an excel file from a datatable (converted vb code, as pr. request by poster)
CarlosAg.ExcelXmlWriter.Workbook book = new CarlosAg.ExcelXmlWriter.Workbook();
book.ExcelWorkbook.ProtectWindows = false;
book.ExcelWorkbook.ProtectStructure = false;
var styles = book.Styles;
WorksheetStyle defaultStyle = styles.Add("Default");
var defStyles = defaultStyle;
defStyles.Name = "Normal";
defStyles.Font.FontName = "Calibri";
defStyles.Font.Size = 11;
defStyles.Font.Color = "#000000";
defStyles.Alignment.Vertical = StyleVerticalAlignment.Bottom;
Worksheet sheet = book.Worksheets.Add("Sheet1");
sheet.Table.DefaultRowHeight = 15f;
sheet.Table.FullColumns = 1;
sheet.Table.FullRows = 1;
DataTable dt = new DataTable(); //= your datatable
//Header
WorksheetRow HeaderRow = sheet.Table.Rows.Add();
foreach (DataColumn col in dt.Columns)
{
HeaderRow.Cells.Add(col.ColumnName.ToString());
}
//Body
foreach (DataRow dr in dt.Rows)
{
WorksheetRow row = sheet.Table.Rows.Add();
foreach (DataColumn cols in dt.Columns)
{
row.Cells.Add(dr[cols.ColumnName.ToString()].ToString());
}
}
sheet.Options.Selected = true;
sheet.Options.ProtectObjects = false;
sheet.Options.ProtectScenarios = false;
book.Save("path to file");