I want to build ExcelPackage file on server side and than send allow user to download it.
Here is my code for file creating:
private byte[] ExcelFileCreate()
{
using (var excelPackage = new ExcelPackage())
{
excelPackage.Workbook.Properties.Author = User.Identity.Name;
excelPackage.Workbook.Properties.Title = "Skybot";
excelPackage.Workbook.Properties.Company = "Dataminds";
excelPackage.Workbook.Worksheets.Add("Selected unit folder");
var excelWorksheet = excelPackage.Workbook.Worksheets[1];
excelWorksheet.Name = "Selected unit folder";
int rowIndex = 1;
int columnIndex = 1;
do
{
var cell = excelWorksheet.Cells[rowIndex, columnIndex];
var fill = cell.Style.Fill;
fill.PatternType = ExcelFillStyle.Solid;
fill.BackgroundColor.SetColor(Color.LightGray);
columnIndex++;
} while (columnIndex != 4);
excelWorksheet.Cells[1, 1].Value = "action cell";
excelWorksheet.Cells[1, 2].Value = "time cell";
excelWorksheet.Cells[1, 3].Value = "processor cell";
excelWorksheet.Cells[2, 1].Value = "action cell";
excelWorksheet.Cells[2, 2].Value = "time cell";
excelWorksheet.Cells[2, 3].Value = "processor cell";
return excelPackage.GetAsByteArray();
}
}
And send it you user:
variant 1:
private void FileTransfer(byte[] fileBytes)
{
//Clear the response
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.Cookies.Clear();
//Add the header & other information
Response.Cache.SetCacheability(HttpCacheability.Private);
Response.CacheControl = "private";
Response.Charset = System.Text.UTF8Encoding.UTF8.WebName;
Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.AppendHeader("Pragma", "cache");
Response.AppendHeader("Expires", "60");
Response.AppendHeader("Content-Disposition",
"attachment; " +
"filename=\"ExcelReport.xlsx\"; " +
"size=" + fileBytes.Length.ToString() + "; " +
"creation-date=" + DateTime.Now.ToString("R") + "; " +
"modification-date=" + DateTime.Now.ToString("R") + "; " +
"read-date=" + DateTime.Now.ToString("R"));
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
//Write it back to the client
Response.BinaryWrite(fileBytes);
Response.End();
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
}
variant 2:
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("content-disposition", "attachment;filename=test.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
variant 3:
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", fileBytes));
Response.AppendHeader("Content-Length", fileBytes.Length.ToString());
Response.BinaryWrite(fileBytes);
Response.End();
And none of them works.
There is no pop-up window with suggestion to store/open file.
Event handler that should make it works:
protected void TreeViewUnit_OnContextMenuItemClick(object sender,
RadTreeViewContextMenuEventArgs eventArgs)
{
FileTransfer(ExcelFileCreate());
}
Any ideas what is wrong?
Try
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=ExcelReport.xlsx");
Response.BinaryWrite(fileBytes);
Response.End();
It works for me as shown here.
Related
protected void DownloadFile(object sender, EventArgs e)
{
string param = Request.QueryString["id"];
//int id = int.Parse((sender as LinkButton).CommandArgument);
//byte[] bytes;
string fileName;
SqlCommand cd = DbCon._dbConnection.CreateCommand();
cd.CommandType = CommandType.Text;
cd.CommandText = "select id from student_registration where id = '" + param + "'";
cd.ExecuteNonQuery();
SqlCommand cmd = DbCon._dbConnection.CreateCommand();
cmd.CommandText = "select books_pdf from books where id = '" + param + "'";
// cmd.Parameters.AddWithValue("#Id", param);
String s1 = cmd.ExecuteScalar().ToString();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
//bytes = (byte[])sdr["Data"];
//contentType = sdr["ContentType"].ToString();
fileName = sdr["books_pdf"].ToString();
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "/";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = contentType;
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName );
//Response.AppendHeader("Content-Disposition", "attachment; filename=" +fileName);
// Response.TransmitFile(Server.MapPath("~/Files/"+ fileName));
// Response.WriteFile(file.FullName);
Response.Flush();
Response.End();
}
This is the code where I have written to download the file. but the result what am getting correct file but '/' is replaced with 'underscore;
My question is how to remove that underscore and add '/' in place of underscore I have attached the image please check that and please help me in finding the solutionenter image description here
enter image description here
image shows the path stored in database and error what I am facing to download
fileName = "../librarian/" + sdr["books_pdf"].ToString();
}
WebClient req = new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer = true;
response.AddHeader("Content-Disposition", "attachment;filename=\"" + Server.MapPath(fileName) + "\"");
byte[] data = req.DownloadData(Server.MapPath(fileName));
response.BinaryWrite(data);
response.End();
Proper Selection of File was not given later i corrected proper file location than i got proper output
I want to display a pdf file on an .aspx page with a button. The codes is like that:
string yol = e.CommandArgument.ToString();
string path = Server.MapPath("~/Raporlar/2021/" + yol.Trim());
WebClient User = new WebClient();
Byte[] s = User.DownloadData(path);
System.IO.MemoryStream ms = new System.IO.MemoryStream(s);
if (ms != null && ms.Length > 1)
{
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Charset = "UTF-8";
Response.Buffer = true;
Response.AddHeader("Content-Length", ms.Length.ToString());
Response.AddHeader("Content-Disposition", "inline; filename=\"" + yol + "\"");
Response.AddHeader("Expires", "0");
Response.AddHeader("Pragma", "cache");
Response.AddHeader("Cache - Control", "private");
Response.ContentType = "application/pdf";
Response.BinaryWrite(ms.ToArray());
Response.Flush();
try { Response.End();
Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
catch { }
}
The codes works on Firefox, Edge. But it is not work on Google Chrome. What could be problem ? Can you help me ?
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";
Response.Flush method is not working. I am getting the data at pdfContent but it is not opening the PDF documnet. Below is the code. Please help.
public ActionResult PdfClick(int requestid)
{
BusinessRequestController bsnrqstcntrlr = new BusinessRequestController();
try
{
int DocId = (new BusinessRequestBR()).GetBaseLineDocumentsForSearch(requestid);
byte[] PdfContent = (new BusinessRequestHelper()).GetBaseLineDonload(DocId);
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + "BaseLine_Doc" + "_" + DocId + ".pdf");
Response.BinaryWrite(PdfContent);
Response.Flush();
return Content("");
}
catch (Exception ex)
{
throw this.log.CreatePropagatedException(ex);
}
Instead of using
return Content("")
use this:
return File(
PdfContent,
"application/pdf",
string.Format("BaseLine_Doc{0}.pdf", DocId)
)
There is no need to manipulate the response. Just return the correct result type.
Pulling out code from my running project
Response.Clear();
Response.AddHeader("Content-Disposition","attachment; filename=\"" + file[0].Name + "\"");
Response.AddHeader("Content-Length", fileSize.ToString(_culture));
Response.ContentType = Path.GetExtension(file[0].Name).GetMimeType();
Response.BufferOutput = false;
Response.AddHeader("Accept-Ranges", "bytes"); //tell the client that we accept byte-range requests
while (totalBytesRead < fileSize)
{
if (!Response.IsClientConnected)
{
System.Diagnostics.Debug.WriteLine("--> Client disconnected");
break;
}
int bytesRead = fs.Read(buffer, 0, buffer.Length);
Response.OutputStream.Write(buffer, 0, bytesRead);
Response.Flush();
totalBytesRead += bytesRead;
}
Response.End();
This code works for me every time, please manipulate according to your need.
Note: Variables are defined above the code.
I am using the below code to Export DataTable to MS Word,Excel,CSV format & it's working fine. But problem is that this code export to MS Word 2003,Excel 2003 version. I need to Export my DataTable to Word 2007,Excel 2007,CSV because I am supposed to handle more than 100,000 records at a time and as we know Excel 2003 supports for only 65,000 records.
Please help me out if you know that how to export DataTable or DataSet to MS Word 2007,Excel 2007.
public static void Convertword(DataTable dt, HttpResponse Response,string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".doc");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.word";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.GridView dg = new System.Web.UI.WebControls.GridView();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void Convertexcel(DataTable dt, HttpResponse Response, string filename)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
dg.DataSource = dt;
dg.DataBind();
dg.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
public static void ConvertCSV(DataTable dataTable, HttpResponse Response, string filename)
{
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".csv");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "Application/x-msexcel";
StringBuilder sb = new StringBuilder();
if (dataTable.Columns.Count != 0)
{
foreach (DataColumn column in dataTable.Columns)
{
sb.Append(column.ColumnName + ',');
}
sb.Append("\r\n");
foreach (DataRow row in dataTable.Rows)
{
foreach (DataColumn column in dataTable.Columns)
{
if(row[column].ToString().Contains(',')==true)
{
row[column] = row[column].ToString().Replace(",", "");
}
sb.Append(row[column].ToString() + ',');
}
sb.Append("\r\n");
}
}
Response.Write(sb.ToString());
Response.End();
//HttpContext.Current.ApplicationInstance.CompleteRequest();
}
Use application/vnd.openxmlformats-officedocument.spreadsheetml.sheet