not able to export excel from gridview - c#

this is my code:
protected void btnExcel_Click(object sender, ImageClickEventArgs e)
{
try
{
DataTable dtbl = (DataTable)ViewState["dtbl"];
string path = "E:\\shubby" + DateTime.Now.Day.ToString() + "_" + DateTime.Now.Month.ToString() + ".xls";
FileInfo fi = new FileInfo(path);
StringWriter sw = new StringWriter();
HtmlTextWriter htmltw = new HtmlTextWriter(sw);
DataGrid grdCrew = new DataGrid();
grdCrew.DataSource = dtbl;
grdCrew.DataBind();
grdCrew.RenderControl(htmltw);
string directory = path.Substring(0, path.LastIndexOf("\\"));// GetDirectory(Path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
System.IO.StreamWriter vw = new System.IO.StreamWriter(path, true);
sw.ToString().Normalize();
vw.Write(sw.ToString());
vw.Flush();
vw.Close();
WriteAttachment(fi.Name, "application/vnd.ms-excel", sw.ToString());
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public static void WriteAttachment(string FileName, string FileType, string content)
{
HttpResponse Response = System.Web.HttpContext.Current.Response;
Response.ClearHeaders();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.ContentType = FileType;
Response.Write(content);
Response.End();
}
I have seperate file for business logic and stored procedures, everything is working fine, its just the excel export that i am facing trouble with,
the error that i am getting is the exception that says "A required privilege is not held by the client"...
please help

Related

MVC FileStreamResult is not downloading file with custom file name

The pdf downloads fine but with a random name - 9619012021194536.pdf
I'm trying to set a custom name but it is not working.
The downloaded file still has a random name instead of the custom name being set in code.
public ActionResult Appointment(int id)
{
Stream stream = null;
string fileName = "";
try
{
stream = GenerateAppointmentReport(id);
fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
}
catch (Exception ex)
{
}
return new FileStreamResult(stream, MimeMapping.GetMimeMapping(fileName))
{ FileDownloadName = fileName };
}
You can use this code:
public ActionResult Appointment(int id)
{
Stream stream = null;
string fileName = "";
try
{
stream = GenerateAppointmentReport(id);
fileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
}
catch (Exception ex)
{
}
return new FileStreamResult(stream, "binary") { FileDownloadName = fileName };
}
I used this code and the file was downloaded with the specific name I mentioned.
You can bind the data in a temporary object of type GridView and then write the object to the output stream like this:
public ActionResult Appointment(int id)
{
GridView gridview = new GridView();
gridview.DataSource = fileData; //fileData is an object with all the properties
gridview.DataBind();
Response.ClearContent();
Response.Buffer = true;
tmpfileName = id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss") + ".pdf";
Response.AddHeader("content-disposition", "attachment; filename = " + tmpfileName);
Response.ContentType = "application/pdf";
Response.Charset = "";
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
gridview.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
}
return RedirectToAction("Appointment"); // To another/same action
}

Unable to translate Unicode character \uD83D at index 716 to specified code page. EPPLUS

I'm getting this error in ExcelPackage.GetAsByteArray() while exporting excel. I have tried everything as UTF-8 encoding etc but nothing works.
Below is my code
public void function Export()
{
ExcelPackage package = ExportUtil.GetMacroEnabledExtract(ds, extractName, "Comments");
Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + ExportUtil.getFileName(extractName, ".xlsm") + "\"");
Response.BinaryWrite(package.GetAsByteArray());
Response.End();
}
export function
public static ExcelPackage GetMacroEnabledExtract(DataSet ds, string extractName, string dataSheetName)
{
string appDataPath = HostingEnvironment.MapPath(#"~/App_Data");
string filePath = Path.Combine(appDataPath, "MacroTemplate.xlsm");
FileInfo templateFile = new FileInfo(filePath);
ExcelPackage package = new ExcelPackage(templateFile, false);
string fileName = getFileName(extractName, ".xlsm");
createDataWorkSheetMacroEnabled(package, ds.Tables[0], dataSheetName, templateFile); //Sheet 1
return package;
}
private static void createDataWorkSheetMacroEnabled(ExcelPackage package, DataTable table, string worksheetName, FileInfo file)
{
ExcelWorksheet wsData = package.Workbook.Worksheets[1];
wsData.Cells["A1"].LoadFromDataTable(table, true);
ExcelTextFormat format = new ExcelTextFormat();
format.Encoding = new UTF8Encoding();
wsData.Cells.LoadFromText(file, format);
}

How to fix Error in Generating Report ' network failed' in ASP>NET

I have a code that generate report onload from Report Viewer. I have also a try catch exception but it doesn't catch any error. But main problem is 'it can generate a report but it is failed'. It says 'failed - network error'
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
try
{
List<ReportParameter> paramList = new List<ReportParameter>();
DataTable dt = new DataTable();
DataSet dsWeeklyReportView = new DataSet();
string ConnectionString = "";
string FileName = "WeeklyReport" + ".xls";
string extension;
string encoding;
string mimeType;
string[] streams;
Warning[] warnings;
string Name = Session["ProjectName"].ToString();
string Status = Session["ProjectStatus"].ToString();
string Active = Session["ProjectActive"].ToString();
ReportViewer.ProcessingMode = ProcessingMode.Local;
paramList.Add(new ReportParameter("WEEKLYREPORTNAME", Session["ProjectName"].ToString()));
paramList.Add(new ReportParameter("WEEKLYREPORTSTATUS", Session["ProjectStatus"].ToString()));
paramList.Add(new ReportParameter("WEEKLYREPORTACTIVE", Session["ProjectActive"].ToString()));
ReportViewer.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Local;
ConnectionString = "DataSet";
ReportViewer.LocalReport.ReportPath = Server.MapPath("~") + "ReportGenerator.rdl";
dsWeeklyReportView = oWeeklyReport.dsWeeklyReport(Name, Status, Active);
dt = dsWeeklyReportView.Tables[0];
ReportViewer.LocalReport.DataSources.Add(new ReportDataSource(ConnectionString, dt));
ReportViewer.LocalReport.SetParameters(paramList);
ReportViewer.LocalReport.Refresh();
// ReportViewer2.Visible = true;
Byte[] mybytes = ReportViewer.LocalReport.Render("EXCEL", null,
out extension, out encoding,
out mimeType, out streams, out warnings); //for exporting to PDF
using (FileStream fs = File.Create(Server.MapPath("~//download//") + FileName))
{
fs.Write(mybytes, 0, mybytes.Length);
}
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.Clear();
Response.ContentType = "application/xls";
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.WriteFile(Server.MapPath("~/download/" + FileName));
Response.Flush();
Response.Close();
Response.End();
}
catch (Exception ex)
{ }
}
}
I already check parameters, path and names. There's no error in try catch and it generate a report but it is failed. Thank you for the answers.
After some investigation I found that calling Response.End() and Response.Clear() its throwing exception always, the solution by calling :
HttpContext.Current.Response.End();
HttpContext.Current.Response.Clear();

