Write() public method

public Write ( char ch ) : void
ch char
return void
 private void ReplyError(HttpStatusCode statusCode, string text, HttpResponse response)
 {
     response.StatusCode = (int)statusCode;
     response.ContentType = "text/html";
     response.Write(String.Format("<html><title>MovieInfo : ERROR</title><body><p>{0}</p></body></html>", text));
     for (int i = 0; i < 85; ++i) response.Write("&nbsp;");
 }
示例#2
1
        public override void ProcessRequest(HttpRequest req, HttpResponse res)
        {
            var type = typeof(CachedConfigContext);
            var configContext = CachedConfigContext.Current;

            if (string.IsNullOrEmpty(req["config"]))
            {
                res.Write("<p><h1>网站当前配置列表:</h1><p>");

                foreach (var p in type.GetProperties())
                {
                    if (p.Name != "ConfigService")
                        res.Write(string.Format("<p><a href='?config={0}' target='_blank'>{0} [点击查看]</a></p>", p.Name));
                }
            }
            else
            {
                foreach (var p in type.GetProperties())
                {
                    if (p.Name == req["config"] && p.Name != "DaoConfig")
                    {
                        var currentConfig = p.GetValue(configContext, null);
                        if (currentConfig != null)
                        {
                            res.ContentType = "text/xml";
                            res.ContentEncoding = System.Text.Encoding.UTF8;
                            res.Write(SerializationHelper.XmlSerialize(currentConfig));
                            break;
                        }
                    }
                }
            }
        }
    /// <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();
    }
示例#4
0
        public 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("GB2312");
            response.ContentType     = "application/vnd.ms-excel";
            response.Write("<meta   http-equiv=Content-Type   content=text/html;charset=GB2312>");
            string file = HttpUtility.UrlEncode(FileName + ".xls", System.Text.Encoding.GetEncoding("GB2312"));

            response.AddHeader("Content-Disposition", "attachment; filename=" + file);
            response.Charset = "GB2312";
            response.Write(sw.ToString());
            response.End();
        }
        public static void ExportToExcel(DataTable dt, string fileName)
        {
            System.Web.HttpResponse Response = System.Web.HttpContext.Current.Response;
            Response.ContentType = "application/csv";
            Response.Charset     = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());
            DataTable dtb = dt;

            try
            {
                StringBuilder sb = new StringBuilder();
                //Tạo dòng tiêu để cho bảng tính
                for (int count = 0; count < dtb.Columns.Count; count++)
                {
                    if (dtb.Columns[count].ColumnName != null)
                    {
                        sb.Append(dtb.Columns[count].ColumnName);
                    }
                    if (count < dtb.Columns.Count - 1)
                    {
                        sb.Append("\t");
                    }
                }
                Response.Write(sb.ToString() + "\n");
                Response.Flush();
                //Duyệt từng bản ghi
                int soDem = 0;
                while (dtb.Rows.Count >= soDem + 1)
                {
                    sb = new StringBuilder();


                    for (int col = 0; col < dtb.Columns.Count - 1; col++)
                    {
                        if (dtb.Rows[soDem][col] != null)
                        {
                            sb.Append(dtb.Rows[soDem][col].ToString().Replace(",", " "));
                        }
                        sb.Append("\t");
                    }
                    if (dtb.Rows[soDem][dtb.Columns.Count - 1] != null)
                    {
                        sb.Append(dtb.Rows[soDem][dtb.Columns.Count - 1].ToString().Replace(",", " "));
                    }


                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    soDem = soDem + 1;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            dtb.Dispose();
            Response.End();
        }
示例#6
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;
        }
    }
        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();
        }
示例#8
0
        /// <summary>
        /// The purpose of this page is to service JSON Files. The files are already generated 
        /// elsewhere and are loaded from file system.
        /// 
        /// A query string parameter is sent to this page. Given name of 'm' and has values of '1:Get movies' file,
        /// '2:Get Movies Catalog' and so on.
        /// </summary>
        public static void Read(HttpRequest Request, HttpResponse Response)
        {
            string fileNameMovies = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies.json";
            string fileNameMoviesCatalog = @"D:\SitiosWeb\Sitio\EC100A_Servicios\EC100A_PlanepolyWidget\planepoly-movies-catalog.json";
            string fileName = "";
            string m = Request.QueryString["m"];

            if (m == null || (m != "1" && m != "2"))
            {
                Response.Write("Invalid");
                return;
            }
            switch (m)
            {
                case "1":
                    fileName = fileNameMovies;
                    break;
                case "2":
                    fileName = fileNameMoviesCatalog;
                    break;
                default:
                    break;
            }
            string s;
            using (StreamReader reader = new StreamReader(fileName))
            {
                s = reader.ReadToEnd();
            }
            Response.Write(s);
            Response.AddHeader("Access-Control-Allow-Origin", "*");
        }
