Clear() public method

public Clear ( ) : void
return void
示例#1
0
        /// <summary>
        /// Datatable数据填充如excel
        /// </summary>
        /// <param name="filename">excel文件名</param>
        /// <param name="dt"> 数据源</param>
        /// <param name="Response"> response响应</param>
        ///  <param name="headerStr"> 表头标题</param>
        public static void DataTableToExcel(string filename, DataTable dt, string sheetname, HttpResponse Response, string headerStr)
        {
            MemoryStream ms = StreamData(dt, sheetname, headerStr) as MemoryStream; //as MemoryStream  as用作转换,此处可以省略
            try
            {

                Response.Clear();
                Response.ContentType = "application/vnd.ms-excel";
                Response.ContentEncoding = Encoding.UTF8;
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename + ".xls"));
                Response.AddHeader("content-length", ms.Length.ToString());
                Byte[] data = ms.ToArray(); //文件写入采用二进制流的方式。所以此处要转换为字节数组
                Response.BinaryWrite(data);
            }
            catch
            {
                Response.Clear();
                Response.ClearHeaders();
                Response.Write("<script language=javascript>alert( '导出Excel错误'); </script>");
            }
            Response.Flush();
            Response.Close();
            Response.End();
            ms = null;
        }
示例#2
0
    public string CreateExcelFile(System.Web.HttpResponse Response, DataTable dt, string FileName)
    {
        string ans = "Download Fail!!!";

        try
        {
            GridView gv = new GridView();
            gv.DataSource = dt;
            gv.DataBind();
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + FileName + ".xls");
            Response.ContentType = "application/vnd.ms-excel";     //For xls
            StringWriter   sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            gv.RenderControl(hw);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
            ans = "Download Successfully!!!";
        }
        catch (Exception Ex)
        {
            ExceptionLogging.SendErrorToText(Ex);
        }
        return(ans);
    }
示例#3
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            List <EvaluacionEntidades.Empleados> list;
            if (!string.IsNullOrEmpty(Request.QueryString["idadmin"]))
            {
                DateTime?inicio = null;
                if (!string.IsNullOrEmpty(Request.QueryString["inicio"]))
                {
                    inicio = DateTime.Parse(Request.QueryString["inicio"]);
                }
                DateTime?fin = null;
                if (!string.IsNullOrEmpty(Request.QueryString["fin"]))
                {
                    fin = DateTime.Parse(Request.QueryString["fin"]);
                }
                int?idSuper = null;
                if (!string.IsNullOrEmpty(Request.QueryString["supervisorid"]))
                {
                    idSuper = int.Parse(Request.QueryString["supervisorid"]);
                }
                list = EvaluacionBL.EmpleadosBL.GetEmpleadoAdmin(int.Parse(Request.QueryString["idadmin"]), Request.QueryString["pais"], inicio, fin, Request.QueryString["departamento"], Request.QueryString["estado"], idSuper);
            }
            else
            {
                list = EvaluacionBL.EmpleadosBL.GetEmpleadosSupervisados(int.Parse(Request.QueryString["idSupervisor"]));
            }
            if (list != null && list.Count > 0)
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.ClearContent();
                response.ClearHeaders();

                //Tipo de contenido para forzar la descarga
                response.ContentType    = "application/octet-stream";
                Response.HeaderEncoding = System.Text.Encoding.Default;
                response.AddHeader("Content-Disposition", "attachment; filename=" + "EmpleadosDesempeño.xlsx");
                System.IO.MemoryStream grilla = Helpers.funcionesGenerales.ConvierteCSVEmpleados(list);
                // System.Text.Encoding encoding = new System.Text.UTF8Encoding();
                // byte[] bufferAux = grilla.ToArray();
                // byte[] buffer;
                //System.Text.Encoding utf8 = new System.Text.UTF8Encoding();
                // System.Text.Encoding win1252 = System.Text.Encoding.GetEncoding(1252);
                // buffer = System.Text.Encoding.Convert(utf8,win1252,bufferAux);
                //while (mContador < grilla.Length)
                //{
                //    buffer[mContador] = Chr grilla.Substring(mContador,1) Strings.Asc(Strings.Mid(pCSV, mContador + 1, 1));
                //    mContador = mContador + 1;
                //}

                //Envia los bytes
                response.BinaryWrite(grilla.ToArray());
                response.End();
            }
        }
        catch (Exception ex)
        { }
    }
示例#4
0
        /// <summary>
        /// Gets the URL represented by the named route.
        /// </summary>
        /// <param name="response">The HTTP context response.</param>
        /// <param name="routeName">The route name.</param>
        /// <returns>The generated URL.</returns>
        public static string GetByRouteName(HttpResponse response, string routeName)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }

            if (String.IsNullOrEmpty(routeName))
            {
                throw new ArgumentNullException("routeName");
            }

            VirtualPathData pathData = RouteTable.Routes.GetVirtualPath(null, routeName, new RouteValueDictionary());

            if (pathData != null && !String.IsNullOrEmpty(pathData.VirtualPath))
            {
                return pathData.VirtualPath;
            }

            response.Clear();
            response.StatusCode = (int) HttpStatusCode.NotFound;
            response.StatusDescription = String.Format(CultureInfo.InvariantCulture, Resources.Global.InvalidNamedRoute, routeName);

            return null;
        }
        public void Genratepdf1(string str_Url, string filename)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfConverter_Transcrpit = new PdfConverter();
                string       temp1 = "";
                pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";

                PdfDocumentOptions docopt = new PdfDocumentOptions();
                pdfConverter_Transcrpit.PageWidth  = 1100;
                pdfConverter_Transcrpit.PageHeight = 500;
                byte[] downloadBytes = pdfConverter_Transcrpit.GetPdfFromUrlBytes(str_Url);
                pdfConverter_Transcrpit.SavePdfFromUrlToFile(str_Url, "D:\\LMS2.0Final\\LMS\\ABN\\pdfs\\test1.pdf");
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + filename + ".pdf" + "; size=" + downloadBytes.Length.ToString());
                response.Flush();
                response.BinaryWrite(downloadBytes);
                response.Flush();
                response.End();
            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
        public void Genratepdftext(string text, string fname)
        {
            try
            {
                string temp_path = "";

                PdfConverter pdfConverter_Transcrpit = new PdfConverter();
                string       temp1 = "";
                pdfConverter_Transcrpit.LicenseKey = "eVJIWUtLWUtZTFdJWUpIV0hLV0BAQEA=";
                byte[] downloadBytes             = pdfConverter_Transcrpit.GetPdfBytesFromHtmlString(text);
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.AddHeader("Content-Type", "binary/octet-stream");
                response.AddHeader("Content-Disposition", "attachment; filename=" + fname + ".pdf" + "; size=" + downloadBytes.Length.ToString());
                response.Flush();
                response.BinaryWrite(downloadBytes);
                response.Flush();
                response.End();
            }
            catch (Exception EX)
            {
                //return "";
                throw EX;
            }
        }
