/// <summary> /// Download the file /// </summary> /// <param name="filePath">The file path</param> public static void DownloadFile(string filePath) { filePath = Utilities.FixRoot(filePath); FileInformation = new FileInfo(filePath); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); if (FileInformation.Name.EndsWith(".txt")) { response.ContentType = "text/plain"; } else if (FileInformation.Name.EndsWith(".jpg")) { response.ContentType = "image/jpg"; } if (FileInformation.Name.Equals("readme.html")) { response.TransmitFile(filePath); response.Flush(); response.End(); return; } response.AppendHeader("Content-Disposition", "attachment; filename=\"" + FileInformation.Name + "\";"); response.TransmitFile(filePath); response.Flush(); response.End(); }
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(); }
/// <summary> /// Funcion que permite al usuario descargar un archivo /// </summary> /// <param name="respuesta">Response del sitio web</param> /// <param name="datos">Datos a descargar</param> /// <param name="nombre">Nombre del archivo</param> /// <creador>Jonathan Contreras</creador> /// <fecha_creacion>03-10-2011</fecha_creacion> public void DescargarArchivo(System.Web.HttpResponse respuesta, System.IO.MemoryStream datos, String nombre, String tipo, System.Text.Encoding codificacion) { try { nombre = nombre.Replace(" ", "_"); string[] arrCaracteres = { ",", "?", "¿", "'", "!", "¡", "=", "|", "/", "\\" }; for (int intIndice = 0; intIndice < arrCaracteres.Length; intIndice++) { nombre = nombre.Replace(arrCaracteres[intIndice], string.Empty); } byte[] arrDatos = datos.ToArray(); respuesta.Clear(); respuesta.Buffer = true; respuesta.AddHeader("content-disposition", String.Format("attachment;filename={0}", nombre)); respuesta.AddHeader("Content-Length", arrDatos.Length.ToString()); respuesta.Charset = ""; respuesta.ContentType = tipo; respuesta.ContentEncoding = codificacion; respuesta.BinaryWrite(arrDatos); respuesta.Flush(); respuesta.End(); } catch { } }
/// <summary> /// Zip files and Download /// </summary> /// <param name="response">Current HttpResponse</param> /// <param name="zipFileToCreate">Zip save path</param> /// <param name="files">zipfile</param> public static void ResponseZip(System.Web.HttpResponse response, string zipFileToCreate, List <string> files) { try { using (ZipFile zip = new ZipFile()) { foreach (string filename in files) { ZipEntry e = zip.AddFile(filename, string.Empty); e.Comment = "Added by VAU"; } zip.Comment = string.Format( "This zip archive was created by the CreateZip example application on machine '{0}'", System.Net.Dns.GetHostName()); zip.Save(zipFileToCreate); } response.Clear(); response.AppendHeader("Content-Disposition", "attachment; filename=VAUFiles.zip"); response.ContentType = "application/x-zip-compressed"; response.WriteFile(zipFileToCreate); if (response.IsClientConnected) { response.Flush(); response.Close(); } } catch (System.Exception ex) { throw ex; } }
/// <summary>Transmits a file.</summary> /// <param name="filePath">The path to the file.</param> /// <param name="response">The response to write to.</param> public void TransmitFile(string filePath, System.Web.HttpResponse response) { SPFile file = FindFile(filePath); Debug("TransmitFile {0}", file.Exists); byte[] contents = file.OpenBinary(); response.OutputStream.Write(contents, 0, contents.Length); response.Flush(); }
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(); }
//public void DownloadFile(Guid? id) public void DownloadFile(string fileName) { //string fileName = fileNameBuilder(id); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.TransmitFile("C:\\reports\\" + fileName); response.Flush(); response.End(); }
public void DownloadFile(string fileName, byte[] csvData) { //string fileName = fileNameBuilder(id); System.Web.HttpResponse response = System.Web.HttpContext.Current.Response; response.ClearContent(); response.Clear(); response.ContentType = "text/csv"; response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";"); response.BinaryWrite(csvData); response.Flush(); response.End(); }
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> /// 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(); }
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(); }
public static void ResponseExcel <T>(System.Web.HttpResponse response, List <T> items) { try { string attachment = "attachment; filename=vauExcel.xls"; response.ClearContent(); response.AddHeader("content-disposition", attachment); response.ContentType = "application/vnd.ms-excel"; string tab = string.Empty; // Get all the properties PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo prop in props) { response.Write(tab + prop.Name); tab = "\t"; } response.Write("\n"); foreach (T item in items) { var values = new object[props.Length]; for (int i = 0; i < props.Length; i++) { values[i] = props[i].GetValue(item, null); if (values[i] != null) { response.Write(values[i].ToString().Trim() + "\t"); } else { response.Write("\t"); } } response.Write("\n"); } response.Flush(); response.Close(); } catch (Exception ex) { throw ex; } }
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); } }
/// <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(); }
/// <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); } }
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); }
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); } }
} // End Sub CreateExe // http://blogs.msdn.com/b/dotnetinterop/archive/2008/06/04/dotnetzip-now-can-save-directly-to-asp-net-response-outputstream.aspx // This will accumulate each of the files named in the fileList into a zip file, // and stream it to the browser. // This approach writes directly to the Response OutputStream. // The browser starts to receive data immediately which should avoid timeout problems. // This also avoids an intermediate memorystream, saving memory on large files. // public static void DownloadZipToBrowser(System.Collections.Generic.List <string> zipFileList) { System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response; Response.ClearContent(); Response.ClearHeaders(); Response.Clear(); Response.Buffer = false; Response.ContentType = "application/zip"; // If the browser is receiving a mangled zipfile, IIS Compression may cause this problem. Some members have found that // Response.ContentType = "application/octet-stream" has solved this. May be specific to Internet Explorer. Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\""); // Response.CacheControl = "Private"; // Response.Cache.SetExpires(System.DateTime.Now.AddMinutes(3)); // or put a timestamp in the filename in the content-disposition // http://stackoverflow.com/questions/9303919/pack-empty-directory-with-sharpziplib byte[] buffer = new byte[4096]; using (ZipOutputStream zipOutputStream = new ZipOutputStream(Response.OutputStream)) { zipOutputStream.SetLevel(3); //0-9, 9 being the highest level of compression // zipOutputStream.Dispose // Empty folder... foreach (string directoryName in zipFileList) { string dname = "myfolder/"; ZipEntry entry = new ZipEntry(dname); // ZipEntry entry = new ZipEntry(ZipEntry.CleanName(dname)); // entry.Size = fs.Length; zipOutputStream.PutNextEntry(entry); } // Next directoryName foreach (string fileName in zipFileList) { // or any suitable inputstream using (System.IO.Stream fs = System.IO.File.OpenRead(fileName)) { ZipEntry entry = new ZipEntry(ZipEntry.CleanName(fileName)); entry.Size = fs.Length; // Setting the Size provides WinXP built-in extractor compatibility, // but if not available, you can set zipOutputStream.UseZip64 = UseZip64.Off instead. zipOutputStream.PutNextEntry(entry); int count = fs.Read(buffer, 0, buffer.Length); while (count > 0) { zipOutputStream.Write(buffer, 0, count); count = fs.Read(buffer, 0, buffer.Length); if (!Response.IsClientConnected) { break; } Response.Flush(); } // Whend fs.Close(); } // End Using fs } // Next fileName zipOutputStream.Close(); } // End Using zipOutputStream Response.Flush(); Response.End(); } // End Function DownloadZipToBrowser
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> /// Download File จาก File Server /// </summary> /// <param name="httpResponse">Current Response from Page</param> /// <param name="folderContrainner">Folder ที่เก็บไฟล์</param> /// <param name="fileName">ชื่อไฟล์</param> public void DownloadFile(System.Web.HttpResponse httpResponse, string folderContrainner, string fileName) { //ระบุตำแหน่งไฟล์และที่เก็บบน File Server //FileService.DownloadRequest requestData = new FileService.DownloadRequest(); //FileService.RemoteFileInfo fileInfo = new FileService.RemoteFileInfo(); //string resMsg = svc.DownloadFile(ref fileName, folderContrainner, out fileInfo.Length, out fileInfo.FileByteStream); DownloadFileResponse response = new DownloadFileResponse(); response = svc.DownloadFile(new DownloadFileRequest() { TargetContainer = folderContrainner, TargetFileName = fileName }); Stream fileStream = response.FileByteStream; httpResponse.Clear(); httpResponse.BufferOutput = true; // Set Response.ContentType httpResponse.ContentType = response.ContentType; //GetContentType(fileExtension); // Append header httpResponse.AppendHeader("Content-Disposition", "attachment; filename=" + fileName); // Write the file to the Response const int bufferLength = 10000; byte[] buffer = new Byte[bufferLength]; int length = 0; Stream download = null; try { download = response.FileByteStream; // GetFile(fileName); do { if (httpResponse.IsClientConnected) { length = download.Read(buffer, 0, bufferLength); httpResponse.OutputStream.Write(buffer, 0, length); buffer = new Byte[bufferLength]; } else { length = -1; } }while (length > 0); httpResponse.Flush(); httpResponse.End(); } finally { if (download != null) { download.Close(); } } }
/// <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); }