示例#9
0
        public void ExportTableData(DataTable dt)
        {
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            string attach = "attachment;filename=" + formName + ".xls";

            response.ClearContent();
            response.AddHeader("content-disposition", attach);
            response.ContentType     = "application/ms-excel";
            response.ContentEncoding = System.Text.Encoding.Unicode;
            response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());

            if (dt != null)
            {
                string tab = "";
                foreach (DataColumn dc in dt.Columns)
                {
                    response.Write(tab + dc.ColumnName);
                    tab = "\t";
                }
                response.Write(System.Environment.NewLine);
                foreach (DataRow dr in dt.Rows)
                {
                    tab = "";
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        response.Write(tab + dr[i].ToString().Replace("\n", " "));
                        tab = "\t";
                    }
                    response.Write("\n");
                }

                response.Flush();
                response.End();
            }
        }
示例#10
0
 private void outVar(System.Web.HttpResponse output, string key, string script)
 {
     output.Write("var _wrs_conf_");
     output.Write(key);
     output.Write(" = _wrs_int_path +'/");
     output.Write(script);
     output.Write(".aspx';\r\n");
 }
示例#11
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();
 }
示例#12
0
 /// <summary>
 /// This method will check for "directive=debug" in the querystring to indicate debugging mode.  If we're
 /// in debugging mode, the error message and stack trace will be written to the page and the response will be ended.
 /// </summary>
 /// <param name="response"></param>
 /// <param name="request"></param>
 /// <param name="exception"></param>
 public static void WriteErrorInfo(HttpResponse response, HttpRequest request, Exception exception)
 {
     if (IsDebugMode(response, request))
     {
         response.Write("<b>Message:</b> " + exception.Message + "<br /><br />");
         response.Write("<b>Stack Trace:</b> " + exception.StackTrace.Replace("\n", "<br />"));
         response.End();
     }
 }
        ///////////////////////////////////////////////////////////////////////
        public static void create_end_of_table(
            HttpResponse r)
        {

            // data
            r.Write("</table>\n");
            r.Write("</div>\n");
            r.Write("<div id=sortedby>&nbsp;</div>\n");

        }
        ///////////////////////////////////////////////////////////////////////
        public static void create_start_of_table(
            HttpResponse r)
        {

            r.Write("\n<div id=wait class=please_wait>&nbsp;</div>\n");
            r.Write("<div class=click_to_sort>click on column headings to sort</div>\n");
            r.Write("<div id=myholder>\n");
            //r.Write ("<table id=mytable class=datat border=1 cellspacing=0 cellpadding=2>\n");
            r.Write("<table id=mytable border=1 class=datat>\n");

        }
示例#15
0
 public override void WriteResponse(HttpResponse response)
 {
     response.ContentType = "text/html";
     response.Charset = "UTF-8";
     if(myXhtml != null) response.Write(myXhtml.OuterXml);
     if(myMessage != null){
         myXhtml.Body.AppendChild(myXhtml.CreateTextNode(myMessage));
         response.Write(myXhtml.OuterXml);
      			}
      			for(int i=0; i < this.Cookies.Count; i++){
         response.Cookies.Add(this.Cookies[i]);
     }
 }
