export excel cannot be open .xlsx - asp.net

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

Related

bulk data export to excel and download in ashx file

I have an asp.net application in which I have a js file and an ashx file. Here in a download button click Im calling handler file in ajax call and retrieving sql table data in a json formatted string/data table and Im trying to export json formated string/data table to excel/csv file and download it. Please help me to find a solution. (Need a solution which help to export large amount of data and download)
I tried the below code but its not downloading excel file.
public void ProcessRequest(HttpContext context)
{
context.Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
context.Response.ContentType = "application/csv";
HttpResponse response = context.Response;
string exportContent = ExportToSpreadsheet(JsonStringToDataTable(GetDataFromTable()),'excelfilename');
response.Write(exportContent);
context.Response.End();
}
public DataTable JsonStringToDataTable(string jsonString)
{
DataTable dt = new DataTable();
string[] jsonStringArray = Regex.Split(jsonString.Replace("[", "").Replace("]", ""), "},{");
List<string> ColumnsName = new List<string>();
foreach (string jSA in jsonStringArray)
{
string[] jsonStringData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
foreach (string ColumnsNameData in jsonStringData)
{
try
{
int idx = ColumnsNameData.IndexOf(":");
string ColumnsNameString = ColumnsNameData.Substring(0, idx - 1).Replace("\"", "");
if (!ColumnsName.Contains(ColumnsNameString))
{
ColumnsName.Add(ColumnsNameString);
}
}
catch (Exception ex)
{
//throw new Exception(string.Format(ex.Message + "Error Parsing Column Name : {0}", ColumnsNameData));
throw ex;
}
}
break;
}
foreach (string AddColumnName in ColumnsName)
{
dt.Columns.Add(AddColumnName);
}
foreach (string jSA in jsonStringArray)
{
string[] RowData = Regex.Split(jSA.Replace("{", "").Replace("}", ""), ",");
DataRow nr = dt.NewRow();
foreach (string rowData in RowData)
{
try
{
int idx = rowData.IndexOf(":");
string RowColumns = rowData.Substring(0, idx - 1).Replace("\"", "");
string RowDataString = rowData.Substring(idx + 1).Replace("\"", "");
nr[RowColumns] = RowDataString;
}
catch (Exception ex)
{
continue;
}
}
dt.Rows.Add(nr);
}
return dt;
}
private static string GetDataFromTable()
{
string returnValue = string.Empty;
var serializer = new JavaScriptSerializer { MaxJsonLength = Int32.MaxValue };
try
{
var result = //get data from sql table;
returnValue = serializer.Serialize(result);
}
catch (Exception e)
{
returnValue = serializer.Serialize(e.Message);
}
return returnValue;
}
public string ExportToSpreadsheet(DataTable table, string name)
{
string res = string.Empty;
try
{
//var resp = Response;
System.Web.HttpResponse resp = System.Web.HttpContext.Current.Response;
resp.Clear();
if (table != null)
{
foreach (DataColumn column in table.Columns)
{
resp.Write(column.ColumnName + ",");
}
}
resp.Write(Environment.NewLine);
if (table != null)
{
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
resp.Write(row[i].ToString().Replace(",", string.Empty) + ",");
}
resp.Write(Environment.NewLine);
}
}
res = "successfully downloaded";
resp.ContentType = "text/csv";
resp.AppendHeader("Content-Disposition", "attachment; filename=" + name + ".csv");
// resp.End();
}
catch(Exception ex)
{
res = ex.Message;
}
return res;
}
Start using a specialized libary like EPPlus. It will create real Excel files.
private void exportToExcel(DataTable dataTable)
{
using (ExcelPackage excelPackage = new ExcelPackage())
{
//create the worksheet
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add("Sheet 1");
//load the datatable into the sheet, with headers
worksheet.Cells["A1"].LoadFromDataTable(dataTable, true);
//send the file to the browser
byte[] bin = excelPackage.GetAsByteArray();
Response.ClearHeaders();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-length", bin.Length.ToString());
Response.AddHeader("content-disposition", "attachment; filename=\"ExcelDemo.xlsx\"");
Response.OutputStream.Write(bin, 0, bin.Length);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}

how to export sql table to excel without loss your formatting?

I want export sql table to excel file.
my Code:
public void ExportToExcel(string strQuery)
{
//Get the data from database into datatable
OleDbCommand cmd = new OleDbCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.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].Attributes.Add("class", "textmode");
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = #"<style> .textmode { mso-number-format:\#; } </style>";
HttpContext.Current.Response.Write(style);
HttpContext.Current.Response.Output.Write(sw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
and In Button of aspx page:
protected void ExportToExcel(object sender, EventArgs e)
{
ExportClass Exc = new ExportClass();
string wherestr = null;
if ((StartTBX.Text.Length > 0) && (EndTBX.Text.Length > 0)) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And (CreateDate >='{0}' And CreateDate <='{1}')", StartTBX.Text, EndTBX.Text); }
else if (StartTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate >='{0}'", StartTBX.Text); }
else if (EndTBX.Text.Length > 0) { wherestr = String.Format("((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin') And CreateDate <='{0}'", EndTBX.Text); }
else { wherestr = "((STATUS = 'User' And PostStatus='Default') or STATUS = 'Admin')"; }
Exc.ExportToExcel("SELECT Users.UserID, UserName, Status, LockUser, FName + ' ' + Lname as [نام کامل] FROM Users inner join UsersInfo on Users.UserID=UsersInfo.UserID WHERE " + wherestr + " ORDER BY CreateDate DESC");
}
When I do not use date filtering in code(last else in code), every thing is fine but when i use date filtering, the content of [نام کامل] format is lost. content of [نام کامل] is Non-English words.
without date filter:
with date filter:
Please help me. Thank a lot.
well, my problem resolve with this code:
HttpContext.Current.Response.ContentEncoding = Encoding.Unicode;
HttpContext.Current.Response.BinaryWrite(Encoding.Unicode.GetPreamble());
best regards.

Export to Excel function working in localhost but not in published website

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 !

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