private void DownloadPDF(byte[] downloadBytes, string downloadName) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.AddHeader("Content-Type", "binary/octet-stream"); response.AddHeader("Content-Disposition", "attachment; filename=" + StringHelper.CreateSlug(downloadName) + ".pdf; size=" + downloadBytes.Length.ToString()); response.Flush(); response.BinaryWrite(downloadBytes); response.Flush(); response.End(); }
public void ProcessRequest(HttpContext context) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(Server.MapPath("FileDownload.csv")); response.Flush(); response.End(); }
protected void TransmitFile(string filePath, string filename) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ";"); response.TransmitFile(filePath); response.Flush(); response.End(); }
/// <summary> /// 把DataTable导出为Word文件 /// </summary> /// <param name="page">Page</param> /// <param name="fileName">Word文件名(不包括后缀*.doc)</param> /// <param name="dtbl">将要被导出的DataTable对象</param> /// <returns></returns> public static bool DataTableToWord(System.Web.HttpResponse response, string fileName, DataTable dtbl) { response.Clear(); response.Buffer = true; response.Charset = "UTF-8"; response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".doc"); response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8"); response.ContentType = "application/ms-word"; //page.EnableViewState = false; response.Write(DataTableToHtmlTable(dtbl)); response.End(); return(true); }
/// <summary> /// Resposne via OutputStream /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void saveAs(rf.OfficeOpenXml.ExcelPackage package, System.Web.HttpResponse Response, string name = "temp.xlsx", string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); Response.Clear(); package.SaveAs(Response.OutputStream); } catch (Exception ex) { } }
protected void Button1_Click(object sender, EventArgs e) { CreateBarcodePdf(); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/pdf"; response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";"); response.TransmitFile(AppPath + @"Files\Barcode\" + FileName); response.Flush(); //File.Delete(FilePath); //File.Delete(FilePath + ".gif"); response.End(); }
/// <summary> /// Response via BinaryWrite /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void binaryWrite(rf.OfficeOpenXml.ExcelPackage package, System.Web.HttpResponse Response, string name = "temp.xlsx", string cookieKey = "Downloaded", string cookieValue = "True") { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", "attachment; filename=" + name); Response.Clear(); Response.BinaryWrite(package.GetAsByteArray()); } catch (Exception ex) { } }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AppendHeader("content-length", stream.Length.ToString()); byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); // Feb2015: Needed to replace "Response.End();" with the following 3 lines, to make sure the Excel was fully written to the Response System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); // Display an error on the webpage. System.Web.UI.Page page = System.Web.HttpContext.Current.CurrentHandler as System.Web.UI.Page; page.ClientScript.RegisterStartupScript(page.GetType(), "log", "console.log('Failed, exception thrown: " + ex.Message + "')", true); return(false); } }
protected void btnDownload_Click(object sender, EventArgs e) { //string ten = ViewState["FileName"].ToString().Trim(); string filePath = Format(ViewState["FileName"].ToString().Trim()); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = ContentType; response.AddHeader("Content-Disposition", "attachment; filename=" + filePath + ";"); response.TransmitFile(Server.MapPath("~/Files/" + filePath)); response.Flush(); response.End(); }
/// <summary> /// สำหรับ Zip ไฟล์และ Download /// </summary> /// <param name="httpResponse">Response ของ Page</param> /// <param name="reqDate">วันที่ต้องการ Download</param> /// <param name="tempFolder">Temp Folder</param> public void DownloadLicenseZip(System.Web.HttpResponse httpResponse, DateTime reqDate, string tempFolder) { //เตรียม Directory และ ไฟล์ที่ต้องการ Download string dir = InitRequestLicenseFileToDownload(tempFolder, reqDate); //สำหรับเก็บ Folder ที่ต้อง Zip เพื่อวนหาไฟล์ใน Folder List <string> list = new List <string>(); list.Add(dir); //วนหา Folder ที่ต้อง Zip และ SubFolder ที่อยู่ภายใน GetAllFiles(list, dir); string folderName = string.Empty; //สร้าง Instantce Zip using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile()) { //กำหนด Option Endcode zip.AlternateEncodingUsage = ZipOption.AsNecessary; //วนเ Folder และ SubFolder for (int i = 0; i < list.Count; i++) { //Folder ปัจจุบัน DirectoryInfo dInfo = new DirectoryInfo(list[i]); folderName += (i == 0 ? "" : "\\") + dInfo.Name; //สร้าง Folder ใน Zip zip.AddDirectoryByName(folderName); //วน Add File ใน Folder foreach (string f in Directory.GetFiles(list[i])) { zip.AddFile(f, folderName); } } httpResponse.Clear(); httpResponse.BufferOutput = false; string zipName = String.Format("{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); httpResponse.ContentType = "application/zip"; httpResponse.AddHeader("content-disposition", "attachment; filename=" + zipName); zip.Save(httpResponse.OutputStream); httpResponse.End(); } }
/// <summary> /// Resposne via OutputStream /// </summary> /// <param name="package"></param> /// <param name="Response"></param> public static void saveAs(rf.NPOI.HSSF.UserModel.HSSFWorkbook hssfworkbook, System.Web.HttpResponse Response, string name = "temp.xls", string cookieKey = defaultDownloadedCookieKey, string cookieValue = defaultDownloadedCookieValue) { try { Response.Cookies.Add(new System.Web.HttpCookie(cookieKey, cookieValue)); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", name)); Response.Clear(); System.IO.MemoryStream file = new System.IO.MemoryStream(); hssfworkbook.Write(file); file.WriteTo(Response.OutputStream); } catch (Exception ex) { } }
internal static void ThrowWmsException(WmsExceptionCode code, string Message) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); Response.ContentType = "text/xml"; Response.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); Response.Write("<ServiceExceptionReport version=\"1.3.0\" xmlns=\"http://www.opengis.net/ogc\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.opengis.net/ogc http://schemas.opengis.net/wms/1.3.0/exceptions_1_3_0.xsd\">\n"); Response.Write("<ServiceException"); if (code != WmsExceptionCode.NotApplicable) { Response.Write(" code=\"" + code.ToString() + "\""); } Response.Write(">" + Message + "</ServiceException>\n"); Response.Write("</ServiceExceptionReport>"); Response.End(); }
public void ProcessRequest(HttpContext context) { // retrieve your xbook System.IO.MemoryStream ms = new System.IO.MemoryStream(); xbook.Save(ms, C1.C1Excel.FileFormat.Biff8); xbook.Dispose(); ms.Position = 0; System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/vnd.ms-excel"; response.AddHeader("Content-Disposition","attachment;filename=CategoryReport.xls"); Response.BufferOutput = true; Response.OutputStream.Write(ms.ToArray(), 0, (int)ms.Length); response.Flush(); response.End(); }
/// <summary> /// Exports dataset into CSV / Excel format /// </summary> private void ExportForWeb(DataSet exportDataSet, string[] headerList, string[] filedList, ExportFormat formatType, string fileName) { try { response.Clear(); response.Buffer = true; if (formatType == ExportFormat.CSV) { response.ContentType = "text/csv"; response.AppendHeader("content-disposition", "attachment; filename=" + fileName); } else { response.ContentType = "application/vnd.ms-excel"; response.AppendHeader("content-disposition", "attachment; filename=" + fileName); } MemoryStream memoryStream = new MemoryStream(); XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8); XmlDataDocument xmlDataDocument = new XmlDataDocument(exportDataSet); XslTransform xslTransform = new XslTransform(); StringWriter stringWriter = new StringWriter(); CreateStylesheet(xmlTextWriter, headerList, filedList, formatType); xmlTextWriter.Flush(); memoryStream.Seek(0, SeekOrigin.Begin); xslTransform.Load(new XmlTextReader(memoryStream), null, null); xslTransform.Transform(xmlDataDocument, null, stringWriter, null); response.Write(stringWriter.ToString()); stringWriter.Close(); xmlTextWriter.Close(); memoryStream.Close(); response.End(); } catch (ThreadAbortException ex) { string ErrMsg = ex.Message; } catch (Exception ex) { throw ex; } }
//download file public void saveFile(System.Web.HttpResponse Response, string PathfileName) { string filename = PathfileName; if (filename != "") { string path = filename; System.IO.FileInfo file = new System.IO.FileInfo(path); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/octet-stream"; Response.WriteFile(file.FullName); Response.End(); } } }
} // TODO: Add constructor logic here public void ProcessRequest(System.Web.HttpContext context) { System.Web.HttpResponse response = context.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/html"; response.ContentEncoding = System.Text.Encoding.UTF8; // <p id="errorMessage">@error.Type: @error.Message</p> // <span>@error.StackTrace</span> string res = ResourceHelper.GetResource(typeof(ErrorTemplateHandler), "ErrorTemplate.htm"); response.Write(res); // response.Write("<html><body><h1>Hello 15Seconds Reader "); // response.Write("</body></html>"); } // End Sub ProcessRequest
protected void hlnkDownload_Click(object sender, EventArgs e) { try { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("Content-Disposition", "attachment; filename=MasterEmployeeData.xlsx;"); response.TransmitFile(Server.MapPath("~/Data/MasterEmployeeData.xlsx")); response.Flush(); response.End(); } catch (Exception ex) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Something went wrong. Check Log."; ExceptionManager.LogError(ex); } }
// zzzzzzz // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx public static void ZipToHttpResponse(string DirectoryToZip) { string ReadmeText = "This is a zip file dynamically generated at " + System.DateTime.Now.ToString("G"); System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.Clear(); string fileName = @"Довнлоад.zip"; // @"Довнлоад.зип" fileName = @"Download.zip"; Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "filename=" + fileName); //using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(Response.OutputStream)) using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile(System.Text.Encoding.UTF8)) { // Add to the zip archive, the file selected in the dropdownlist. // zip.AddFile(ListOfFiles.SelectedItem.Text, "files"); // Add a boilerplate copyright file into the zip. // zip.AddFile(@"\static\Copyright.txt", ""); // The string ReadmeText becomes the content for an entry in the zip archive, with the filename "Readme.txt". // zip.AddStringAsFile(ReadmeText, "Readme.txt", ""); zip.Comment = "This will be embedded into a self-extracting exe"; zip.AddEntry("ReadMeZB.txt", ReadmeText); // http://dotnetslackers.com/articles/aspnet/Use-ASP-NET-and-DotNetZip-to-Create-and-Extract-ZIP-Files.aspx // zip.Password = "******"; // zip.Encryption = Ionic.Zip.EncryptionAlgorithm.PkzipWeak; //zip.StatusMessageTextWriter = System.Console.Out; zip.AddDirectory(DirectoryToZip); // recurses subdirectories // zip.Save(); zip.Save(Response.OutputStream); } // End Using zip Response.End(); } // End Sub ZipToHttpResponse
public JObject DownloadFile(string fileName) { JObject obj = new JObject(); try { System.Web.HttpRequest httpRequest = System.Web.HttpContext.Current.Request; string filePath = System.Web.HttpContext.Current.Server.MapPath("~/ApiUploadFile/"); filePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/ApiUploadFile/"), fileName); if (File.Exists(filePath)) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.Clear(); response.ClearHeaders(); response.ClearContent(); response.Buffer = true; response.AddHeader("content-disposition", string.Format("attachment; FileName={0}", fileName)); response.Charset = "utf-8"; response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); response.ContentType = System.Web.MimeMapping.GetMimeMapping(fileName); response.WriteFile(filePath); response.Flush(); response.Close(); obj.Add("success", true); obj.Add("message", ""); } else { obj.Add("success", false); obj.Add("message", "文件不存在!"); } } catch (Exception ex) { obj.Add("success", false); obj.Add("message", ex.Message); } return(obj); }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document, filename); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.ms-excel"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { System.IO.File.WriteAllText(@"D:\DSPBlackRock\errormessage.txt", "Failed, exception thrown: " + ex.Message); return(false); } }
/// <summary> /// Handles the Click event of the btnDownloadLog control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> protected void btnDownloadLog_Click(object sender, EventArgs e) { System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/plain"; response.AddHeader("content-disposition", "attachment; filename=slingshot-errors.log"); response.Charset = ""; string filePath = Server.MapPath("~/App_Data/SlingshotFiles/slingshot-errors.log"); if (File.Exists(filePath)) { response.TransmitFile(filePath); } response.Flush(); response.End(); response.SuppressContent = true; System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest(); }
public static void Export(System.Data.DataTable dt, System.Web.HttpResponse response, string filename) { //first let's clean up the response.object response.Clear(); response.ClearHeaders(); response.Buffer = true; response.ContentEncoding = System.Text.Encoding.UTF8; response.Charset = "utf-8"; response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); //set the response mime type for excel response.ContentType = "application/vnd.ms-excel"; // added to help issue with IE problems with Cache-Control: no-cache response.ExpiresAbsolute = DateTime.Now.AddYears(-1); //header/footer to support UTF-8 characters var header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + Constants.vbLf + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + Constants.vbLf + "<head>" + Constants.vbLf + "<title></title>" + Constants.vbLf + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + Constants.vbLf + "<style>" + Constants.vbLf + "</style>" + Constants.vbLf + "</head>" + Constants.vbLf + "<body>" + Constants.vbLf; var footer = Constants.vbLf + "</body>" + Constants.vbLf + "</html>"; response.Write(header); //create an htmltextwriter which uses the stringwriter var htmlWrite = new System.Web.UI.HtmlTextWriter(response.Output); //instantiate a datagrid var dg = new System.Web.UI.WebControls.DataGrid(); //set the datagrid datasource to the dataset passed in dg.DataSource = dt; //bind the datagrid dg.DataBind(); //tell the datagrid to render itself to our htmltextwriter dg.RenderControl(htmlWrite); response.Write(footer); //all that's left is to output the html response.End(); }
public static bool CreateExcelDocumentAsStream(DataSet ds, string filename, System.Web.HttpResponse Response) { try { System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument document = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { WriteExcelFile(ds, document); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { Trace.WriteLine("Failed, exception thrown: " + ex.Message); return(false); } }
/// <summary> /// Initialization event. /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { System.Web.HttpRequest request = Context.Request; System.Web.HttpResponse response = Context.Response; if (request.Params["PlotSurface2D_" + this.ClientID] != null) { // retrieve the bitmap and display response.Clear(); try { response.ContentType = "Image/Png"; System.Drawing.Bitmap bmp = (System.Drawing.Bitmap)Context.Session[prefix() + "PNG"]; // don't ask why, but if I write directly to the response // I have a GDI+ error, if I first write to a MemoryStream and // then to the response.OutputStream I don't get an error. System.IO.MemoryStream s = new System.IO.MemoryStream(); bmp.Save(s, System.Drawing.Imaging.ImageFormat.Png); s.WriteTo(response.OutputStream); Context.Session.Remove(prefix() + "PNG"); } catch (Exception ex) { response.ContentType = "Text/HTML"; response.Write(ex.Message); } finally { response.Flush(); response.End(); } } this.plotUrl = this.buildPlotURL(); base.OnInit(e); }
//OpenXML kullanarak DataSeti Excel (.xlsx) dosyasına çevirip indirmek // REFERANSLAR // *************************************** // DocumentFormat.OpenXml // WindowsBase //Bu iki referans projeye bir kez eklenir // *************************************** public static bool ExcelOlusturIndir(DataSet ds, string dosyaadi, System.Web.HttpResponse Response) { try { //"HttpCacheability does not exist" hatası alırsanız projeye System.Web referansını ekleyin System.IO.MemoryStream stream = new System.IO.MemoryStream(); using (SpreadsheetDocument dosya = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook, true)) { DataSetExceleYaz(ds, dosya); } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + dosyaadi); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } catch (Exception ex) { Trace.WriteLine("Hata oluştu: " + ex.Message); return(false); } }
// // GET: /ExportToImage/ public ActionResult Index(string Format = "png") { string baseURL = Request.Url.Authority; if (Request.ServerVariables["HTTPS"] == "on") { baseURL = "https://" + baseURL; } else { baseURL = "http://" + baseURL; } // Check for license and apply if exists string licenseFile = Server.MapPath("~/App_Data/Aspose.Words.lic"); if (System.IO.File.Exists(licenseFile)) { License license = new License(); license.SetLicense(licenseFile); } //Null value Check if (Request.UrlReferrer != null) { string refUrl = Request.UrlReferrer.AbsoluteUri; string html = new WebClient().DownloadString(refUrl); var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(html)); Document doc = new Document(memoryStream); string fileName = ""; if (doc.PageCount > 1) { Directory.CreateDirectory(Server.MapPath("~/Images/" + "Zip")); } ImageSaveOptions options = new ImageSaveOptions(SaveFormat.Png); if (Format.Contains("png")) { options = new ImageSaveOptions(SaveFormat.Png); options.PageCount = 1; } else if (Format.Contains("JPEG")) { options = new ImageSaveOptions(SaveFormat.Jpeg); options.PageCount = 1; } else if (Format.Contains("TIFF")) { options = new ImageSaveOptions(SaveFormat.Tiff); options.PageCount = 1; } else if (Format.Contains("bmp")) { options = new ImageSaveOptions(SaveFormat.Bmp); options.PageCount = 1; } // Check for Images folder string path = Server.MapPath("~/Images"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } // Convert the html , get page count and save PNG's in Images folder for (int i = 0; i < doc.PageCount; i++) { if (Format.Contains("TIFF")) { options.PageCount = doc.PageCount; fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); break; } else { options.PageIndex = i; if (doc.PageCount > 1) { fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); } else { // webpage count is 1 fileName = i + "_" + System.Guid.NewGuid().ToString() + "." + Format; doc.Save(Server.MapPath("~/Images/Zip/") + fileName, options); } } } /* if webpage count is more then one download images as a Zip but if image type if TIFF * dont download as a zip because Tiff already have all content in one Image */ if (doc.PageCount > 1 && !Format.Contains("TIFF")) { try { string ImagePath = Server.MapPath("~/Images/Zip/"); string downloadDirectory = Server.MapPath("~/Images/"); ZipFile.CreateFromDirectory(ImagePath, downloadDirectory + "OutputImages.zip"); // Prompts user to save file System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "application/zip"; response.AddHeader("Content-Disposition", "attachment; filename=OutputImages.zip" + ";"); response.TransmitFile(downloadDirectory + "OutputImages.zip"); response.End(); Directory.Delete(ImagePath, true); System.IO.File.Delete(downloadDirectory + "OutputImages.zip"); } catch (Exception Ex) { } } else { string filepath = Server.MapPath("~/Images/Zip/") + fileName; string downloadDirectory = Server.MapPath("~/Images/Zip/"); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "image/" + Format; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile(filepath); response.End(); Directory.Delete(downloadDirectory, true); } } //set the view to your default View (in my case its home index view) return(RedirectToAction("index", "Home")); }
public void Save(System.IO.Stream OutputStream, System.Web.HttpResponse response) { string filename = "Export_" + Guid.NewGuid().ToString(); string completePathOne = GenerateUniquePath(filename, "xlsx"); string completePathTwo = GenerateUniquePath(filename, "xls"); string completePath = null; string tableName = null; ISDWorksheet ws = (ISDWorksheet)this.Worksheets[0]; ISDTable ta = ws.Table; tableName = ws.Name; ArrayList rows = ta.Rows; ISDWorksheetRow row0 = null; if (rows.Count > 0) { row0 = (ISDWorksheetRow)rows[0]; } ISDWorksheetRow row1 = row0; if (rows.Count > 1) { row1 = (ISDWorksheetRow)rows[1]; } ArrayList cols = ta.Columns; string colDefs = GetColumnDefinitions(cols, row0.Cells, row1.Cells, true); string colNames = GetColumnDefinitions(cols, row0.Cells, row1.Cells, false); completePath = completePathTwo; HSSFWorkbook hssfwb = new HSSFWorkbook(); IDataFormat format = hssfwb.CreateDataFormat(); ISheet sh = hssfwb.CreateSheet("Sheet1"); int rIndex = 0; IRow r = sh.CreateRow(rIndex); int c = 0; HSSFCellStyle[] styles = new HSSFCellStyle[row0.Cells.Count + 1]; foreach (ISDWorksheetCell hCell in row0.Cells) { HSSFCellStyle style = (HSSFCellStyle)hssfwb.CreateCellStyle(); ICell ce = r.CreateCell(c); ce.SetCellValue(hCell.Text); style.WrapText = true; styles[c] = (HSSFCellStyle)hssfwb.CreateCellStyle(); ce.CellStyle = style; c += 1; } for (rIndex = 1; rIndex <= rows.Count - 1; rIndex++) { ISDWorksheetRow currentRow = (ISDWorksheetRow)rows[rIndex]; r = sh.CreateRow(rIndex); c = 0; for (int i = 0; i <= currentRow.Cells.Count - 1; i++) { //myValue = myValue.Replace("$", "").Replace(",", "") ICell ce = r.CreateCell(c); HSSFCellStyle style = styles[i]; ISDWorksheetCell dCell = (ISDWorksheetCell)currentRow.Cells[i]; string formatStr = dCell.Format; if (dCell.Type == ISDDataType.ISDInteger || dCell.Type == ISDDataType.ISDNumber) { ce.SetCellType(CellType.NUMERIC); if (dCell.Value != null) { ce.SetCellValue(Convert.ToDouble(dCell.Value)); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { System.Globalization.NumberFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.NumberFormat; if (string.IsNullOrEmpty(dCell.Format) || dCell.Format == null) { formatStr = "##0.00"; } else if (dCell.Format.Contains("C") || dCell.Format.Contains("c")) { formatStr = info.CurrencySymbol + "##0.00"; } else if (dCell.Format.Contains("P") || dCell.Format.Contains("p")) { formatStr = "##0.00" + info.PercentSymbol; } else if (dCell.Format.Contains(info.CurrencySymbol) || dCell.Format.Contains(info.PercentSymbol)) { // use the user given display format } else { formatStr = "##0.00"; } style.DataFormat = format.GetFormat(formatStr); } } else if (dCell.Type == ISDDataType.ISDDateTime) { if (dCell.Value != null) { ce.SetCellType(CellType.NUMERIC); ce.SetCellValue(Convert.ToDateTime(dCell.Value)); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { System.Globalization.DateTimeFormatInfo info = System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat; // convert the date format understood by Excel // see http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx switch (dCell.Format) { case "d": formatStr = info.ShortDatePattern; break; case "D": formatStr = info.LongDatePattern; break; case "t": formatStr = info.ShortTimePattern; break; case "T": formatStr = info.LongTimePattern; break; case "f": formatStr = info.LongDatePattern + " " + info.ShortTimePattern; break; case "F": formatStr = info.FullDateTimePattern; break; case "g": formatStr = info.ShortDatePattern + " " + info.ShortTimePattern; break; case "G": formatStr = info.ShortDatePattern + " " + info.LongTimePattern; break; case "M": case "m": formatStr = info.MonthDayPattern; break; case "R": case "r": formatStr = info.RFC1123Pattern; break; case "s": formatStr = info.SortableDateTimePattern; break; case "u": formatStr = info.UniversalSortableDateTimePattern; break; case "U": formatStr = info.FullDateTimePattern; break; case "Y": case "y": formatStr = info.YearMonthPattern; break; default: formatStr = info.ShortDatePattern; break; } // some pattern above might return t but this is not recognized by Excel, so remove it formatStr = formatStr.Replace("t", ""); style.DataFormat = format.GetFormat(formatStr); } } else { ce.SetCellType(CellType.STRING); if (dCell.Value != null) { string myValue = dCell.Text; if (myValue.Length > 255) { myValue = myValue.Substring(0, 255); } ce.SetCellValue(myValue); } if (GetBuildInFormat(dCell.Format) > 0) { style.DataFormat = HSSFDataFormat.GetBuiltinFormat(dCell.Format); } else { style.DataFormat = HSSFDataFormat.GetBuiltinFormat("TEXT"); style.WrapText = true; } } ce.CellStyle = style; c += 1; } } MemoryStream ms = new MemoryStream(); hssfwb.Write(ms); string NPOIDownloadFileName = this.Properties.Title; if (completePath.EndsWith(".xlsx")) { NPOIDownloadFileName += ".xlsx"; } else { NPOIDownloadFileName += ".xls"; } response.ClearHeaders(); response.Clear(); response.Cache.SetCacheability(System.Web.HttpCacheability.Private); response.Cache.SetMaxAge(new TimeSpan(0)); response.Cache.SetExpires(new DateTime(0)); response.Cache.SetNoServerCaching(); response.AppendHeader("Content-Disposition", ("attachment; filename=\"" + (NPOIDownloadFileName + "\""))); response.ContentType = "application/vnd.ms-excel"; OutputStream.Write(ms.ToArray(), 0, ms.ToArray().Length); return; }
public void ExportToExcel(DataTable dtTemp, string filename, string sheetname, string sheetHeader) { try { string Today = DateTime.Now.ToString("d MMM yyyy"); HSSFWorkbook hssfworkbook = new HSSFWorkbook(); string FileName = ""; if (filename.EndsWith(".xls")) { FileName = filename; } else { FileName = filename + ".xls"; } HSSFSheet sheet1 = (NPOI.HSSF.UserModel.HSSFSheet)hssfworkbook.CreateSheet(sheetname); sheet1.DisplayGridlines = true; sheet1.Footer.Right = "Page " + HSSFFooter.Page; sheet1.SetMargin(MarginType.FooterMargin, (double)0.25); #region "Print Setup" sheet1.SetMargin(MarginType.RightMargin, (double)0.25); sheet1.SetMargin(MarginType.TopMargin, (double)0.75); sheet1.SetMargin(MarginType.LeftMargin, (double)0.50); sheet1.SetMargin(MarginType.BottomMargin, (double)0.75); sheet1.PrintSetup.Copies = 1; sheet1.PrintSetup.Landscape = false; sheet1.PrintSetup.PaperSize = 9; sheet1.PrintSetup.Scale = 90; sheet1.IsPrintGridlines = true; sheet1.Autobreaks = true; sheet1.FitToPage = false; #endregion HSSFRow rowHeader = (NPOI.HSSF.UserModel.HSSFRow)sheet1.CreateRow(0); #region "Header" for (int k = 0; k < dtTemp.Columns.Count; k++) { String columnName = dtTemp.Columns[k].ToString().Replace("_", " "); HSSFCell cell = (NPOI.HSSF.UserModel.HSSFCell)rowHeader.CreateCell(k); var headerLabelCellStyle = hssfworkbook.CreateCellStyle(); headerLabelCellStyle.LeftBorderColor = HSSFColor.Black.Index; headerLabelCellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; headerLabelCellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; headerLabelCellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; headerLabelCellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; headerLabelCellStyle.BottomBorderColor = HSSFColor.Grey50Percent.Index; headerLabelCellStyle.TopBorderColor = HSSFColor.Grey50Percent.Index; headerLabelCellStyle.LeftBorderColor = HSSFColor.Grey50Percent.Index; headerLabelCellStyle.RightBorderColor = HSSFColor.Grey50Percent.Index; headerLabelCellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left; headerLabelCellStyle.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Top; headerLabelCellStyle.ShrinkToFit = true; var formate = hssfworkbook.CreateDataFormat(); var headerLabelFont = hssfworkbook.CreateFont(); headerLabelFont.FontHeight = 200; headerLabelFont.Boldweight = (short)FontBoldWeight.Bold; var headerDataFormat = hssfworkbook.CreateDataFormat(); headerLabelCellStyle.SetFont(headerLabelFont); cell.SetCellValue(columnName); cell.CellStyle = headerLabelCellStyle; rowHeader.Height = 400; } #endregion #region "Row" int count = 1; for (int i = 0; i < dtTemp.Rows.Count; i++) { var RowCellStyle = hssfworkbook.CreateCellStyle(); HSSFRow row = (NPOI.HSSF.UserModel.HSSFRow)sheet1.CreateRow(count); for (int l = 0; l < dtTemp.Columns.Count; l++) { HSSFCell cell = (NPOI.HSSF.UserModel.HSSFCell)row.CreateCell(l); String columnName = dtTemp.Columns[l].ToString(); cell.CellStyle.WrapText = true; cell.SetCellValue(Convert.ToString(dtTemp.Rows[i][columnName])); cell.CellStyle = RowCellStyle; cell.CellStyle.WrapText = true; } count++; } #endregion #region "Set Columns width" for (int d = 0; d < dtTemp.Columns.Count; d++) { string columnName = dtTemp.Columns[d].ToString(); if (columnName == "Notification") { sheet1.SetColumnWidth(d, 35 * 300); } else if (columnName == "Processing_Status") { sheet1.SetColumnWidth(d, 35 * 300); } else if (columnName == "Action_Status") { sheet1.SetColumnWidth(d, 35 * 300); } else { sheet1.AutoSizeColumn(d); } } #endregion System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", FileName)); Response.Clear(); Response.BinaryWrite(WriteToStream(hssfworkbook).GetBuffer()); Response.Flush(); Response.End(); } catch (Exception ex) { string s = ex.Message; } }
/// <summary> /// Create an Excel file, and write it out to a MemoryStream (rather than directly to a file) /// </summary> /// <param name="ds">DataSet containing the data to be written to the Excel.</param> /// <param name="filename">The filename (without a path) to call the new Excel file.</param> /// <param name="Response">HttpResponse of the current page.</param> /// <returns>Either a MemoryStream, or NULL if something goes wrong.</returns> public static bool CreateExcelDocumentAsStreamList(DataSet dtSet, string filename, System.Web.HttpResponse Response) { try { foreach (DataTable dtSchema in dtSet.Tables) { System.IO.MemoryStream stream = new System.IO.MemoryStream(); int RowInCell = 63000; DataTable ResultsData = new DataTable(); ResultsData = dtSchema.Clone(); int c = 0; int rowNumber = 0; bool firstTime = true; foreach (DataRow rows in dtSchema.Rows) { DataRow row = ResultsData.NewRow(); ResultsData.ImportRow(rows); // ResultsData.Rows.Add(rows); // ResultsData.Rows.Add(rows); if (c == RowInCell) { c = 0; //ExportToOxml(firstTime, ResultsData, filename); ExportToOxml(firstTime, ResultsData, stream); ResultsData.Clear(); firstTime = false; } if (rowNumber == dtSchema.Rows.Count - 1) { c = 0; //ExportToOxml(firstTime, ResultsData, filename); ExportToOxml(firstTime, ResultsData, stream); ResultsData.Clear(); firstTime = false; } c++; rowNumber++; } stream.Flush(); stream.Position = 0; Response.ClearContent(); Response.Clear(); Response.Buffer = true; Response.Charset = ""; // NOTE: If you get an "HttpCacheability does not exist" error on the following line, make sure you have // manually added System.Web to this project's References. Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); Response.AddHeader("content-disposition", "attachment; filename=" + filename); Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; byte[] data1 = new byte[stream.Length]; stream.Read(data1, 0, data1.Length); stream.Close(); Response.BinaryWrite(data1); Response.Flush(); Response.End(); return(true); } } catch (Exception ex) { Common.WriteLog(ex.Message + "\n" + ex.InnerException + "\n" + ex.StackTrace); return(false); } return(false); }
} // TODO: Add constructor logic here public void ProcessRequest(System.Web.HttpContext context) { System.Web.HttpResponse response = context.Response; response.ClearHeaders(); response.ClearContent(); response.Clear(); response.ContentType = "text/html"; response.ContentEncoding = System.Text.Encoding.UTF8; string html = @"<!DOCTYPE html> <html xmlns=""http://www.w3.org/1999/xhtml"" lang=""en""> <head> <meta http-equiv=""X-UA-Compatible"" content=""IE=edge,chrome=1"" /> <meta http-equiv=""cache-control"" content=""max-age=0"" /> <meta http-equiv=""cache-control"" content=""no-cache"" /> <meta http-equiv=""expires"" content=""0"" /> <meta http-equiv=""expires"" content=""Tue, 01 Jan 1980 1:00:00 GMT"" /> <meta http-equiv=""pragma"" content=""no-cache"" /> <meta charset=""utf-8"" /> <meta http-equiv=""Content-Type"" content=""text/html; charset=utf-8"" /> <meta http-equiv=""Content-Language"" content=""en"" /> <meta name=""viewport"" content=""width=device-width,initial-scale=1"" /> <!-- <meta name=""author"" content=""name"" /> <meta name=""description"" content=""description here"" /> <meta name=""keywords"" content=""keywords,here"" /> <link rel=""shortcut icon"" href=""favicon.ico"" type=""image/vnd.microsoft.icon"" /> <link rel=""stylesheet"" href=""stylesheet.css"" type=""text/css"" /> --> <title>Title</title> <style type=""text/css"" media=""all""> body { background-color: #0c70b4; color: #546775; font: normal 400 18px ""PT Sans"", sans-serif; -webkit-font-smoothing: antialiased; } </style> <script type=""text/javascript""> </script> </head> <body> <h1>Hello 15Seconds Reader</h1> </body> </html> "; html = ResourceHelper.GetResource(typeof(InjectionBlockHandler), "BlackErrorTemplate_Injection_DE.htm"); response.Write(html); context.ApplicationInstance.CompleteRequest(); } // End Sub ProcessRequest