示例#16
0
        public static void ToExcel(HttpResponse Response,DataTable dt , string fileName)
        {
            Response.ContentType = "application/csv";
            Response.Charset = "";
            Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
            Response.ContentEncoding = Encoding.Unicode;
            Response.BinaryWrite(Encoding.Unicode.GetPreamble());

            try
            {
                StringBuilder sb = new StringBuilder();

                //Add Header
                for (int count = 0; count < dt.Columns.Count - 1; count++)
                {
                    if (dt.Columns[count].ColumnName != null)
                        sb.Append(dt.Columns[count].ColumnName);
                    sb.Append("\t");
                }
                Response.Write(sb.ToString() + "\n");
                Response.Flush();

                //Append Data
                int index = 0;
                while (dt.Rows.Count >= index + 1)
                {
                    sb = new StringBuilder();

                    for (int col = 0; col < dt.Columns.Count -1; col++)
                    {
                        if (dt.Rows[index][col] != null)
                            //sb.Append(dt.Rows[index][col].ToString().Replace(",", " "));
                            sb.Append(dt.Rows[index][col].ToString());
                        sb.Append("\t");
                    }

                    Response.Write(sb.ToString() + "\n");
                    Response.Flush();
                    index = index + 1;
                }

            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }

            dt.Dispose();
            Response.End();
        }
        ///////////////////////////////////////////////////////////////////////
        public static void create_start_of_table(
            HttpResponse r, bool write_column_headings_as_links)
        {

            if (write_column_headings_as_links)
            {
                r.Write("\n<div id=wait class=please_wait>&nbsp;</div>\n");
                r.Write("<div class=click_to_sort>click on column headings to sort</div>\n");
            }

            r.Write("<div id=myholder>\n");
            r.Write("<table id=mytable border=1 class=datat>\n");

        }
 public void DoGet(HttpRequest req, HttpResponse resp)
 {
     resp.ContentType = "application/json";
     string command = "SELECT account, balance " +
         "FROM ACCTS WHERE id=" + req.Params[
             ConfigurationManager.AppSettings["request.parametername"]];
     SqlDataAdapter dataAdapter = new SqlDataAdapter(command,
         ConfigurationManager.AppSettings["handler.serverstring"]);
     DataSet dataSet = new DataSet();
     dataAdapter.Fill(dataSet, "ACCTS");
     DataTable dataTable = dataSet.Tables[0];
     try
     {
         float totalBalance = 0;
         int rowNum = 0;
         resp.Write("{\"balances\":[");
         while (dataTable.Rows.GetEnumerator().MoveNext())
         {
             rowNum++;
             DataRow results = (DataRow)dataTable.Rows.GetEnumerator().Current;
             // Assuming result is 9-digit bank account number,
             // validate with 11-test:
             int sum = 0;
             for (int i = 0; i < ((string)results["account"]).Length; i++)
             {
                 sum = sum + (9 - i) *
                     (int)Char.GetNumericValue(((string)results["account"])[i]);
             }
             if (sum % 11 == 0)
             {
                 totalBalance += (float)results["balance"];
                 resp.Write($"{{\"{results["account"]}\":{results["balance"]}}}");
             }
             if (rowNum == dataTable.Rows.Count)
             {
                 resp.Write("],\n");
             }
             else
             {
                 resp.Write(",");
             }
         }
         resp.Write($"\"total\":{totalBalance}}}\n");
     }
     catch (SqlException e)
     {
         Console.WriteLine($"SQL exception: {e.Message}");
     }
 }
示例#19
0
		/// <summary>
		/// 渡された HttpResponse にレスポンスを書き込みます。
		/// このメソッドは何度も使われるため、Html に AppendChild してはいけません。
		/// </summary>
		public override void WriteResponse(HttpResponse response){
			WriteResponseHeader(response);
			SetLastModified(response);
			// HTML にメッセージを投入
			if(Html == null){
				response.Write("<plaintext>");
				response.Write(myMessage);
			} else {
//				XmlElement mes = Html.P(null, myMessage);
//				Html.Append(mes);
				response.Write(Html.OuterXml);
			}


		}
示例#20
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());
            }
        }
示例#21
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="url"></param>
 public static void OpenInNewWindows(HttpResponse response, string url)
 {
     string s = string.Format(
         "<script type='text/javascript' language='javascript'>window.open('{0}')</script>",
         url);
     response.Write(s);
 }
        public void displayEdit(HttpRequest request, HttpResponse response)
        {
            String itemId = request["itemId"];
            TextBox x = new TextBox();

            response.Write(calendarManager.findEventDetails(Int16.Parse(itemId)));
        }
示例#23
0
        public static void ToExcelG(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head, string Foot)//add by zachary 2009-04-07
        {
            System.IO.StringWriter       sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);

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

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

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

            ToExelRearDecorator(hw);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Buffer      = true;
            response.ContentType = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName) + ".xls");
            response.Charset         = "UTF-8";
            response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            response.Write(sw.ToString());
            response.End();
        }