示例#7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HtmlToPdf.Options.PageSize   = PdfPageSizes.A4;// new SizeF(PdfPageSizes.A4.Height, PdfPageSizes.A4.Width);
            HtmlToPdf.Options.OutputArea = new RectangleF(0.05f, 0.07f, 8.17f, 12f);



            MemoryStream ms       = new MemoryStream();
            string       fileName = "ANGLO-EASTERN SHIP MANAGEMENT";
            var          watch    = System.Diagnostics.Stopwatch.StartNew();

            HtmlToPdf.ConvertUrl("D:\\" + fileName + ".html", ms);
            watch.Stop();
            //HtmlToPdf.ConvertUrl("D:\\HtmlContentForPdf.html", "D:\\result.pdf");
            byte[] bPDFBytes          = ms.ToArray();
            var    timeTakenToConvert = watch.ElapsedMilliseconds;

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "application/pdf");
            response.AddHeader("Content-Disposition", "attachment; filename=Eo_" + fileName + "_" + timeTakenToConvert + ".pdf; size=" + bPDFBytes.Length.ToString());
            response.Flush();
            response.BinaryWrite(bPDFBytes);
            response.Flush();
            response.End();
        }
    /// <summary>
    /// 导入数据,保存文档
    /// </summary>
    /// <param name="tab"></param>
    /// <param name="fileName"></param>
    /// <param name="typeName"></param>
    /// <param name="styleText"></param>
    private void TableExport(System.Web.UI.HtmlControls.HtmlGenericControl tab, string fileName, string typeName, bool isFireFox)
    {
        System.Web.HttpResponse httpResponse = _InvokePage.Response;
        httpResponse.Clear();
        httpResponse.Buffer = true;

        httpResponse.Charset = "gb2312";// "GB2312";
        //Response.Charset = "UTF-8";
        httpResponse.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");

        if (isFireFox == true)
        {
            fileName = "\"" + fileName + "\"";
            httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
        }
        else
        {
            httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8).ToString());
        }

        httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        httpResponse.ContentType     = typeName;
        _InvokePage.EnableViewState  = false;
        StringWriter tw = new StringWriter();

        System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
        tab.RenderControl(hw);
        // httpResponse.Write(styleText);
        httpResponse.Write(tw.ToString());
        httpResponse.End();
    }
示例#9
0
        private void Descargar(ArrayList arrText)
        {
            string fic = Server.MapPath(@"TextFiles/polizavta.txt");

            StreamWriter sw = new StreamWriter(fic, false, Encoding.UTF8);

            if (arrText.Count > 0)
            {
                for (int i = 0; i < arrText.Count; i++)
                {
                    sw.WriteLine(arrText[i].ToString());
                }
            }
            sw.Close();

            //String FileName = "BulkAdd_Instructions.txt";
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=polizavta.txt;");
            response.TransmitFile(fic);
            response.Flush();
            response.End();
        }
示例#10
0
        public static void SendPosterToBrowser( PosterBuilder.Builder pb, HttpResponse resp, string posterFilename, PosterBuilder.ImgFormat.SupportedTypes outputFormat)
        {
            string filename = BuildFilename(posterFilename, outputFormat);

            resp.Clear();
            // Ensure caching is off naturally
            resp.CacheControl = "no-cache";

            resp.ContentType = PosterBuilder.ImgFormat.ToMimeType(outputFormat);
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);

            // Call our image with our amendments and have it save to the response so we can send it back
            Bitmap bmp = pb.Render();

            // Have the Poster build our new image and save the result to the outgoing response
            // ... have to do all this with MemoryStreams as PNG doesn't like being saved directly to HttpResponse.OutputStream
            // ... may as well do the same for all image types and be consistent
            using (Bitmap bitmap = pb.Render()) {

                using (MemoryStream ms = new MemoryStream()) {
                    ImageFormat outFmt = PosterBuilder.ImgFormat.ToImageFormat(outputFormat);

                    bmp.Save(ms, outFmt);

                    ms.WriteTo(resp.OutputStream);
                } // using ms

            } // using pb

            // And of course, clear up after ourselves
            pb.Dispose();
            resp.End();
        }
示例#11
0
        public ActionResult Download(ModelFile file)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    GenerateFile(file.MaxValue, file.FileAmount);

                    var fileName = "GenerateFile.txt";

                    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("~/GenerateFile.txt"));
                    response.Flush();
                    response.End();
                }
            }
            catch
            {
                return(View("Download"));
            }

            return(View());

            //return null;
        }
示例#12
0
 public static void Convert(System.Data.DataSet ds, string TableName, System.Web.HttpResponse response, string ExcelName)
 {
     //let's make sure the table name exists
     //if it does not then call the default method
     if (ds.Tables[TableName] == null)
     {
         Convert(ds, response, ExcelName);
     }
     //we've got a good table so
     //let's clean up the response.object
     response.Clear();
     response.Charset = "";
     //set the response mime type for excel
     response.ContentType = "application/vnd.ms-excel";
     //create a string writer
     System.IO.StringWriter stringWrite = new System.IO.StringWriter();
     //create an htmltextwriter which uses the stringwriter
     System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
     //instantiate a datagrid
     System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
     //set the datagrid datasource to the dataset passed in
     dg.DataSource = ds.Tables[TableName];
     //bind the datagrid
     dg.DataBind();
     //tell the datagrid to render itself to our htmltextwriter
     dg.RenderControl(htmlWrite);
     //all that's left is to output the html
     response.Write(stringWrite.ToString());
     response.End();
 }
示例#13
0
        private void ExportDivContentToPDF()
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            try
            {
                // create an API client instance
                string          userName = ConfigurationManager.AppSettings["pdfcrowdUsername"].ToString();
                string          APIKey   = ConfigurationManager.AppSettings["pdfcrowdAPIKey"].ToString();
                pdfcrowd.Client client   = new pdfcrowd.Client(userName, APIKey);

                // convert a web page and write the generated PDF to a memory stream
                MemoryStream Stream = new MemoryStream();
                //client.convertURI("http://www.google.com", Stream);

                // set HTTP response headers
                Response.Clear();
                Response.AddHeader("Content-Type", "application/pdf");
                Response.AddHeader("Cache-Control", "max-age=0");
                Response.AddHeader("Accept-Ranges", "none");
                Response.AddHeader("Content-Disposition", "attachment; filename=TigerReservePdfExport.pdf");
                System.IO.StringWriter       stringWrite1 = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter htmlWrite1   = new HtmlTextWriter(stringWrite1);
                MainContent.RenderControl(htmlWrite1);
                client.convertHtml(stringWrite1.ToString(), Stream);
                // send the generated PDF
                Stream.WriteTo(Response.OutputStream);
                Stream.Close();
                Response.Flush();
                Response.End();
            }
            catch (pdfcrowd.Error why)
            {
                Response.Write(why.ToString());
            }
        }
