Show SaveAs dialogbox for downloading CSV File - asp.net

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

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

Export to CSV Website asp

I have a GridView and when I click Export Button to export my data into CSV. I click the button and it takes all the data correctly but it doesn't show anything, no popup to ask me to open or to save .
Here is my code
protected void btnExport_Click(object sender, EventArgs e)
{
ExportCSV();
}
protected void ExportCSV()
{
GridViewSW.DataSource = ViewState["source"];
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Orders.csv");
Response.Charset = "";
Response.ContentType = "application/text";
GridViewSW.AllowPaging = false;
GridViewSW.DataBind();
StringBuilder columnbind = new StringBuilder();
for (int k = 0; k < GridViewSW.Columns.Count; k++)
{
columnbind.Append(GridViewSW.Columns[k].HeaderText + ",");
}
columnbind.Append("\r\n");
for (int i = 0; i < GridViewSW.Rows.Count; i++)
{
for (int j = 0; j < GridViewSW.Columns.Count; j++)
{
columnbind.Append(GridViewSW.Rows[i].Cells[j].Text + ",");
}
columnbind.Append("\r\n");
}
Response.Output.Write(columnbind.ToString());
Response.Flush();
Response.End();
}
NEW EDIT
I changed the code a little bit. Now i have the csv file and he has all the data in, but when I click the button it doesn't show any dialog box with open or save.
string fullSavePath = HttpContext.Current.Server.MapPath(string.Format("~/csv/Orders.csv"));
StreamWriter sr = new StreamWriter(fullSavePath);
DataSet ds = (DataSet)ViewState["source"];
MyDateTime date = new MyDateTime();
DataTableReader dr = ds.Tables[0].CreateDataReader();
while (dr.Read())
{
sr.Write(dr.GetValue(0) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(2))) + "," + date.ConvertToDate(Convert.ToInt64(dr.GetValue(3))) + "," + dr.GetValue(4) + "\r\n");
}
sr.Flush();
sr.Close();
sr.Dispose();
System.IO.FileInfo file = new System.IO.FileInfo(fullSavePath);
System.Web.HttpContext context = System.Web.HttpContext.Current;
System.Web.HttpResponse response = context.Response;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename =" + "Orders.csv"));
// Response.TransmitFile(fullSavePath);
Response.WriteFile(file.FullName);
// Response.Flush();
context.ApplicationInstance.CompleteRequest();
// Response.End();
// Response.Close();
I believe you need to change your content type to "text/csv"
Response.ContentType = "text/csv";

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

Resources