Ejemplo n.º 1
0
        /// <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 { }
        }
Ejemplo n.º 2
0
        //----------------------------------------------------------------------------------------------------
        /// <summary></summary>
        /// <param name="report"></param>
        /// <param name="response"></param>
        public static void ResponsePDF(Report report, System.Web.HttpResponse response, string fileName)
        {
            if (report.formatter == null)
            {
                report.Init(new PdfFormatter());
            }
            if (report.page_Cur == null)
            {
                report.Create();
            }

            response.Clear();
            response.Buffer          = true;
            response.ContentType     = "application/pdf";
            response.Charset         = "";
            response.ContentEncoding = System.Text.Encoding.Default;
            response.ClearContent();
            response.AddHeader("Content-Disposition", "filename=" + fileName + ".pdf");

            MemoryStream ms = new MemoryStream();

            report.formatter.Create(report, ms);
            ms.Close();

            response.BinaryWrite(ms.GetBuffer());
            response.End();
        }
Ejemplo n.º 3
0
 private void ExportPdfFile(byte[] pdfBytes, string fileName)
 {
     pdfConverter.LicenseKey = SF.Framework.SFConfig.EVOPDFKEY;
     System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
     response.Clear();
     response.AddHeader("Content-Type", "application/pdf");
     response.AddHeader("Content-Disposition", String.Format("attachment; filename=" + fileName + ".pdf; size={0}", pdfBytes.Length.ToString()));
     response.BinaryWrite(pdfBytes);
     response.End();
 }
Ejemplo n.º 4
0
                /// <summary>
                /// Get thumbnail image
                /// </summary>
                /// <param name="image"></param>
                /// <param name="imageFormat"></param>
                /// <param name="thumbWidth"></param>
                /// <param name="thumbHeight"></param>
                /// <param name="ThumbnailCallback"></param>
                /// <param name="Response"></param>
                /// <param name="responseContentType"></param>
                /// <returns></returns>
                public static byte[] GetThumbImage(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat imageFormat, int thumbWidth = -1, int thumbHeight = -1, Func <bool> ThumbnailCallback = null, System.Web.HttpResponse Response = null, String responseContentType = "image/jpeg")
                {
                    byte[] imageContent = new byte[] { };
                    ThumbnailCallback = null == ThumbnailCallback ? new System.Func <bool>(delegate() { return(true); }) : ThumbnailCallback;
                    thumbWidth        = (-1 == thumbWidth) ? image.Width : thumbWidth;
                    thumbHeight       = (-1 == thumbHeight) ? image.Height : thumbHeight;
                    try
                    {
                        // get the file name -- fall800.jpg
                        //string file = Request.QueryString["file"];

                        // create an image object, using the filename we just retrieved
                        //System.Drawing.Image image = System.Drawing.Image.FromFile(Server.MapPath(file));

                        // create the actual thumbnail image
                        System.Drawing.Image thumbnailImage = image.GetThumbnailImage(thumbWidth, thumbHeight, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero);
                        // make a memory stream to work with the image bytes
                        using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
                        {
                            try
                            {
                                // put the image into the memory stream
                                thumbnailImage.Save(imageStream, imageFormat);

                                // make byte array the same size as the image
                                imageContent = new Byte[imageStream.Length];

                                // rewind the memory stream
                                imageStream.Position = 0;

                                // load the byte array with the image
                                imageStream.Read(imageContent, 0, (int)imageStream.Length);
                            }
                            catch (Exception exb)
                            {
                            }
                        }
                        if (null != Response)
                        {
                            // return byte array to caller with image type
                            try
                            {
                                Response.ContentType = responseContentType;
                                Response.BinaryWrite(imageContent);
                            }
                            catch (Exception exc) { }
                        }
                        else
                        {
                        }
                    }
                    catch (Exception ex) { }
                    return(imageContent);
                }
Ejemplo n.º 5
0
        public void ResponseFile(System.Web.HttpResponse response, string fileUId)
        {
            Box.CMS.File file = cms.GetFile(fileUId);
            if (file == null)
            {
                response.End();
            }

            response.ContentType = file.Type;
            response.BinaryWrite(file.Data.StoredData);
            response.End();
        }
Ejemplo n.º 6
0
 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();
 }
Ejemplo n.º 7
0
 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();
 }
Ejemplo n.º 8
0
 /// <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)
     {
     }
 }