示例#14
0
        /// <summary>
        /// 导出EXCEL(HTML格式的)
        /// </summary>
        /// <param name="ds">要导出的DataSet</param>
        /// <param name="fileName"></param>
        public static void CreateEXCEL(DataSet ds, string fileName)
        {
            System.Web.UI.WebControls.DataGrid dg = new DataGrid();
            dg.DataSource = ds;
            dg.DataBind();

            for (int i = 0; i < dg.Items.Count; i++)
            {
                for (int j = 0; j < dg.Items[i].Cells.Count; j++)
                {
                    dg.Items[i].Cells[j].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }

            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            Response.Clear();
            Response.Buffer  = true;
            Response.Charset = "GB2312";
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(fileName + ".xls", System.Text.Encoding.UTF8) + ";charset=GB2312");
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); //设置输出流为简体中文
            Response.ContentType     = "application/ms-excel";                     //设置输出文件类型为excel文件。
            System.Globalization.CultureInfo   myCItrad        = new System.Globalization.CultureInfo("ZH-CN", true);
            System.IO.StringWriter             oStringWriter   = new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter       oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            System.Web.UI.WebControls.DataGrid DG = dg;
            DG.RenderControl(oHtmlTextWriter);
            Response.Write(oStringWriter.ToString());
            Response.End();
        }
示例#15
0
        /// <summary>
        /// Creates a text version (mostly) of the Diagnostics data that is sent via the HttpResponse to the client.
        /// </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 btnDumpDiagnostics_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=RockDiagnostics-" + System.Environment.MachineName + ".txt");
            response.Charset = "";

            ResponseWrite("Version:", lRockVersion.Text, response);
            ResponseWrite("Database:", lDatabase.Text.Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Execution Location:", lExecLocation.Text, response);
            ResponseWrite("Migrations:", GetLastMigrationData().Replace("<br />", Environment.NewLine.ToString()), response);
            ResponseWrite("Cache:", lCacheOverview.Text.Replace("<br />", Environment.NewLine.ToString()), response);;
            ResponseWrite("Routes:", lRoutes.Text.Replace("<br />", Environment.NewLine.ToString()), response);

            // Last and least...
            ResponseWrite("Server Variables:", "", response);
            foreach (string key in Request.ServerVariables)
            {
                ResponseWrite(key, Request.ServerVariables[key], response);
            }

            response.Flush();
            response.End();
        }
示例#16
0
        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                    case ".mp3":
                        response.ContentType = "audio/mpeg3";
                        break;
                    case ".mpeg":
                        response.ContentType = "video/mpeg";
                        break;
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".bmp":
                        response.ContentType = "image/bmp";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".doc":
                        response.ContentType = "application/msword";
                        break;
                    case ".css":
                        response.ContentType = "text/css";
                        break;
                    case ".html":
                        response.ContentType = "text/html";
                        break;
                    case ".htm":
                        response.ContentType = "text/html";
                        break;
                    case ".swf":
                        response.ContentType = "application/x-shockwave-flash";
                        break;
                    case ".exe":
                        response.ContentType = "application/octet-stream";
                        break;
                    case ".inf":
                        response.ContentType = "application/x-texinfo";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
 public void PrepareResponse(HttpResponse httpResponse)
 {
     httpResponse.Clear();
     httpResponse.ContentType = "text/tab-separated-values";
     httpResponse.AddHeader("content-disposition", "attachment; filename=\"" + "export" + ".tsv\"");
     httpResponse.BufferOutput = false;
 }
        public void ExportDataGridToExcel(System.Web.UI.Control ctrl, System.Web.HttpResponse response)
        {
            response.Clear();
            response.Buffer = true;
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("content-disposition", "attachment;filename=Flash Report.xls");
            response.Charset     = "";
            this.EnableViewState = false;

            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            //this.ClearControls(ctrl);
            ctrl.RenderControl(oHtmlTextWriter);

            // set content type and character set to cope with european chars like the umlaut.
            response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">" + Environment.NewLine);

            // add the style props to get the page orientation
            response.Write(AddExcelStyling());
            response.Write("<span style='font-size: 11pt; font-family: Arial; font-weight:bold;'>" + "REPORTE EXCESO DE INVENTARIO" + indicadorTexto + "</span>");
            response.Write("<br>");
            response.Write("<span style='font-size: 10pt; font-family: Arial;'>" + lblLeyenda.Text + "</span>");
            response.Write("<br>");
            response.Write("<br>");
            response.Write(oStringWriter.ToString());
            response.Write("</body>");
            response.Write("</html>");

            response.End();
        }
