Export to Excel function working in localhost but not in published website - asp.net

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 !

Related

export excel cannot be open .xlsx

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

Sql server Procedure Output convert to CSV File in asp.net

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

How to download excel file to a specific folder in asp.net

I need to download the excel to the specific folder
Example : D:\email
Now i was able to download the excel file in downloads ....but i need to download in D:\email
this is my code to create excel file :
protected void UploadDataTableToExcel(DataTable dtRecords)
{
string XlsPath = Server.MapPath(#"~/Add_data/test.xls");
string attachment = string.Empty;
if (XlsPath.IndexOf("\\") != -1)
{
string[] strFileName = XlsPath.Split(new char[] { '\\' });
attachment = "attachment; filename=" + strFileName[strFileName.Length - 1];
}
else
attachment = "attachment; filename=" + XlsPath;
try
{
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
string tab = string.Empty;
foreach (DataColumn datacol in dtRecords.Columns)
{
Response.Write(tab + datacol.ColumnName);
tab = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dtRecords.Rows)
{
tab = "";
for (int j = 0; j < dtRecords.Columns.Count; j++)
{
Response.Write(tab + Convert.ToString(dr[j]));
tab = "\t";
}
Response.Write("\n");
}
Response.End();
}
catch (Exception ex)
{
//Response.Write(ex.Message);
}
}
you can manually move the file after download using
string sourceFile = #"C:\Users\test\Documents\Downloads\test.xls";
string destinationFile = #"D:\emails\test.xls";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);

Show SaveAs dialogbox for downloading CSV File

My CSV Code is:--
public void CreateCSVFile(DataTable dt, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
for (int i = 0; i < iColCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
// Now write all the rows.
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string email = dr[i].ToString();
bool result = IsEmail(email);
if (result == true)
sw.Write(dr[i].ToString());
}
//if (i < iColCount - 1)
//{
// sw.Write(" , ");
//}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
and on grid_RowCommand() doing this...
if (e.CommandName == "cmdCSV")
{
DataTable dtCSV = new DataTable();
dtCSV = ob.TotalRecord(TableField, TableName);
CreateCSVFile(dtCSV, "c:\\csv file/csv "+TableName+".csv");
lblMsg.Visible = true;
lblMsg.Text = "CSV File Successfully created in C.";
lblMsg.ForeColor = Color.Green;
}
Here CreateCSVFile(dtCSV, "c:\\csv file/csv "+TableName+".csv"); Download CSV File bydefault in c.Here i want to download CSV file in that location where i want to save.How can i do this??Please guide me.
Thanks in advance
Try This
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=XYZ.csv");
string newpath2 = System.Web.HttpContext.Current.Server.MapPath("~//downloadfile//XYZ.csv");
FileStream sourceFile = new FileStream(newpath2, FileMode.Open);
long FileSize;
FileSize = sourceFile.Length;
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
OR
string filePath = Server.MapPath("~/files/myFileName.csv");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=\\\"{0}\\\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();

gridview to excel

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();
}
}

Resources