Ejemplo n.º 9
0
        /// <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);
            }
        }
Ejemplo n.º 10
0
        internal static void CreatePDFDocument(DataTable dt, string excelFilename, System.Web.HttpResponse Response)
        {
            //
            // For PDF export we are using the free open-source iTextSharp library.
            //
            Document     pdfDoc    = new Document();
            MemoryStream pdfStream = new MemoryStream();
            PdfWriter    pdfWriter = PdfWriter.GetInstance(pdfDoc, pdfStream);

            pdfDoc.Open();//Open Document to write
            pdfDoc.NewPage();

            iTextSharp.text.Font font8 = FontFactory.GetFont("ARIAL", 7);

            PdfPTable PdfTable = new PdfPTable(dt.Columns.Count);
            PdfPCell  PdfPCell = null;

            //Add Header of the pdf table
            for (int column = 0; column < dt.Columns.Count; column++)
            {
                PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Columns[column].Caption, font8)));
                PdfTable.AddCell(PdfPCell);
            }

            //How add the data from datatable to pdf table
            for (int rows = 0; rows < dt.Rows.Count; rows++)
            {
                for (int column = 0; column < dt.Columns.Count; column++)
                {
                    PdfPCell = new PdfPCell(new Phrase(new Chunk(dt.Rows[rows][column].ToString(), font8)));
                    PdfTable.AddCell(PdfPCell);
                }
            }

            PdfTable.SpacingBefore = 15f; // Give some space after the text or it may overlap the table
            pdfDoc.Add(PdfTable);         // add pdf table to the document
            pdfDoc.Close();
            pdfWriter.Close();

            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/pdf";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + excelFilename);
            Response.BinaryWrite(pdfStream.ToArray());
            Response.End();
        }
Ejemplo n.º 11
0
        public static void ResponsePDF(Report report, System.Web.HttpResponse response)
        {
            if (report.formatter == null)
            {
                report.Init(new PdfFormatter());
            }
            if (report.page_Cur == null)
            {
                report.Create();
            }
            response.ClearContent();
            response.ContentType = "application/pdf";
            MemoryStream ms = new MemoryStream(20000);

            report.formatter.Create(report, ms);
            ms.Close();

            response.BinaryWrite(ms.GetBuffer());
            response.End();
        }
Ejemplo n.º 12
0
        /// <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);
            }
        }
Ejemplo n.º 13
0
        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);
            }
        }
Ejemplo n.º 14
0
        //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);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="_Request"></param>
        /// <param name="_Response"></param>
        /// <param name="_fullPath">源文件路径</param>
        /// <param name="_speed"></param>
        /// <returns></returns>
        public static bool DownloadFile(System.Web.HttpRequest _Request, System.Web.HttpResponse _Response, string _fullPath, long _speed)
        {
            string _fileName = GetFileName(false, _fullPath);

            try
            {
                FileStream   myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                BinaryReader br     = new BinaryReader(myFile);
                try
                {
                    _Response.AddHeader("Accept-Ranges", "bytes");
                    _Response.Buffer = false;
                    long fileLength = myFile.Length;
                    long startBytes = 0;

                    double pack = 10240; //10K bytes
                    //int sleep = 200;   //每秒5次   即5*10K bytes每秒
                    int sleep = (int)Math.Floor(1000 * pack / _speed) + 1;
                    if (_Request.Headers["Range"] != null)
                    {
                        _Response.StatusCode = 206;
                        string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                        startBytes = Convert.ToInt64(range[1]);
                    }
                    _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                    _Response.AddHeader("Connection", "Keep-Alive");
                    _Response.ContentType = "application/octet-stream";
                    _Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                    br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                    int maxCount = (int)Math.Floor((fileLength - startBytes) / pack) + 1;

                    for (int i = 0; i < maxCount; i++)
                    {
                        if (_Response.IsClientConnected)
                        {
                            _Response.BinaryWrite(br.ReadBytes(int.Parse(pack.ToString())));
                            System.Threading.Thread.Sleep(sleep);
                        }
                        else
                        {
                            i = maxCount;
                        }
                    }
                }
                catch
                {
                    return(false);
                }
                finally
                {
                    br.Close();
                    myFile.Close();
                }
            }
            catch
            {
                return(false);
            }
            return(true);
        }
Ejemplo n.º 16
0
        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;
            }
        }
Ejemplo n.º 17
0
        /// <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);
        }