示例#19
0
文件: HttpImg.cs 项目: Xiaoyuyexi/LMS
        private void Real(HttpResponse response, HttpRequest request)
        {
            if (File.Exists(request.PhysicalPath))
            {
                FileInfo file = new System.IO.FileInfo(request.PhysicalPath);
                response.Clear();
                response.AddHeader("Content-Disposition", "filename=" + file.Name);
                response.AddHeader("Content-Length", file.Length.ToString());
                string fileExtension = file.Extension.ToLower();
                switch (fileExtension)
                {
                   
                    case ".jpg":
                        response.ContentType = "image/jpeg";
                        break;
                    case ".gif":
                        response.ContentType = "image/gif";
                        break;
                    case ".png":
                        response.ContentType = "image/png";
                        break;
                    default:
                        response.ContentType = "application/octet-stream";
                        break;
                }

                response.WriteFile(file.FullName);
                response.End();
            }
            else
            {
                response.Write("File Not Exists");
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            try
            {
                //Save a trial user to the database
                string version = ConfigurationManager.AppSettings["Version"];

                if (string.IsNullOrEmpty(version))
                {
                    //throw error and return
                    return;
                }

                string trialDownloadPath = "~\\Releases\\" + version + "\\Utility\\Downloadables\\Trial\\SimpleSqliteUtility.zip";

                //Transmit the files
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.ClearContent();
                response.Clear();
                response.ContentType = "text/plain";
                response.AddHeader("Content-Disposition", "attachment; filename=SimpleSqliteUtility.zip;");
                response.TransmitFile(trialDownloadPath);
                response.Flush();
                response.End();
            }
            catch (Exception ex)
            {
                //Report error in an email
            }
        }
示例#21
0
        public void ProcessRequest(HttpContext context)
        {
            Int32  userid        = SessionData.UserID;
            String uploadFileDir = ConfigurationManager.AppSettings["UploadFolderPath"];

            System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
            string startDate      = request.QueryString["startDate"];
            string endDate        = request.QueryString["endDate"];
            string uploadfilepath = MppUtility.GetFilelocation(userid, uploadFileDir, "bulk");
            string fileName       = ConfigurationManager.AppSettings["filename"];
            string fileName1      = fileName.PadRight(29) + MppUtility.DateFormat(Convert.ToDateTime(startDate), 2) + "-" + MppUtility.DateFormat(Convert.ToDateTime(endDate), 2) + ".csv";
            string filePath       = Path.Combine(uploadfilepath, fileName1);
            bool   test           = System.IO.File.Exists(filePath);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            if (System.IO.File.Exists(filePath))
            {
                response.ClearContent();
                response.Clear();
                byte[] Content = System.IO.File.ReadAllBytes(filePath);
                response.ContentType = "text/csv";
                response.AddHeader("content-disposition", "attachment; filename=" + fileName1 + ".csv");
                response.BufferOutput = true;
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                response.OutputStream.Write(Content, 0, Content.Length);
                response.Flush();
                response.End();
            }
            else
            {
                response.Redirect("ShowStatus.html");
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            DBConn oConn = new DBConn();

            if (oConn.Open())
            {
                Web oWeb = new Web();

                //cProductosContrato oProductosContrato = new cProductosContrato(ref oConn);
                //oProductosContrato.NumContrato = oWeb.GetData("pCodContrato");
                //DataTable dtProdCont = oProductosContrato.GetByExcel();

                cRoyaltyContrato oRoyaltyContrato = new cRoyaltyContrato(ref oConn);
                oRoyaltyContrato.NumContrato = oWeb.GetData("pCodContrato");
                DataTable dtProdCont = oRoyaltyContrato.GetByExcel();
                oConn.Close();

                System.Web.HttpResponse oResponse = System.Web.HttpContext.Current.Response;

                oResponse.Clear();
                oResponse.AddHeader("content-disposition", "attachment;filename=FileName.csv");
                oResponse.Charset = "";
                oResponse.Cache.SetCacheability(HttpCacheability.NoCache);
                oResponse.ContentType = "application/vnd.ms-excel";

                oResponse.Output.Write(ToCSV(dtProdCont));
                oResponse.Flush();
                oResponse.End();
            }
        }
示例#23
0
        public void ExportToExcel(DataTable dataTable, HttpResponse response)
        {
            // Create a dummy GridView
            GridView GridView1 = new GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = dataTable;
            GridView1.DataBind();
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition", "attachment;filename=DataTable.xls");
            response.Charset = "";
            response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; (i
                        <= (GridView1.Rows.Count - 1)); i++)
            {
                // Apply text style to each Row
                GridView1.Rows[i].Attributes.Add("class", "textmode");
            }

            GridView1.RenderControl(hw);
            // style to format numbers to string
            string style = "<style> .textmode{mso-number-format:\\@;}</style>";
            response.Write(style);
            response.Output.Write(sw.ToString());
            response.Flush();
            response.End();
        }
示例#24
0
        protected void btnSaoLuuDuLieu_Click(object sender, EventArgs e)
        {
            dtSetting dt      = new dtSetting();
            DataTable db      = dt.LayTenDatabase();
            DataRow   dr      = db.Rows[0];
            string    Name    = dr["DatabaseName"].ToString();
            string    CD      = Server.MapPath("~/Uploads/");
            string    TenFile = DateTime.Now.ToString("ddMMyyyy") + "_" + Name + ".Bak";

            data = new dtDuLieu();
            //FileInfo newFile = new FileInfo(Server.MapPath("~/Uploads/" + TenFile));
            //newFile.Delete();
            string[] Files = Directory.GetFiles(Server.MapPath("~/Uploads/"));

            foreach (string file in Files)
            {
                File.Delete(file);
            }
            data.SaoLuuCSDL(CD, Name);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.ClearContent();
            response.Clear();
            response.ContentType = "text/plain";
            response.AddHeader("Content-Disposition", "attachment; filename=" + TenFile + ";");
            response.TransmitFile(Server.MapPath("~/Uploads/" + TenFile));
            response.Flush();
            response.End();
        }
示例#25
0
        /// <summary>
        /// Exporta la información a Excel.
        /// </summary>
        /// <param name="response">HttpResponse actual.</param>
        /// <param name="data">Datos a exportar.</param>
        /// <param name="nombreArchivo">Nombre del archivo Excel</param>
        public static void ExportToExcelFile(HttpResponse response, DataView data, string nombreArchivo)
        {
            var dg = new DataGrid { DataSource = data };
            dg.DataBind();

            response.Clear();
            response.Buffer = true;

            //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
            response.AddHeader("Content-Disposition", "filename=" + nombreArchivo);
            response.ContentType = "application/vnd.ms-excel";
            response.Charset = "UTF-8";
            response.ContentEncoding = System.Text.Encoding.Default;

            var stringWriter = new StringWriter();
            var htmlWriter = new HtmlTextWriter(stringWriter);
            dg.RenderControl(htmlWriter);

            response.Write(stringWriter.ToString());
            //resp.Flush();
            try
            {
                response.End();
            }
            catch (Exception ex)
            {
                ISException.RegisterExcepcion(ex);
                throw ex;
            }
        }
示例#26
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)
        {
            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";
            byte[] data1 = new byte[stream.Length];
            stream.Read(data1, 0, data1.Length);
            stream.Close();
            Response.BinaryWrite(data1);
            Response.Flush();


            return(true);
        }