示例#24
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();
 }
示例#25
0
 /// <summary>
 /// Write the file size
 /// </summary>
 /// <param name="response">The response object</param>
 /// <param name="size">The size of file to write</param>
 private void WriteFileSizeResponse(System.Web.HttpResponse response, long size)
 {
     // Respond with the error.
     response.ContentType = "text/plain";
     response.AddHeader("Content-Length", size.ToString().Length.ToString());
     response.Write(size.ToString());
 }
示例#26
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");
            }
        }
示例#27
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;
            }
        }
示例#28
0
    public void getArticleCate(int id, int a, int cate_id)
    {
        int       i     = a;
        QueryInfo Query = new QueryInfo();

        Query.PageSize    = 0;
        Query.CurrentPage = 1;
        Query.ParamInfos.Add(new ParamInfo("AND", "int", "ArticleCateInfo.Article_Cate_ParentID", "=", id.ToString()));
        Query.ParamInfos.Add(new ParamInfo("AND", "str", "ArticleCateInfo.Article_Cate_Site", "=", Public.GetCurrentSite()));
        Query.OrderInfos.Add(new OrderInfo("ArticleCateInfo.Article_Cate_Sort", "asc"));

        IList <ArticleCateInfo> entitys = MyBLL.GetArticleCates(Query, Public.GetUserPrivilege());

        if (entitys != null)
        {
            i++;
            foreach (ArticleCateInfo entity in entitys)
            {
                string str = "";
                for (int n = 1; n <= i; n++)
                {
                    str += "&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                Response.Write("<option " + select(entity.Article_Cate_ID, cate_id) + " value=\"" + entity.Article_Cate_ID + "\">" + str + entity.Article_Cate_Name + "</option>");
                getArticleCate(entity.Article_Cate_ID, i, cate_id);
            }
        }
    }
示例#29
0
 /// <summary>
 /// Write the download URI file
 /// </summary>
 /// <param name="response">The response object</param>
 private void WriteDownloadUrlFileResponse(System.Web.HttpResponse response)
 {
     // Respond with the error.
     response.ContentType = "text/plain";
     response.AddHeader("Content-Length", "Completed".Length.ToString());
     response.Write("Completed");
 }
 public static void WriteJsonResponse(HttpResponse response, object model)
 {
     var serializer = new JavaScriptSerializer();
     string json = serializer.Serialize(model);
     response.Write(json);
     response.End();
 }
示例#31
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();
 }
示例#32
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();
        }
示例#33
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();
        }
示例#34
0
        public void ExportPdf(System.Web.UI.WebControls.GridView exportGV, System.Web.HttpResponse Response, System.Web.UI.HtmlControls.HtmlForm htmlForm)
        {
            string strFileName = "PDFReport-" + System.DateTime.Now.Date.ToString("dd") + System.DateTime.Now.AddMonths(0).ToString("MM") + System.DateTime.Now.AddYears(0).ToString("yyyy");

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter   sw  = new StringWriter();
            HtmlTextWriter hw  = new HtmlTextWriter(sw);
            HtmlForm       frm = new HtmlForm();

            exportGV.Parent.Controls.Add(frm);
            frm.Attributes["runat"] = "server";
            frm.Controls.Add(exportGV);
            frm.RenderControl(hw);

            StringReader sr         = new StringReader(Regex.Replace(sw.ToString(), "<script.*?</script>", "", RegexOptions.Singleline | RegexOptions.IgnoreCase));
            Document     pdfDoc     = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
            HTMLWorker   htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }
示例#35
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;
        }
示例#36
0
        /// <summary>
        /// ����IHttpHandler����
        /// </summary>
        /// <param name="context"></param>
        public void ProcessRequest(HttpContext context)
        {
            Request = context.Request;
            Response = context.Response;
            Session = context.Session;

            VerifyImage dt_verifyImage = new VerifyImage();
            dt_verifyImage._Random = new Random();
            dt_verifyImage._Code = dt_verifyImage.GetRandomCode();
            dt_verifyImage.BackColor = ColorTranslator.FromHtml("#edf8fe");
            Session["SystemCode"] = dt_verifyImage._Code;

            ///����û�л���
            Response.Buffer = true;
            Response.ExpiresAbsolute = System.DateTime.Now.AddSeconds(-1);
            Response.Expires = 0;
            Response.CacheControl = "no-cache";
            Response.AppendHeader("Pragma", "No-Cache");

            Bitmap objBitmap = dt_verifyImage.GetVerifyImage();
            objBitmap.Save(Response.OutputStream, ImageFormat.Gif);
            if (null != objBitmap)
                objBitmap.Dispose();
            Response.ContentType = "image/gif";
            Response.Write(Response.OutputStream);
        }