Why doesn't asp.net download work?

I am using this code to download a image i.e. I am storing Image name with extension in database and getting it here.
this code throws no error but doesn't download anything. why ?
try {
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
}
catch (Exception ex)
{
ResultLabel.ResultLabelAttributes(ex.Message, ProjectUserControls.Enums.ResultLabel_Color.Red);
}
finally
{
ResultPanel.Controls.Add(ResultLabel);
}
Update:
i tried this but doesn't work.
if (e.CommandName == "Download")
{
string ImgPath = Convert.ToString(r["Attachment"]);
//string ImgName = r["ComplaintDetailID"].ToString() + "-" + r["LetterNo"].ToString() + "-" + DateTime.Now.ToString("ddMMyyyyhhmmss");
//string filePath = ImgName + ".jpg";
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath).CopyTo(m);
m.WriteTo(Response.OutputStream);
string fullFilePath = Server.MapPath("~/SiteImages/CMS/" + ImgPath);
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(fullFilePath));
Response.ContentType = ContentType;
Response.TransmitFile(fullFilePath); //downloads file
Response.Flush();
//FileInfo file = new FileInfo(fullFilePath);
//file.Delete(); //deletes file after downloading
}
Create a Stream using following code
MemoryStream m = new MemoryStream();
File.OpenRead(ImgPath ).CopyTo(m);
m.WriteTo(Response.OutputStream);
You're on the right track using TransmitFile. Check this line:
Response.ContentType = ContentType;
It looks like you're setting the ContentType to the page's default.
Try specifying it explicitly:
Response.ContentType = "image/jpeg";

Namespace name 'html' does not exist in the namespace iTextSharp v5.4.0

I have a problem I want to convert to PDF From using iTextSharp using version v5.4.0
1.The type or namespace name 'html' does not exist in the namespace 'iTextSharp.text' (are you missing an assembly reference?)
2.The name 'PdfWriter' does not exist in the current context
3.The name 'HTMLWorker' does not exist in the current context
{
string fileName = "pdfDocument" + DateTime.Now.Ticks + ".pdf";
Response.Clear();
GeneratePDF("", fileName, true, "");
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
protected void GeneratePDFAndDownload(object sender, EventArgs e)
{
string fileName = "pdfDocument" + DateTime.Now.Ticks + ".pdf";
Response.Clear();
GeneratePDF("", fileName, true, "");
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.Flush();
Response.End();
}
private void GeneratePDF(string path, string fileName, bool download, string text)
{
var document = new Document();
try
{
if (download)
{
PdfWriter.GetInstance(document, Response.OutputStream);
}
else
{
PdfWriter.GetInstance(document, new FileStream(path + fileName, FileMode.Create));
}
StringBuilder strB = new StringBuilder();
document.Open();
if (text.Length.Equals(0))
{
BindMyGrid();
using (StringWriter sWriter = new StringWriter(strB))
{
using (HtmlTextWriter htWriter = new HtmlTextWriter(sWriter))
{
istorijaKupovinaGreedView.RenderControl(htWriter);
}
}
}
else
{
strB.Append(text);
}
using (TextReader sReader = new StringReader(strB.ToString()))
{
List<IElement> list = HTMLWorker.ParseToList(sReader, new StyleSheet());
foreach (IElement elm in list)
{
document.Add(elm);
}
}
}
catch (Exception ee)
{
lblMessage.Text = ee.ToString();
}
finally
{
document.Close();
}
}
private void BindMyGrid()
{
throw new NotImplementedException();
}
}

Categories