示例#27
0
 private void DoExportForHishop(string csvFilename, string imagePath, System.Collections.Generic.List <ExportToLocal.ProductDetail> list)
 {
     using (System.IO.FileStream fileStream = new System.IO.FileStream(csvFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
     {
         string productCSVForEcdev = this.GetProductCSVForHishop(imagePath, list);
         System.Text.UnicodeEncoding unicodeEncoding = new System.Text.UnicodeEncoding();
         //UTF8Encoding unicodeEncoding = new UTF8Encoding();
         int    byteCount = unicodeEncoding.GetByteCount(productCSVForEcdev);
         byte[] preamble  = unicodeEncoding.GetPreamble();
         byte[] array     = new byte[preamble.Length + byteCount];
         System.Buffer.BlockCopy(preamble, 0, array, 0, preamble.Length);
         unicodeEncoding.GetBytes(productCSVForEcdev.ToCharArray(), 0, productCSVForEcdev.Length, array, preamble.Length);
         fileStream.Write(array, 0, array.Length);
     }
     using (ZipFile zipFile = new ZipFile(System.Text.Encoding.Default))
     {
         System.IO.DirectoryInfo directoryInfo = new System.IO.DirectoryInfo(imagePath);
         zipFile.CompressionLevel = CompressionLevel.Default;
         zipFile.AddFile(csvFilename, "");
         zipFile.AddDirectory(directoryInfo.FullName, directoryInfo.Name);
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.ContentType     = "application/x-zip-compressed";
         response.ContentEncoding = this._encoding;
         response.AddHeader("Content-Disposition", "attachment; filename=" + directoryInfo.Name + ".zip");
         response.Clear();
         zipFile.Save(response.OutputStream);
         this._workDir.Delete(true);
         response.Flush();
         response.Close();
     }
 }
示例#28
0
        public Document GetErrorDocument(
            Boolean openCloseConnection, Boolean addContentDisposition,
            String fileName,
            System.Web.HttpResponse webResponse, System.Web.HttpCookie cookie,
            DocTemplateVers.Domain.DTO.ServiceExport.DTO_Settings settings,
            IList <DocTemplateVers.Domain.DTO.ServiceExport.DTO_Signature> Signatures)
        {
            if (openCloseConnection)
            {
                webResponse.Clear();
            }
            if (cookie != null)
            {
                webResponse.AppendCookie(cookie);
            }
            if (addContentDisposition || openCloseConnection)
            {
                webResponse.AddHeader("Content-Disposition", "attachment; filename=" + HtmlCheckFileName(fileName) + "." + ExportFileType.pdf.ToString());
                webResponse.ContentType = "application/pdf";
            }

            Document doc = ExportTo(settings, webResponse.OutputStream, true, Signatures, "");

            if (doc != null && openCloseConnection)
            {
                webResponse.End();
            }
            return(doc);
        }
示例#29
0
 public static void Convert(System.Data.DataSet ds, int TableIndex, System.Web.HttpResponse response, string ExcelName)
 {
     //lets make sure a table actually exists at the passed in value
     //if it is not call the base method
     if (TableIndex > ds.Tables.Count - 1)
     {
         Convert(ds, response, ExcelName);
     }
     //we've got a good table so
     //let's clean up the response.object
     response.Clear();
     response.Charset = "";
     response.AddHeader("Content-Disposition", "attachment;filename=Shilpa.xls");
     //set the response mime type for excel
     response.ContentType = "application/vnd.ms-excel";
     //create a string writer
     System.IO.StringWriter stringWrite = new System.IO.StringWriter();
     //create an htmltextwriter which uses the stringwriter
     System.Web.UI.HtmlTextWriter htmlWrite = new System.Web.UI.HtmlTextWriter(stringWrite);
     //instantiate a datagrid
     System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();
     //set the datagrid datasource to the dataset passed in
     dg.DataSource = ds.Tables[TableIndex];
     //bind the datagrid
     dg.DataBind();
     //tell the datagrid to render itself to our htmltextwriter
     dg.RenderControl(htmlWrite);
     //all that's left is to output the html
     response.Write(stringWrite.ToString());
     response.End();
 }
示例#30
0
        protected void Page_Load(object sender, EventArgs e)
        {
            String FileName = null;

            switch ((string)Session["filetype"])
            {
            case ".txt":
                FileName = "CompressedText.cmx";
                break;

            case ".JPG":
            case ".jpg":
                FileName = "CompressedImage.cmi";
                break;

            case ".cmi":
                FileName = "ExtractedImage.jpg";
                break;

            case ".cmx":
                FileName = "ExtractedText.txt";
                break;
            }

            string fn = Server.MapPath("resources/" + FileName);

            System.Web.HttpResponse responses = System.Web.HttpContext.Current.Response;
            responses.ClearContent();
            responses.Clear();
            responses.ContentType = "text/plain";
            responses.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
            responses.TransmitFile(fn);
            responses.Flush();
            responses.End();
        }
示例#31
0
        // Function  : Export_with_XSLT_Web
        // Arguments : dsExport, sHeaders, sFileds, FormatType, FileName
        // Purpose   : Exports dataset into CSV / Excel format

        private void Export_with_XSLT_Web(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
        {
            try
            {
                // Appending Headers
                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);
                }

                // XSLT to use for transforming this dataset.
                MemoryStream  stream = new MemoryStream( );
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.Default);
                CreateStylesheet(writer, sHeaders, sFileds, FormatType);
                writer.Flush( );
                stream.Seek(0, SeekOrigin.Begin);
                XmlDocument xsl = new XmlDocument();
                xsl.Load(stream);

                //XslTransform xslTran = new XslTransform();
                //xslTran.Load(new XmlTextReader(stream), null, null);
                //System.IO.StringWriter  sw = new System.IO.StringWriter();
                //xslTran.Transform(xmlDoc, null, sw, null);

                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);

                StringWriter         sw  = new StringWriter();
                XmlTextWriter        xtw = new XmlTextWriter(sw);
                XslCompiledTransform t   = new XslCompiledTransform();
                t.Load((IXPathNavigable)xsl, null, null);
                t.Transform((IXPathNavigable)xmlDoc, xtw);

                //Writeout the Content
                response.Write(sw.ToString());
                sw.Close();
                xtw.Close();
                writer.Close();
                stream.Close();
                response.End();
                sw.Dispose();
                stream.Dispose();
            }
            catch (ThreadAbortException Ex)
            {
                string ErrMsg = Ex.Message;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
示例#32
0
        public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head)
        {
            System.IO.StringWriter       sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);

            FrontDecorator(hw);
            if (Title != "")
            {
                hw.Write(Title + "<br>");
            }
            if (Head != "")
            {
                hw.Write(Head + "<br>");
            }

            DataGrid2Excel.EnableViewState = false;
            DataGrid2Excel.RenderControl(hw);

            RearDecorator(hw);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Buffer          = true;
            response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
            response.ContentType     = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            response.Charset = "gb2312";
            response.Write(sw.ToString());
            response.End();
        }
示例#33
0
        public void ExportToCSV(DataTable dataTable, HttpResponse response)
        {
            response.Clear();
            response.Buffer = true;
            response.AddHeader("content-disposition",
                "attachment;filename=DataTable.csv");
            response.Charset = "";
            response.ContentType = "application/text";

            StringBuilder sb = new StringBuilder();
            for (int k = 0; k < dataTable.Columns.Count; k++)
            {
                //add separator
                sb.Append(dataTable.Columns[k].ColumnName + ',');
            }
            //append new line
            sb.Append("\r\n");
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                for (int k = 0; k < dataTable.Columns.Count; k++)
                {
                    //add separator
                    sb.Append(dataTable.Rows[i][k].ToString().Replace(",", ";") + ',');
                }
                //append new line
                sb.Append("\r\n");
            }
            response.Output.Write(sb.ToString());
            response.Flush();
            response.End();
        }