示例#37
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;
            }
        }
示例#38
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();
        }
示例#39
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");
            }
        }
 private static void SendNotFoundResponse(string message, HttpResponse httpResponse)
 {
     httpResponse.StatusCode = (int) HttpStatusCode.NotFound;
     httpResponse.ContentType = "text/plain";
     httpResponse.Write(message);
     httpResponse.End(); // This terminates the HTTP processing pipeline
 }
示例#41
0
 private void DoGet(HttpRequest request, HttpResponse response)
 {
     string ns = request.QueryString["ns"];
     response.ContentType = "text/javascript";
     string url = request.Url.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.Unescaped);
     response.Write(new DirectApiBuilder(_metadata).BuildApi(ns, url));
 }
示例#42
0
        /// <summary>
        /// Writes the result directly into the response stream, e.g. for a classic ASP.NET response
        /// </summary>
        /// <param name="response">A standard HttpResponse object</param>
        /// <param name="result">An IBackloadResult object</param>
        public static void Write(HttpResponse response, IBackloadResult result)
        {

            response.StatusCode = (int)result.HttpStatusCode;
            if ((int)result.HttpStatusCode < 300)
            {

                // Write result to the response (Json or file data, default: Json response)
                if (result.RequestType == RequestType.Default)
                {
                    // Json response (We use the systems JavaScriptSerializer, you can also use Newtonsoft.Json)
                    IFileStatusResult status = (IFileStatusResult)result;
                    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();

                    if ((status.ClientStatus != null) && (result.Exception == null))
                        response.Write(serializer.Serialize(status.ClientStatus));
                }
                else if ((result.RequestType == RequestType.File) || (result.RequestType == RequestType.Thumbnail))
                {
                    // file data (byte array) response
                    IFileDataResult data = (IFileDataResult)result;

                    if ((data.FileData != null) && (result.Exception == null))
                        response.BinaryWrite(data.FileData);
                }
            }
        }
示例#43
0
 private void updataCourseMark(HttpRequest Request, HttpResponse Response)
 {
     //评论内容敏感词过滤---待加
     comModel.CourseID = int.Parse(Request.Form["courseID"]);
     comModel.Score = int.Parse(Request.Form["mark"]);
     comModel.Comments =Common.CommonCode.NoHTML( Request.Form["content"]);//去掉评论中的HTML标签和JS标签
     comModel.UserID = int.Parse(Request.Form["userId"]);
     comModel.ParentID = -1;
     if (comBll.CourseComment(comModel))
     {
         Response.Write("Success");
     }
     else
     {
         Response.Write("Faile");
     }
 }
示例#44
0
 public static void ExportToExcel(System.Web.HttpResponse Response, string datos)
 {
     Response.Clear();
     Response.Write(datos);
     Response.ContentType = "application/vnd.ms-excel";
     Response.AppendHeader("Content-Disposition", "attachment; filename=Informe.xls");
     Response.End();
 }
示例#45
0
        /// <summary>
        /// Write the download URI file
        /// </summary>
        /// <param name="response">The response object</param>
        /// <param name="result">The response from the server</param>
        private void WriteUploadUrlFileResponse(System.Web.HttpResponse response, byte[] result)
        {
            // Respond with the error.
            response.ContentType = "text/plain";

            if (result != null)
            {
                string data = "Completed. " + Encoding.Default.GetString(result);
                response.AddHeader("Content-Length", data.Length.ToString());
                response.Write(data);
            }
            else
            {
                response.AddHeader("Content-Length", "Completed".Length.ToString());
                response.Write("Completed");
            }
        }
 public void Process(HttpResponse response)
 {
     response.AppendHeader("Last-Modified", serverFingerprint.LastModifiedTime.ToString("r"));
     response.AppendHeader("ETag", serverFingerprint.ETag);
     response.AppendHeader("Cache-Control", "private, max-age=0");
     response.ContentType = MimeType.Json.ContentType;
     response.Write(jsonFragment);
 }
        private void DoGet(HttpRequest request, HttpResponse response)
        {
            string format = request.QueryString["format"];
            string url = request.Url.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.Unescaped);
            var apiBuilder = new DirectApiBuilder(_metadata);

            if(string.Equals(format, "json", StringComparison.InvariantCultureIgnoreCase))
            {
                response.ContentType = "application/json";
                response.Write(apiBuilder.BuildJson(url));
            }
            else
            {
                response.ContentType = "text/javascript";
                response.Write(apiBuilder.BuildJavascript(url));
            }
        }