示例#34
0
 private static void WriteError(string error, HttpResponse response)
 {
     response.Clear();
     response.Status = "Internal Server Error";
     response.StatusCode = 500;
     response.Output.WriteLine(error);
 }
        protected void btnPDF_Click222(object sender, EventArgs e)
        {
            string downloadName = "Report";

            byte[] downloadBytes = null;
            downloadName += ".pdf";
            PdfConverter pdfConverter = new PdfConverter();

            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
            pdfConverter.PdfStandardSubset = PdfStandardSubset.Full;
            pdfConverter.PdfDocumentOptions.AutoSizePdfPage = true;
            pdfConverter.PdfDocumentOptions.EmbedFonts      = true;
            pdfConverter.PdfDocumentOptions.BottomMargin    = 80;
            pdfConverter.PdfDocumentOptions.TopMargin       = 50;

            string url = string.Format("http://{0}/ExamOnline/ExamPaperStorage/ExamPaperView.aspx?epid=39&isPdf=1", Request.Url.Host);

            downloadBytes = pdfConverter.GetPdfBytesFromUrl(url);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.AddHeader("Content-Type", "binary/octet-stream");
            response.AddHeader("Content-Disposition",
                               "attachment; filename=" + downloadName + "; size=" + downloadBytes.Length.ToString());
            response.Flush();
            response.BinaryWrite(downloadBytes);
            response.Flush();
            response.End();
        }
示例#36
0
        public void DownLoadFlash(FlashInfo flashInfo, System.Web.HttpResponse Response)
        {
            var basePath = VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath);

            string fileURL = "";

            if (flashInfo.FlashVersion == "Chrome")
            {
                fileURL = HttpContext.Current.Server.MapPath((basePath + "Login/Temp/flashplayerPPAPI_25.0.0.127.exe"));//文件路径,可用相对路径
            }
            else
            {
                fileURL = HttpContext.Current.Server.MapPath((basePath + "Login/Temp/flashplayerNPAPI_26.0.0.131.exe"));//文件路径,可用相对路径
            }

            try
            {
                FileInfo fileInfo = new FileInfo(fileURL);
                Response.Clear();
                Response.AddHeader("content-disposition", "attachment;filename=" + HttpContext.Current.Server.UrlEncode(fileInfo.Name.ToString())); //文件名
                Response.AddHeader("content-length", fileInfo.Length.ToString());                                                                   //文件大小
                Response.ContentType     = "application/octet-stream";
                Response.ContentEncoding = System.Text.Encoding.Default;
                Response.WriteFile(fileURL);
            }
            catch (Exception ex)
            {
                flashInfo.result = "failed";
                flashInfo.msg    = "下载失败! \n" + ex.Message;
            }
        }
示例#37
0
 /// <summary>
 /// 发送PDF文件回浏览器端
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="ms"></param>
 /// <param name="encoding"></param>
 public static void SendFile(string fileName, MemoryStream ms, Encoding encoding = null)
 {
     fileName = (fileName + "").Replace(" ", "");
     encoding = encoding ?? Encoding.UTF8;
     if (ms != null && !string.IsNullOrEmpty(fileName))
     {
         System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
         response.Clear();
         response.Charset = encoding.BodyName;// "utf-8";
         if (!HttpContext.Current.Request.UserAgent.Contains("Firefox") && !HttpContext.Current.Request.UserAgent.Contains("Chrome"))
         {
             fileName = HttpUtility.UrlEncode(fileName, encoding);
         }
         response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
         //为了解决打开,导出NPOI生成的xlsx文件时,提示发现不可读取内容。
         if (!(fileName + "").ToLower().EndsWith(".xlsx"))
         {
             response.AddHeader("Content-Type", "application/octet-stream");
             response.BinaryWrite(ms.GetBuffer());
         }
         else
         {
             response.BinaryWrite(ms.ToArray());
         }
         ms.Close();
         ms = null;
         response.Flush();
         response.End();
     }
 }
        public ActionResult ExportCSV(string emailList)
        {
            string FilePath = Server.MapPath("/App_Data/");
            string FileName = "EmailList.csv";

            System.IO.File.WriteAllText(FilePath + FileName, emailList);

            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(FilePath + FileName);
            response.Flush();
            System.IO.File.Delete(FilePath + FileName); // Deletes the file on server

            response.End();
            List <string> listOfEmails = emailList.Split(',').ToList();

            foreach (var emailName in listOfEmails)
            {
                //Takes each email in list and searches for it on the JPStudents table and finds the associated ApplicationUserID.
                //Then calls the UpdateLatestContact method on each ApplicationUserID.
                var userId = db.JPStudents.Where(x => x.JPEmail == emailName).First().ApplicationUserId.ToString();
                UpdateLatestContact(userId);
            }
            return(RedirectToAction("Index"));
        }
示例#39
0
    public static void exportarExcel(string htmlString, System.Web.HttpResponse response)
    {
        StringBuilder sb = new StringBuilder();

        System.IO.StringWriter sw  = new System.IO.StringWriter(sb);
        HtmlTextWriter         htw = new HtmlTextWriter(sw);
        Page     page = new Page();
        HtmlForm form = new HtmlForm();

        try
        {
            page.EnableEventValidation = false;
            page.DesignerInitialize();
            page.Controls.Add(form);
            page.RenderControl(htw);
            response.Clear();
            response.Buffer      = true;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "inline;filename=Reporte.xls");
            string style = @"<style> .textmode { mso-number-format:\@; } .ancho{width:50%} .fechaformat{mso-number-format:\dd/mm/yyyy;} </style>";
            response.Write(style);
            response.Charset         = "utf-8";
            response.ContentEncoding = Encoding.UTF8;
            response.Write(htmlString);
            //'Response.End()
            response.Flush();
            response.SuppressContent = true;
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch (Exception)
        {
            throw;
        }
    }
示例#40
0
        public void ExportCSV(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response)
        {
            string        strFileName = "Report" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy") + System.DateTime.Now.Millisecond.ToString("0000");
            StringBuilder sb          = new StringBuilder();

            System.Web.UI.WebControls.GridViewRow grHeader = exportGV.HeaderRow;
            int counter = 0;

            foreach (System.Web.UI.WebControls.TableCell tc in grHeader.Cells)
            {
                sb.Append("\"" + exportGV.Columns[counter].HeaderText.Trim() + "\",");
                counter++;
            }
            sb.AppendLine();

            foreach (System.Web.UI.WebControls.GridViewRow gr in exportGV.Rows)
            {
                foreach (System.Web.UI.WebControls.TableCell tc in gr.Cells)
                {
                    sb.Append("\"" + getGridCellText(tc) + "\",");
                }
                sb.AppendLine();
            }

            Response.Clear();
            Response.ClearHeaders();
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment; filename=Export.csv");
            Response.ContentType = "text/csv";
            Response.AddHeader("Pragma", "public");
            Response.Write(sb.ToString());
            Response.End();
        }
示例#41
0
文件: CHelper.cs 项目: 0anion0/IBN
 public static void CloseIt(HttpResponse response)
 {
     response.Clear();
     response.Write("<script type=\"text/javascript\">");
     response.Write("window.close();");
     response.Write("</script>");
     response.End();
 }
示例#42
0
        public void SavePdf( HttpResponse response, string downloadfilename )
        {
            response.Clear();
            response.ContentType = "application/x-pdf";
            response.AddHeader("content-disposition", string.Format("attachment; filename={0}",downloadfilename));

            SavePdf(response.OutputStream);
        }
示例#43
0
		static void RedirectPermanent(HttpResponse response, string destination)
		{
			response.Clear();
			response.Status = "301 Moved Permanently";
			response.AddHeader("Location", destination);
			response.Flush();
			response.End();
		}
示例#44
0
 private static void PermanentRedirect(HttpResponse response, string location)
 {
     response.Clear();
     response.StatusCode = (int)HttpStatusCode.MovedPermanently;
     response.StatusDescription = "Moved Permanently";
     response.AddHeader("Location", location);
     response.End();
 }
示例#45
0
文件: ExcelHelper.cs 项目: mccj/FOMS
        public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)
        {
            var excelXml = GetExcelXml(dsInput, filename);
            response.Clear();
            response.AppendHeader("Content-Type", "application/vnd.ms-excel");
            response.AppendHeader("Content-Disposition", "attachment; filename=\"" + HttpContext.Current.Server.UrlEncode(filename) + "\"");

            response.Write(excelXml);
            response.Flush();
            response.End();
        }
示例#46
0
        public static bool ShowDownloadToolFile(HttpResponse httpResponse, NameValueCollection queryString, CommonUtils.AppSettingKey settingKey, out Exception message)
        {
            try
            {
                string fileName = queryString["DownloadToolFile"];

                if (string.IsNullOrEmpty(fileName))
                {
                    message = new Exception("Query string 'DownloadToolFile' missing from url.");
                    return false;
                }

                if (!File.Exists(fileName))
                {
                    message = new FileNotFoundException(string.Format(@"Failed to find file '{0}'.
                                                    Please ask your administrator to check whether the folder exists.", fileName));
                    return false;
                }

                httpResponse.Clear();
                httpResponse.ClearContent();

                //Response.OutputStream.f
                httpResponse.BufferOutput = true;
                httpResponse.ContentType = "application/unknown";
                httpResponse.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(fileName)));
                byte[] fileContent = File.ReadAllBytes(fileName);

                BinaryWriter binaryWriter = new BinaryWriter(httpResponse.OutputStream);
                binaryWriter.Write(fileContent, 0, fileContent.Length);
                binaryWriter.Flush();
                binaryWriter.Close();

                var dirName = Path.GetDirectoryName(fileName);

                if (dirName != null)
                {
                    //Delete any files that are older than 1 hour
                    Directory.GetFiles(dirName)
                        .Select(f => new FileInfo(f))
                        .Where(f => f.CreationTime < DateTime.Now.AddHours(-1))
                        .ToList()
                        .ForEach(f => f.Delete());
                }
            }
            catch (Exception ex)
            {
                message = ex;
                return false;
            }

            message = null;
            return true;
        }
示例#47
0
		public void Render(HttpResponse response)
		{
			string serializedItems = ToString();

			response.Clear();
			var calendarName = _calendarName.Replace(',', ' ');
			response.AppendHeader("Content-Disposition",
			                      String.Format("attachment; filename={0}.ics",
			                                    HttpUtility.UrlPathEncode(calendarName)));
			response.ContentType = "text/calendar";

			response.Write(serializedItems);
		}
        public void Process(HttpResponse response)
        {
            response.Clear();

            response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r"));
            response.AppendHeader("ETag", serverFingerprint.ETag);
            response.AppendHeader("Cache-Control", "private, max-age=0");

            response.ContentType = contentType;

            response.BinaryWrite(content);
            response.End();
        }
示例#49
0
 /// <summary>
 /// Downloads the latex from estimate.
 /// </summary>
 /// <param name="projectId">The project id.</param>
 /// <param name="maxPriority">The max priority.</param>
 /// <param name="response">The response.</param>
 public void DownloadLatexFromEstimate(int? projectId
     , int? maxPriority
     , HttpResponse response)
 {
     response.Clear();
     response.AddHeader
         ("Content-Disposition"
         , "attachment;filename=estimate.tex");
     response.ContentType = "application/x-latex";
     response.Write(GetLatexFromEstimate
         (projectId, maxPriority));
     response.Flush();
     response.End();
 }
示例#50
0
 public static void DataGridToExcel(HttpResponse myResponse, DataGrid dg, string fileName, int numRowLock)
 {
     myResponse.Clear();
     myResponse.Buffer = true;
     myResponse.ContentType = "application/vnd.ms-excel";
     myResponse.Charset = "";
     myResponse.AddHeader("content-disposition", "attachment;filename=" + fileName + ".xls");
     StringWriter writer = new StringWriter();
     HtmlTextWriter writer2 = new HtmlTextWriter(writer);
     dg.HeaderStyle.Height = 30;
     dg.HeaderStyle.BackColor = Color.LightSlateGray;
     MassageData(dg);
     dg.RenderControl(writer2);
     myResponse.End();
 }
示例#51
0
        public ResponseFile()
        {
            response = HttpContext.Current.Response;

            // 清空当前 HTTP 响应流(RESPONSE)
            response.Clear();
            // 设置当前 HTTP 响应流(RESPONSE)的骗码.
            response.Charset = "utf-8";
            // 设置缓冲输入.
            response.Buffer = true;
            // 设置内容类型
            response.ContentType = "application/octet-stream";
            // 设置当前 HTTP 响应流(RESPONSE)内容编码.
            response.ContentEncoding = System.Text.Encoding.UTF8;
        }
        internal static void GenerateCsvResponse(HttpResponse response, string formName, string data)
        {
            Assert.ArgumentNotNull(response, "response");
            Assert.ArgumentNotNullOrEmpty(formName, "formName");
            Assert.ArgumentNotNullOrEmpty(data, "data");

            response.Clear();
            response.ContentType = Constants.Response.ContentType.Csv;
            response.AddHeader(Constants.Response.Header.ContentDisposition.Name,
                string.Format(Constants.Response.Header.ContentDisposition.AttachmentFilenameFormat,
                    GenerateFileNameService.GenerateFileName(formName)));
            response.Charset = Constants.Response.Charset.Utf8;
            response.BinaryWrite(Encoding.UTF8.GetPreamble());
            response.Write(data);
            response.End();
        }