示例#48
0
        public static void ResponseExcel <T>(System.Web.HttpResponse response, List <T> items)
        {
            try
            {
                string attachment = "attachment; filename=vauExcel.xls";
                response.ClearContent();
                response.AddHeader("content-disposition", attachment);
                response.ContentType = "application/vnd.ms-excel";
                string tab = string.Empty;

                // Get all the properties
                PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo prop in props)
                {
                    response.Write(tab + prop.Name);
                    tab = "\t";
                }

                response.Write("\n");
                foreach (T item in items)
                {
                    var values = new object[props.Length];
                    for (int i = 0; i < props.Length; i++)
                    {
                        values[i] = props[i].GetValue(item, null);
                        if (values[i] != null)
                        {
                            response.Write(values[i].ToString().Trim() + "\t");
                        }
                        else
                        {
                            response.Write("\t");
                        }
                    }

                    response.Write("\n");
                }

                response.Flush();
                response.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#49
0
        protected void renderMergedOutputModel(Dictionary<string, Object> model,
                                               HttpRequest request, HttpResponse response)
        {
            Assertion assertion = getAssertionFrom(model);

            if (this.successResponse)
            {
                response.Write(
                    "yes\n"
                    + assertion.getChainedAuthentications().First().getPrincipal()
                          .getId() + "\n");
            }
            else
            {
                response.Write("no\n\n");
            }
        }
示例#50
0
 // This method is actually the heart of all http handlers.
 // This method is called to process http requests.
 public void ProcessRequest(System.Web.HttpContext context)
 {
     try
     {
         ChmProcessor chmProc = new ChmProcessor(context);
         chmProc.Process();
     }
     catch (Exception ex)
     {
         System.Web.HttpResponse r = context.Response;
         r.Write("<h2>CHM App error</h2><br>\n");
         r.Write("<pre>\n");
         r.Write("Error processing path: " + context.Request.Path + "<br>\n");
         r.Write("Error: " + ex.ToString());
         r.Write("</pre>\n");
     }
 }
示例#51
0
 public  static void PagerJson(HttpResponse rsp,DataTable rows, string pager)
 {
     const string fmt = "{'pager':'%pager%','rows':%html%}";
     rsp.Write(fmt.Template(
        pager.Replace("'", "\\'"),
         JsonConvert.SerializeObject(rows)
        ));
     rsp.ContentType = "application/json";
 }
        private void DoGet(HttpRequest request, HttpResponse response)
        {
            string ns = request.QueryString["ns"];
            string format = request.QueryString["format"];
            string url = request.Url.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.Unescaped);
            DirectApiBuilder apiBuilder = new DirectApiBuilder(_metadata);

            if (format == "json")
            {
                response.ContentType = "application/json";
                response.Write(apiBuilder.BuildApiDescriptor(ns, ns, url));
            }
            else
            {
                response.ContentType = "text/javascript";
                response.Write(apiBuilder.BuildApi(ns, url));
            }
        }