示例#53
0
        public void ExportGridViewToExcel(GridView grid, string fileName, HttpResponse Hresponse)
        {
            Hresponse.Clear();
            Hresponse.Buffer = true;
            Hresponse.AddHeader("content-disposition", "attachment;fileName=" + fileName + ".xls");
            Hresponse.Charset = "";
            Hresponse.ContentType = "application/vnd.ms-excel";

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            grid.RenderControl(hw);
            Hresponse.Output.Write(sw.ToString());
            Hresponse.Flush();
            Hresponse.Close();
            //Hresponse.End();
            Hresponse.OutputStream.Close();
        }
 /// <summary>
 /// 保存报表文件为文件
 /// </summary>
 /// <param name="rpvObject">Reportview控件实例</param>
 /// <param name="rptType">打印的文件类型</param>
 /// <param name="filePath">文件存放路径</param>
 /// <param name="fileName">文件名</param>
 public static void Dowload(HttpResponse response, string filePath, string fileName, string extension)
 {
     if (response == null || string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(filePath) || string.IsNullOrEmpty(extension)) return;
     FileStream stream = new FileStream(filePath + fileName + "." + extension, FileMode.Open);
     byte[] bytes = new byte[stream.Length];
     stream.Read(bytes, 0, bytes.Length);
     // 设置当前流的位置为流的开始
     stream.Seek(0, SeekOrigin.Begin);
     stream.Close();
     //Download
     response.Buffer = true;
     response.Clear();
     response.ContentType = "application/" + extension;
     response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + extension);
     response.BinaryWrite(bytes);
     response.Flush();
     response.End();
 }
示例#55
0
        public static void ReturnThroughErrorController(HttpServerUtility server, HttpResponse response, HttpContext context)
        {
            var exception = server.GetLastError();
            response.StatusCode = GetStatusCode(exception);

            if (response.StatusCode == 500) return;

            server.ClearError();
            response.Clear();
            var routeData = new RouteData();
            routeData.Values["controller"] = "Errors";
            routeData.Values["action"] = GetActionForStatusCode(response.StatusCode);
            routeData.Values["exception"] = exception;

            IController errorsController = new ErrorsController();
            var requestContext = new RequestContext(new HttpContextWrapper(context), routeData);
            errorsController.Execute(requestContext);
        }
        private void ExportToCSV(string exportContent, HttpResponse response)
        {
            response.Clear();

            response.AddHeader("content-disposition", "attachment;filename=" + fileName);

            response.Charset = "";

            response.ContentType = "application/octet-stream";

            System.IO.StringWriter stringWrite = new System.IO.StringWriter();

            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            response.Write(exportContent);

            response.End();
        }
示例#57
0
        public void imprimirReciboPDF(int numRecibo, HttpResponse Response)
        {
            try
            {
                DataSet dsRec = new DataSet("DataSetRec");
                DataTable dt = new DataTable("DataTableRec");
                FacturasRN ds = new FacturasRN();
                dsRec.Tables.Add(dt);

                ds.getRecibos(ref dt, numRecibo);
                ReportDataSource rds = new ReportDataSource();
                rds.Name = "DataSetRec_DataTableRec";
                rds.Value = dsRec.Tables[0];
                ReportViewer ReportViewer1 = new ReportViewer();
                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.DataSources.Add(rds);
                ReportViewer1.LocalReport.ReportPath = "F:/EBuy/EbuyPlaceNet/FacturacionEbuy/Reportes/Recibo/Recibo_rpt.rdlc";
                //Dim p As New ReportParameter("TITULO", "DETALLE DEL LOTE " & Request.QueryString("id_lote") & " DE LA OBRA " & Request.QueryString("obra"))
                //ReportViewer1.LocalReport.SetParameters(New ReportParameter() {p})
                ReportViewer1.LocalReport.Refresh();
                string reportType = "PDF";
                string mimeType = "";
                string encoding = "";
                string fileNameExtension = "";

                string deviceInfo = "" + " PDF" + " 8.5in" + " 11in" + " 0.5in" + " 1in" + " 1in" + " 0.5in" + "";

                Warning[] Warnings = null;
                string[] streams = null;
                Byte[] renderedBytes;

                renderedBytes = ReportViewer1.LocalReport.Render(reportType, null, out mimeType, out encoding, out fileNameExtension, out streams, out Warnings);

                Response.Clear();
                Response.ContentType = mimeType;
                Response.AddHeader("content-disposition", "attachment; filename=Recibo." + fileNameExtension);
                Response.BinaryWrite(renderedBytes);
                Response.End();
            }
            catch(Exception ex)
            {

            }
        }
        public static void ExportToExcel(string Filename, GridView gv, HttpResponse response)
        {
            gv.AllowPaging = false;
            gv.DataBind();

            response.Clear();
            response.AddHeader("content-disposition", "attachment;filename=" + Filename + ".xls");
            response.Charset = "";
            response.Cache.SetCacheability(HttpCacheability.NoCache);
            response.ContentType = "application/vnd.ms-excel";
            foreach (GridViewRow row in gv.Rows)
            {
                PrepareControlForExport(row);
            }
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            gv.RenderControl(htmlWrite);
            response.Write(stringWrite.ToString());
            //response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        public static void OutputToExcel(LocalReport localReport, string fileName, HttpResponse Response)
        {
            const string reportType = "Excel";
            string mimeType;
            string encoding;
            string fileNameExtension;

            // The DeviceInfo settings should be changed based on the reportType
            //      http://msdn2.microsoft.com/en-us/library/ms155397.aspx

            const string deviceInfo = "<DeviceInfo>" +
                                      "  <OutputFormat>Excel</OutputFormat>" +
                                      "  <OmitDocumentMap>false</OmitDocumentMap>" +
                                      "  <OmitFormulas>false</OmitFormulas>" +
                                      "  <RemoveSpace>0.125in</RemoveSpace>" +
                                      "  <SimplePageHeaders>false</SimplePageHeaders>" +
                                      "</DeviceInfo>";

            Warning[] warnings;
            string[] streams;

            //Render the report
            byte[] renderedBytes = localReport.Render(
                reportType,
                deviceInfo,
                out mimeType,
                out encoding,
                out fileNameExtension,
                out streams,
                out warnings);

            // Clear the response stream and write the bytes to the outputstream
            // Set content-disposition to "attachment" so that user is prompted to take an action
            // on the file (open or save)
            Response.Clear();
            Response.ContentType = mimeType;
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName + "." + fileNameExtension);
            Response.BinaryWrite(renderedBytes);
            Response.End();
        }
        public static void DownloadExcel(HttpResponse response)
        {
            response.Clear();
            response.Charset = "";

            // set MIME type to be Excel file.
            response.ContentType = "application/vnd.ms-excel";

            // add a header to response to force download (specifying filename)
            response.AddHeader("Content-Disposition", "attachment; filename=\"MyFile.xls\"");

            // Send the data. Tab delimited, with newlines.
            response.Write("Col1\tCol2\tCol3\tCol4\n");

            response.Write("Data 1\tData 2\tData 3\tData 4\n");
            response.Write("Data 1\tData 2\tData 3\tData 4\n");
            response.Write("Data 1\tData 2\tData 3\tData 4\n");
            response.Write("Data 1\tData 2\tData 3\tData 4\n");

            // Close response stream.
            response.End();
        }