示例#53
0
        /// <summary>
        /// Export DataGrid To Excel
        /// </summary>
        /// <param name="response">ส่ง Response</param>
        /// <param name="thisPage">ส่ง this</param>
        /// <param name="objDataGrid">ส่ง DataGrid ที่ต้องการ Export</param>
        /// <param name="header">ชื่อ Header</param>
        /// <param name="footer">ชื่อ Footer</param>
        public void ExportToExcel(System.Web.HttpResponse response, System.Web.UI.Page thisPage, GridView objDataGrid, string header, string footer)
        {
            response.Clear();
            response.Buffer          = true;
            response.ContentType     = "application/vnd.ms-excel";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.Charset         = "";
            //Response.AddHeader("Content-Disposition", "attachment;filename=Clientes.xls");

            string open = @"<html xmlns:x=""urn:schemas-microsoft-com:office:excel""><head><style>
			<!--table
			br {mso-data-placement:same-cell;}
			tr {vertical-align:middle;}
			td {mso-number-format:\@;font-family:Tahoma, sans-serif;font-size:8.0pt;text-align:center;}			
			--></style></head> <body>"            ;

            response.Write(open);

            thisPage.EnableViewState = false;
            if (header != "")
            {
                response.Write("<font face='Tahoma'><b>" + header + "</b></font>");
            }
            System.IO.StringWriter       oStringWriter   = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);

            this.ClearControl(objDataGrid);

            for (int rowPos = 0; rowPos < objDataGrid.Rows.Count; ++rowPos)
            {
                for (int colPos = 0; colPos < objDataGrid.Rows[rowPos].Cells.Count; ++colPos)
                {
                    objDataGrid.Rows[rowPos].Cells[colPos].Attributes.Add("class", "NumberString");
                }
            }
            objDataGrid.RenderControl(oHtmlTextWriter);

            string styleInfo = @"<style>.NumberString    {mso-number-format:\@;}</style>";

            response.Write(styleInfo + oStringWriter.ToString());
            response.Write(footer);
            response.Write("</body></html>");
            response.End();
        }
示例#54
0
        /// <summary>
        /// DataTable을 Excel로 변환해서 Response.Write로 기록
        /// </summary>
        public static void DS2Excel(System.Web.HttpResponse Response, DataTable DT, string FileName)
        {
            StringBuilder strBuilder = new StringBuilder();

            int i;
            int j;

            //화면 출력할 table 만들기
            strBuilder.Append("<html xmlns='http://www.w3.org/1999/xhtml'>");
            strBuilder.Append("     <head>");
            strBuilder.Append("         <meta http-equiv='Content-Type' content = 'text/html;charset=utf-8' />");
            strBuilder.Append("     </head>");
            strBuilder.Append("     <body>");
            strBuilder.Append("         <table border='1'>");
            strBuilder.Append("             <thead>");
            strBuilder.Append("                 <tr>");
            //제목줄 출력
            for (j = 0; j < DT.Columns.Count; j++)
            {
                strBuilder.Append("                 <th bgcolor = '#90BFC6'>");
                strBuilder.Append(DT.Columns[j].ColumnName);
                strBuilder.Append("                 </th>");
            }

            strBuilder.Append("                 </tr'>");
            strBuilder.Append("             </thead>");

            strBuilder.Append("             <tbody>");
            //table 새로운 열이 시작 될때(tr)
            for (i = 0; i < DT.Rows.Count; i++)
            {
                strBuilder.Append("             <tr>");

                //행 출력(td)
                for (j = 0; j < DT.Columns.Count; j++)
                {
                    strBuilder.Append("             <td style ='mso-number-format:\\@;'>");
                    strBuilder.Append(DT.Rows[i][j].ToString());
                    strBuilder.Append("             </td>");
                }

                strBuilder.Append("             </tr>");
            }
            strBuilder.Append("             </tbody>");

            strBuilder.Append("         </table>");
            strBuilder.Append("     </body>");
            strBuilder.Append("</html>");

            Response.Clear();
            Response.ContentType = "application/vnd.ms-excel";
            Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
            Response.Write(strBuilder.ToString());
            Response.End();
        }
示例#55
0
		/// <summary>
		/// 日志输出到页面
		/// </summary>
		/// <param name="res"></param>
		/// <param name="str"></param>
		public static void List(System.Web.HttpResponse res, String str) 
		{
			try 
			{
                string dt = FormatUtil.Format("yyyy-MM-dd hh:mm:ss", System.DateTime.Now);
				res.Write("[" + dt + "]"+ str + "<br>");
			} 
			catch
			{
			}
		}
示例#56
0
        private static void PerformInsertOrUpdateOrDelete(System.Web.HttpResponse Response, ViewModel vmc, bool allowed, string name, Func <DataItem> action)
        {
            if (!allowed)
            {
                MethodNotAllowed(Response, vmc, name);
                return;
            }


            DataItem r = null;

            try
            {
                r = action();
            }
            catch (NotFoundException)
            {
                vmc.ModelState.ApplyNotFound(Response);

                return;
            }
            catch (Firefly.Box.Data.DataProvider.DatabaseErrorException ex)
            {
                vmc.ModelState.AddError(ex.ErrorType.ToString());
            }
            catch (Exception ex)
            {
                vmc.ModelState.AddError(ex);
            }

            if (!vmc.ModelState.IsValid)
            {
                Response.Write(vmc.ModelState.ToJson());
                Response.StatusCode = 400;
            }
            else if (r != null)
            {
                Response.Write(r.ToJson());
            }
        }
示例#57
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);
                }
                //response.BinaryWrite(Encoding.Unicode.GetPreamble());
                // XSLT to use for transforming this dataset.
                MemoryStream  stream = new MemoryStream( );
                XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

                CreateStylesheet(writer, sHeaders, sFileds, FormatType);
                writer.Flush( );
                stream.Seek(0, SeekOrigin.Begin);

                XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
                //dsExport.WriteXml("Data.xml");
                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);
                //xslTran.Transform(System.Web.HttpContext.Current.Server.MapPath("Data.xml"), null, sw, null);

                //Writeout the Content
                response.Write(sw.ToString());
                sw.Close();
                writer.Close();
                stream.Close();
                response.End();
            }
            catch (ThreadAbortException Ex)
            {
                string ErrMsg = Ex.Message;
            }
            catch (Exception Ex)
            {
                throw Ex;
            }
        }
示例#58
0
 /// <summary>
 /// 把DataTable导出为Word文件
 /// </summary>
 /// <param name="page">Page</param>
 /// <param name="fileName">Word文件名(不包括后缀*.doc)</param>
 /// <param name="dtbl">将要被导出的DataTable对象</param>
 /// <returns></returns>
 public static bool DataTableToWord(System.Web.HttpResponse response, string fileName, DataTable dtbl)
 {
     response.Clear();
     response.Buffer  = true;
     response.Charset = "UTF-8";
     response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName + ".doc");
     response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
     response.ContentType     = "application/ms-word";
     //page.EnableViewState = false;
     response.Write(DataTableToHtmlTable(dtbl));
     response.End();
     return(true);
 }
示例#59
0
    // Exports dataset into CSV / Excel format

    private void ExportXSLT(DataSet dsExport, string[] sHeaders, string[] sFileds, ExportFormat FormatType, string FileName)
    {
        try
        {
            // Appending Headers
            objHttpResponse.Clear();
            objHttpResponse.Buffer = true;

            if (FormatType == ExportFormat.CSV)
            {
                objHttpResponse.ContentType = "text/csv";
                objHttpResponse.AppendHeader("content-disposition", "attachment; filename=" + FileName);
            }
            else
            {
                objHttpResponse.ContentType = "application/vnd.ms-excel";
                objHttpResponse.AppendHeader("content-disposition", "attachment; filename=" + FileName);
            }

            // XSLT to use for transforming this dataset.
            MemoryStream  stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            CreateStylesheet(writer, sHeaders, sFileds, FormatType);
            writer.Flush();
            stream.Seek(0, SeekOrigin.Begin);

            XmlDataDocument xmlDoc = new XmlDataDocument(dsExport);
            //dsExport.WriteXml("Data.xml");
            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);

            //Writeout the Content
            objHttpResponse.Write(sw.ToString());
            sw.Close();
            writer.Close();
            stream.Close();
            objHttpResponse.End();
        }
        catch (ThreadAbortException Ex)
        {
            string ErrMsg = Ex.Message;
        }
        catch (Exception Ex)
        {
            ErrorLog.WriteErrorLog("DB2Excel-ExportDetails", Ex);
        }
    }
示例#60
0
        /// <summary>
        /// Writes xml to the response output stream.
        /// </summary>
        /// <param name="xml">The XML.</param>
        /// <param name="filename">Name of the file.</param>
        public void SaveXML(string xml, string filename)
        {
            if (xml != null)
            {
                System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.Charset     = "utf-8";
                response.ContentType = "text/xml";
                response.AddHeader("content-disposition", String.Format("attachment; filename={0}", filename));

                response.Write(xml);
                response.End();
            }
        }