예제 #1
0
        /// <summary>
        /// 获取文件输出流
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="isAutoContentType"></param>
        /// <returns></returns>
        public static HttpResponse GetFileResponse(string fileName, bool isAutoContentType = false)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.Buffer = true;
            response.Clear();
            response.ContentType     = WSH.Common.Http.HttpHepler.GetContentType(isAutoContentType ? Path.GetExtension(fileName) : "file");
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.Charset         = "utf-8";
            if (HttpContext.Current.Request.UserAgent.ToLower().Contains("msie"))
            {
                fileName = HttpContext.Current.Server.UrlEncode(fileName);
            }
            response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
            return(response);
        }
        /// <summary>
        ///     通过StringBuilder输出Excel
        /// </summary>
        /// <param name="sb">StringBuilder对象</param>
        /// <param name="fileName">文件名</param>
        public static void ExportExcelBySB(StringBuilder sb, string fileName)
        {
            //输出EXCEL
            HttpResponse httpResponse = HttpContext.Current.Response;

            httpResponse.Clear();
            httpResponse.Buffer          = true;
            httpResponse.Charset         = "gb2312";
            httpResponse.ContentEncoding = Encoding.GetEncoding("utf-8");
            httpResponse.AppendHeader("Content-Disposition",
                                      "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8));
            httpResponse.ContentType = "application/ms-excel";
            httpResponse.Write("<html><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">");
            httpResponse.Write(sb.ToString());
            httpResponse.End();
        }
예제 #3
0
        //private Usuario usr;

        /// <summary>
        /// Metodo para Generar el Reporte

        public void ExportToExcel(DataSet dSet, int TableIndex, HttpResponse Response, string FileName)
        {
            Response.Clear();
            Response.Charset     = "";
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("content-disposition", "attachment; filename=" + FileName + ".xls");
            System.IO.StringWriter       sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
            GridView gv = new GridView();

            gv.DataSource = dSet.Tables[TableIndex];
            gv.DataBind();
            gv.RenderControl(hw);
            Response.Write(sw.ToString());
            Response.End();
        }
예제 #4
0
    /// <summary>
    /// �������ؿ�
    /// </summary>
    /// <param name="argResp">����ҳ��</param>
    /// <param name="argFileStream">�ļ���</param>
    /// <param name="strFileName">�ļ���</param>
    public static void DownloadFile(HttpResponse argResp, StringBuilder argFileStream, string strFileName)
    {
        try {
            string strResHeader = "attachment; filename=" + Guid.NewGuid().ToString() + ".csv";
            if (!string.IsNullOrEmpty(strFileName)) {
                strResHeader = "inline; filename=" + strFileName;
            }
            argResp.AppendHeader("Content-Disposition", strResHeader);//attachment˵���Ը������أ�inline˵�����ߴ�
            argResp.ContentType = "application/ms-excel";
            argResp.ContentEncoding = Encoding.GetEncoding("GB2312"); // Encoding.UTF8;//
            argResp.Write(argFileStream);

        } catch (Exception ex) {
            throw ex;
        }
    }
예제 #5
0
        public void Export()
        {
            HttpResponse response = HttpContext.Current.Response;

            CreateData();

            response.Charset         = "GB2312";
            response.ContentEncoding = Encoding.GetEncoding("GB2312");
            response.ContentType     = "APPLICATION/OCTET-STREAM";
            response.AppendHeader("Content-Disposition", "attachment;filename=" +
                                  HttpUtility.UrlEncode(_fileName));
            response.WriteFile(_fileName);
            response.Flush();
            File.Delete(_fileName);
            response.End();
        }
예제 #6
0
        /// <summary>
        /// 向客户端传递错误信息
        /// </summary>
        /// <param name="string">错误信息内容</param>
        private static void GenerateErrorInformation(string errorInformation)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.AppendHeader("errorMessage", HttpUtility.UrlEncode("message=" + errorInformation));

            if (HttpContext.Current.Request.QueryString["upmethod"] == "new")
            {
                response.ClearContent();
                var    dialogControlID = WebUtility.GetRequestQueryValue("dialogControlID", string.Empty);
                string output          = "<script type='text/javascript'>";
                output += "window.parent.$find('" + dialogControlID + "').onUploadFinish(2,'" + errorInformation + "')";
                output += "</script>";
                response.Write(output);
            }
        }
예제 #7
0
        public void saveasPdf(HttpRequest req, HttpResponse res)
        {
            string str    = PathTool.getRealPath(req, FileAction.basePath + req["spath"]);
            Report report = method_4(str, req, method_3(req["e_paramid"]));
            string str2   = "ereport";

            res.ContentType = ("application/pdf");
            res.AppendHeader("Content-Disposition", new StringBuilder("attachment; filename=").Append(str2).Append(".pdf").ToString().ToString());
            try
            {
                report.exportToPDF(res.OutputStream);
            }
            catch (Exception)
            {
            }
        }
예제 #8
0
파일: Rule.cs 프로젝트: fuqi0340/StaticHtml
        /// <summary>
        /// 根据请求头自动判断客户端是否支持gzip,如果不支持, 在服务器解压
        /// </summary>
        /// <param name="req"></param>
        /// <param name="rep"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        private static Stream AcceptGzip(HttpRequest req, HttpResponse rep, HttpInfo info)
        {
            var    acceptEncoding = req.Headers.Get("Accept-Encoding");
            Stream _out;

            if (acceptEncoding != null && acceptEncoding.Contains("gzip"))
            {
                _out = info.Content;
                rep.AppendHeader("Content-Encoding", "gzip");
            }
            else
            {
                _out = new GZipStream(info.Content, CompressionMode.Decompress);
            }
            return(_out);
        }
예제 #9
0
        /// <summary>
        /// 写响应头
        /// </summary>
        /// <param name="response">HttpResponse实例</param>
        /// <param name="headerName">响应头的名字</param>
        /// <param name="headerValue">响应头的内容</param>
        public virtual void WriteResponseHeader(HttpResponse response, string headerName, string headerValue)
        {
            if (HttpRuntime.UsingIntegratedPipeline)
            {
                // 这是 .net framework 3.5 sp1 中增加的方法,减少代码的执行路径,性能会更好,所以优先使用。
                response.Headers.Add(headerName, headerValue);
            }
            else
            {
                // 早期版本做法(或者在经典模式下)
                response.AppendHeader(headerName, headerValue);
            }

            // 说明:响应头可能会写到多个地方:Headers, _cacheHaaders, _customHeaders
            // 这里封装一个方法,便于验证【写入操作】,可参考 WebRuntimeExt
        }
예제 #10
0
        private void DirectReceive(HttpContext context, TcpClient proxyClient)
        {
            context.Server.ScriptTimeout = int.MaxValue;
            HttpRequest  Request  = context.Request;
            HttpResponse Response = context.Response;

            //长连接必须关掉
            Response.AppendHeader(HttpResponseHeader.Connection.ToString(), "close");

            var proxyStream = proxyClient.GetStream();

            while (proxyClient.Connected && Response.IsClientConnected)
            {
                try
                {
                    proxyStream.Read(EmptyBuffer, 0, 0);
                    int length;
                    //阻塞解除后做第2道检查
                    if (!(proxyClient.Connected && Response.IsClientConnected) || (length = proxyClient.Available) == 0)
                    {
                        //服务端主动关闭,发送空包
                        if (Response.IsClientConnected)
                        {
                            Response.OutputStream.Write(EmptyBuffer, 0, 0);
                            Response.Flush();
                        }
                        break;
                    }
                    proxyStream.FixedCopyTo(Response.OutputStream, length);
                    if (Response.IsClientConnected)
                    {
                        Response.Flush();
                    }
#if DEBUG
                    App.LogInfo("DirectReceive from {0} {1}bytes.", proxyClient.Client.RemoteEndPoint, length);
#endif
                }
                catch (IOException ex)
                {
                    TunnelExceptionHandler.Handle(ex, proxyClient.Client, "DirectReceive");
                }
                catch (SocketException ex)
                {
                    TunnelExceptionHandler.Handle(ex, proxyClient.Client, "DirectReceive");
                }
            }
        }
예제 #11
0
        private void ExportToExcel(HttpContext context)
        {
            HttpResponse resp = System.Web.HttpContext.Current.Response;

            resp.Charset = "utf-8";
            resp.Clear();
            string filename = "入库明细表_" + DateTime.Now.ToString("yyyyMMddHHmmss");

            resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
            resp.ContentEncoding = System.Text.Encoding.UTF8;

            resp.ContentType = "application/ms-excel";
            string style = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=utf-8\"/>" + "<style> .table{ font: 9pt Tahoma, Verdana; color: #000000; text-align:center;  background-color:#8ECBE8;  }.table td{text-align:center;height:45px;background-color:#EFF6FF;}.table th{ font: 9pt Tahoma, Verdana; color: #000000; font-weight: bold; background-color: #8ECBEA; height:35px;  text-align:center; padding-left:10px;}</style>";

            resp.Write(style);

            resp.Write("<table class='table'><tr><th>条码号</th><th>产品编码</th><th>产品名称</th><th>数量</th><th>操作员</th><th>操作时间</th></tr>");

            var dt = new DataTable("sqlTemp");

            DateTime dStart, dEnd;
            var      cStart = context.Request.QueryString["dStart"];
            var      cEnd   = context.Request.QueryString["dEnd"];

            if (DateTime.TryParse(cStart, out dStart) && DateTime.TryParse(cEnd, out dEnd))
            {
                dt = DalStoreDetail.GetStoreDetailByDate(dStart, dEnd);
            }
            else
            {
                dt = DalStoreDetail.GetStoreDetail();
            }
            foreach (DataRow tmpRow in dt.Rows)
            {
                resp.Write("<tr><td style='mso-number-format:\"@\"'>" + tmpRow[0] + "</td>");
                resp.Write("<td>" + tmpRow[1] + "</td>");
                resp.Write("<td>" + tmpRow[2] + "</td>");
                resp.Write("<td>" + tmpRow[3] + "</td>");
                resp.Write("<td>" + tmpRow[4] + "</td>");
                resp.Write("<td>" + tmpRow[5] + "</td>");
                resp.Write("</tr>");
            }
            resp.Write("<table>");

            resp.Flush();
            resp.End();
        }
예제 #12
0
        public IHttpActionResult GetAttendanceAsXLSFile(int id)
        {
            Attendance attendance = aRepo.GetAttendance(id);

            if (attendance != null)
            {
                //Create an instance of ExcelEngine.
                using (ExcelEngine excelEngine = new ExcelEngine())
                {
                    //Set the default Excel-version  -  New Excel is back compatible with older Excel but an old Excel can't access new Excel so therefor we set the ExcelVersion to be as low as possible.
                    excelEngine.Excel.DefaultVersion = ExcelVersion.Excel97to2003;
                    //Create a workbook with a worksheet.
                    IWorkbook workbook = excelEngine.Excel.Workbooks.Create(1); //We only need one Excel page
                    //Access first worksheet from the workbook instance.
                    IWorksheet worksheet = workbook.Worksheets[0];              //We want to work on first page

                    //Titles
                    worksheet.Range["A1"].Text = "Teacher";
                    worksheet.Range["B1"].Text = attendance.Course.Teacher.FirstName + " " + attendance.Course.Teacher.LastName;
                    worksheet.Range["D1"].Text = "Course";
                    worksheet.Range["E1"].Text = attendance.Course.Subject.Name + "(" + attendance.Course.Teacher.FirstName + " " + attendance.Course.Teacher.LastName + ")";


                    worksheet.Range["A3"].Text = "Firstname:";
                    worksheet.Range["B3"].Text = "Lastname";
                    worksheet.Range["D3"].Text = "Attendance";

                    int index = 4;
                    foreach (User student in attendance.Students)
                    {
                        //Values
                        worksheet.Range["A" + index].Text = student.FirstName;
                        worksheet.Range["B" + index].Text = student.LastName;
                        worksheet.Range["D" + index].Text = (attendance.Students.Where(s => s.Id == student.Id).Count() > 0).ToString();

                        index++;
                    }
                    //Save the workbook to user-header in xlx format. - The file is downloading
                    HttpResponse response = HttpContext.Current.ApplicationInstance.Response;
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                    workbook.SaveAs("Attendance.xls", response, ExcelDownloadType.Open);
                    return(Ok());
                }
            }
            return(NotFound());
        }
예제 #13
0
        private void ExportToExcel(HttpContext context)
        {
            MemberQuery query = this.getQuery(context);

            query.PageIndex = 1;
            query.PageSize  = 2147483647;
            DbQueryResult membersClerkExpand = MemberHelper.GetMembersClerkExpand(query);
            StringBuilder stringBuilder      = new StringBuilder();

            stringBuilder.AppendLine("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");
            stringBuilder.AppendLine("<tr style=\"font-weight: bold; white-space: nowrap;\">");
            stringBuilder.AppendLine("<td>会员账号</td>");
            stringBuilder.AppendLine("<td>店员</td>");
            stringBuilder.AppendLine("<td>创建时间</td>");
            stringBuilder.AppendLine("<td>订单金额</td>");
            stringBuilder.AppendLine("</tr>");
            DataTable data = membersClerkExpand.Data;
            DateTime  dateTime;

            foreach (DataRow row in data.Rows)
            {
                stringBuilder.AppendLine("<tr>");
                stringBuilder.AppendLine("<td>" + row.Field <string>("UserName") + "</td>");
                stringBuilder.AppendLine("<td>" + row.Field <string>("ManagersName") + "</td>");
                StringBuilder stringBuilder2 = stringBuilder;
                dateTime = row.Field <DateTime>("CreateDate");
                stringBuilder2.AppendLine("<td>" + dateTime.ToString("yyyy-MM-dd HH:mm:ss") + "</td>");
                stringBuilder.AppendLine("<td>" + row["Expenditure"].ToDecimal(0).F2ToString("f2") + "</td>");
                stringBuilder.AppendLine("</tr>");
            }
            stringBuilder.AppendLine("<tr>");
            stringBuilder.AppendLine("<td></td>");
            stringBuilder.AppendLine("</tr>");
            stringBuilder.AppendLine("</table>");
            context.Response.Clear();
            context.Response.Buffer  = false;
            context.Response.Charset = "GB2312";
            HttpResponse response = context.Response;

            dateTime = DateTime.Now;
            response.AppendHeader("Content-Disposition", "attachment;filename=MemberDetails_" + dateTime.ToString("yyyyMMddHHmmss") + ".xls");
            context.Response.ContentEncoding = Encoding.GetEncoding("GB2312");
            context.Response.ContentType     = "application/ms-excel";
            context.Response.Write(stringBuilder.ToString());
            context.Response.End();
        }
예제 #14
0
 protected void btnOK_Click(object sender, EventArgs e)
 {
     byte[] buffer = MSSQL.BackupDataToZipStream();
     if (buffer == null)
     {
         JavaScript.Alert(this.Page, "数据表备份失败!");
     }
     else
     {
         HttpResponse response = this.Page.Response;
         response.AppendHeader("Content-Disposition", "attachment;filename=ShoveLottery_DataBackup_" + DateTime.Now.ToString().Replace("-", "_").Replace(" ", "_").Replace(":", "_") + ".zip");
         base.Response.ContentType = "application/octet-stream";
         base.Response.BinaryWrite(buffer);
         base.Response.Flush();
         response.End();
     }
 }
        /// <summary>
        /// 输出ExcelXml格式的Header
        /// </summary>
        /// <param name="response"></param>
        public static void AddExcelXmlHeader(this HttpResponse response, string fileNameWithoutExt)
        {
            ExceptionHelper.FalseThrow <ArgumentNullException>(response != null, "response");

            string fileType = "text/xml";
            string fileExt  = "xml";

            if (DeluxePrincipal.IsAuthenticated)
            {
                fileType = UserSettings.GetSettings(DeluxeIdentity.CurrentUser.ID).GetPropertyValue("CommonSettings", "downExcelXmlContentType", fileType);
                fileExt  = UserSettings.GetSettings(DeluxeIdentity.CurrentUser.ID).GetPropertyValue("CommonSettings", "downExcelXmlFileExt", fileExt);
            }

            response.ContentType = fileType;
            response.AppendHeader("CONTENT-DISPOSITION",
                                  string.Format("{0};filename={1}", "inline", response.EncodeFileNameInContentDisposition(fileNameWithoutExt + "." + fileExt)));
        }
예제 #16
0
파일: ExcelHelper.cs 프로젝트: yuzs/donetci
        /// <summary>
        /// 用于Web导出
        /// </summary>
        /// <param name="dtSource">源DataTable</param>
        /// <param name="strHeaderText">表头文本</param>
        /// <param name="strFileName">文件名</param>
        public static void ExportByCSV(DataTable dtSource, string strHeaderText, string strFileName)
        {
            HttpResponse resp = HttpContext.Current.Response;

            // 设置编码和附件格式
            resp.ContentType     = "application/vnd.ms-excel";
            resp.ContentEncoding = Encoding.UTF8;
            resp.Charset         = "";
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));

            string colHeaders = "";
            int    colCount   = dtSource.Columns.Count;
            var    dtCol      = new DataColumn();

            for (int i = 0; i < colCount; i++)
            {
                dtCol      = dtSource.Columns[i];
                colHeaders = colHeaders + dtCol.ColumnName + ",";
            }
            if (colHeaders.Length > 0)
            {
                colHeaders = colHeaders.Substring(0, colHeaders.LastIndexOf(','));
            }
            colHeaders = colHeaders + (char)13 + (char)10;
            resp.Write(colHeaders);

            int           num = 0;
            StringBuilder sb  = new StringBuilder();

            for (int i = 0; i < colCount; i++)
            {
                if (num < 1000)
                {
                    sb.Append(Export(dtSource.Rows[i], dtSource));
                    num++;
                }
                else
                {
                    resp.Write(sb.ToString());
                    sb.Remove(0, sb.Length);
                    num = 0;
                }
            }
            resp.Write(sb.ToString());
            resp.End();
        }
예제 #17
0
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    protected void btnExport_Click(object sender, ImageClickEventArgs e)
    {
        try
        {
            string filePath = ServerMapPath(@"../Import/Visitors/VisitorsBlank.xls");

            HttpResponse res = GetHttpResponse();
            res.Clear();
            res.AppendHeader("content-disposition", "attachment; filename=VisitorsBlank.xls");
            res.ContentType = "application/x-msexcel";
            // res.ContentType = "application/octet-stream";
            res.WriteFile(filePath);
            res.Flush();
            res.End();
        }
        catch (Exception ex) { }
    }
예제 #18
0
    /// <summary>
    /// Export data to csv and response directly
    /// </summary>
    /// <param name="response">Current page response</param>
    /// <param name="fileName">export file name</param>
    /// <param name="listData">list data to export</param>
    public static void ExportCSV(HttpResponse response, string fileName, List <ImportExportFields> listData)
    {
        //prepare the output stream
        response.Clear();
        response.Buffer = true;
        // response.ContentType = "text/csv";
        response.ContentType = "application/octet-stream";//application/vnd.ms-excel";
        response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
        //response.ContentEncoding = Encoding.Unicode;
        response.ContentEncoding = System.Text.Encoding.UTF8;
        response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

        response.Write(DataToCsvString(listData));

        response.Flush();
        response.End();
    }
예제 #19
0
        public void DisposePendingNotificationClientRequest()
        {
            IMailboxContext mailboxContext = UserContextManager.GetMailboxContext(HttpContext.Current, null, false);
            HttpResponse    response       = HttpContext.Current.Response;
            object          parameter      = base.GetParameter("Fn");
            bool            flag           = false;

            if (parameter != null)
            {
                flag = (bool)parameter;
            }
            bool   flag2 = false;
            string text  = (string)base.GetParameter("cid");

            text = this.ProcessChannelIdOnRequestAndGenerateIfNeeded(text, flag);
            if (mailboxContext != null && text != null)
            {
                PendingRequestChannel pendingGetChannel = mailboxContext.PendingRequestManager.GetPendingGetChannel(text);
                if (pendingGetChannel != null)
                {
                    flag2 = pendingGetChannel.HandleFinishRequestFromClient();
                    if (flag)
                    {
                        ExTraceGlobals.NotificationsCallTracer.TraceDebug <string>((long)this.GetHashCode(), "[PendingRequestEventHandler::DisposePendingNotificationClientRequest] userContext.PendingRequestManager.RemovePendingGetChannel. ChannelId: {0}", text);
                        mailboxContext.PendingRequestManager.RemovePendingGetChannel(text);
                    }
                }
                else
                {
                    mailboxContext.PendingRequestManager.AddPendingGetChannel(text);
                }
            }
            response.AppendHeader("X-OWA-EventResult", "0");
            response.Write("{");
            if (text != null)
            {
                response.Write("cid:\"");
                response.Write(text);
                response.Write("\",");
            }
            response.Write("syncFnshRq:");
            response.Write(flag2 ? "1}" : "0}");
            HttpUtilities.MakePageNoCacheNoStore(response);
            response.ContentType = HttpUtilities.GetContentTypeString(base.ResponseContentType);
        }
예제 #20
0
파일: ExcelHelper.cs 프로젝트: soon14/vzan
        /// <summary>
        /// 将一组字典导出成Excel
        /// </summary>
        /// <param name="objList"></param>
        /// <param name="FileName"></param>
        /// <param name="columnInfo"></param>
        public static void ExExcel(List <Dictionary <string, object> > objList, string FileName, Dictionary <string, string> columnInfo)
        {
            if (columnInfo.Count == 0)
            {
                return;
            }
            if (objList.Count == 0)
            {
                return;
            }
            //生成EXCEL的HTML
            string excelStr = "";
            Dictionary <string, object> dic = objList[0];

            foreach (string cName in columnInfo.Keys)
            {
                excelStr += columnInfo[cName] + "\t";
            }
            //如果没有找到可用的属性则结束
            //if (myPro.Count == 0) { return; }
            excelStr += "\n";
            foreach (Dictionary <string, object> obj in objList)
            {
                foreach (string key in columnInfo.Keys)
                {
                    if (obj.ContainsKey(key))
                    {
                        excelStr += obj[key] + "\t";
                    }
                    else
                    {
                        excelStr += "\t";
                    }
                }
                excelStr += "\n";
            }
            //输出EXCEL
            HttpResponse rs = System.Web.HttpContext.Current.Response;

            rs.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            rs.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            rs.ContentType = "application/ms-excel";
            rs.Write(excelStr);
            rs.End();
        }
예제 #21
0
    public static void CreateExcel(HttpResponse resp, DataTable dtcol, DataTable dt, string FileName)
    {
        string headers       = "",
               items         = "";
        List <string> lstkey = new List <string>();


        resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);



        // 写表头
        foreach (DataRow row in dtcol.Rows)
        {
            string key, title;

            key   = row.IsNull("tf_fieldName") ? "" : (string)row["tf_fieldName"];
            title = row.IsNull("tf_title") ? "" : (string)row["tf_title"];
            if (key.Length == 0 || key == "id")
            {
                continue;
            }
            lstkey.Add(key);
            headers += title + '\t';
        }
        headers += "\n";
        resp.Write(headers);

        // 写内容
        foreach (DataRow row in dt.Rows)
        {
            string item = "";

            items = "";
            foreach (string key in lstkey)
            {
                item   = row.IsNull(key) ? "" : row[key].ToString();
                items += item + "\t";
            }
            items += "\n";
            resp.Write(items);
        }
        resp.End();
    }
예제 #22
0
        /// <summary>
        /// 导出Excel Datatable版本 HTML类型
        /// </summary>
        /// <param name="dt">导出的Datatable</param>
        /// <param name="ExcelName">导出EXCEL的名称 不需要要带有扩展名_xls</param>
        public static void DataTableToExcel(DataTable dt, string Title)
        {
            HttpResponse resp      = System.Web.HttpContext.Current.Response;
            string       ExcelName = Title + DateTime.Now.ToString("yyyyMMddHHmmss");

            resp.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + ExcelName + ".xls");
            string colHeaders = "", ls_item = "";

            DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
            int       i     = 0;
            int       cl    = dt.Columns.Count;

            //取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
            //resp.Write("<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" /></head><body><table border=1><tr ");
            //添加网格
            resp.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
                       "<!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>123</x:Name><x:WorksheetOptions><x:Print><x:ValidPrinterInfo /></x:Print></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table><tr ");
            for (i = 0; i < cl; i++)
            {
                colHeaders += "<th>" + dt.Columns[i].Caption.ToString() + "</th>";
            }
            resp.Write(colHeaders + "</tr>");
            //向HTTP输出流中写入取得的数据信息
            //逐行处理数据
            foreach (DataRow row in myRow)
            {
                //当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
                ls_item = "<tr>";
                for (i = 0; i < cl; i++)
                {
                    if (i == (cl - 1))//最后一列,加n
                    {
                        ls_item += "<td>'" + row[i].ToString() + "</td></tr>";
                    }
                    else
                    {
                        ls_item += "<td>'" + row[i].ToString() + "</td>";
                    }
                }
                resp.Write(ls_item);
            }
            resp.Write("</table></body></html>");
            resp.End();
        }
예제 #23
0
        /// <summary>
        /// 输出文件
        /// </summary>
        /// <param name="path">文件物理路径</param>
        /// <param name="outputFilename"></param>
        public void Export(string path, string outputFilename)
        {
            // 判断是否为Firefox浏览器
            if (!HttpContext.Current.Request.Browser.Browser.Equals("Firefox"))
            {
                // 文件名编码处理
                outputFilename = HttpContext.Current.Server.UrlEncode(outputFilename);
            }

            // 设置当前 HTTP 响应头.如果是下载,加上 attachment
            response.AppendHeader("Content-Disposition", "attachment;filename=" + outputFilename);
            // 文件写入响应流以便下载
            response.BinaryWrite(File.ReadAllBytes(path));
            // 向客户端清除当前所有缓存输出.
            response.Flush();
            // 停止执行该页.
            response.End();
        }
예제 #24
0
        /// <summary>
        /// Gets the XSL template.
        /// </summary>
        /// <returns></returns>
        public bool GetXSLTemplate(Page pwPage)
        {
            HttpResponse Response = pwPage.Response;

            Response.Clear();
            int    FileSize    = report.ReportTemplateSize;
            string contentType = "text/xml";
            string fileName    = report.ReportTemplateName;

            Response.ContentType = contentType;
            Response.AppendHeader("Content-Disposition", "inline; filename=" + fileName);

            Response.OutputStream.Write(this.report.ReportTemplateBinary, 0, FileSize);

            Response.End();

            return(true);
        }
예제 #25
0
        protected void DownloadDeals_Click(object sender, EventArgs e)
        {
            try
            {
                string filename = @"~\Newsletter\DEALSNEWSLETTER.pdf";

                HttpResponse res = HttpContext.Current.Response;
                res.Clear();
                res.AppendHeader("content-disposition", "attachment; filename=newsletter.pdf");
                res.ContentType = "application/octet-stream";
                res.WriteFile(filename);
                res.Flush();
                res.End();
            }
            catch (SystemException)
            {
            }
        }
예제 #26
0
        /// <summary>
        /// 将数据表 DataTable 转换为 Excel 工作簿并下载,系统根目录下需要建 Temp 目录,并授予访问者读取、写入权限
        /// </summary>
        /// <param name="dt">数据表</param>
        /// <param name="FileName">要保存的文件名</param>
        public static void DataTableToWorkBookAndDownload(System.Data.DataTable dt, string FileName)
        {
            HttpResponse response = HttpContext.Current.Response;

            response.ContentEncoding = System.Text.Encoding.Default;

            if (String.IsNullOrEmpty(FileName))
            {
                FileName = "Excel.xls";
            }

            Microsoft.Office.Interop.Excel.Workbook wb = DataTableToWorkBook(dt);
            string TempFileName = WriteWorkBookToTempFile(wb);

            response.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
            response.WriteFile(TempFileName); // 将 DataTable 转换成 Excel 工作簿,并下载
            response.End();
        }
예제 #27
0
        public void ProcessRequest(HttpContext context)
        {
            HttpResponse      oResponse = HttpContext.Current.Response;
            HttpServerUtility oServer   = HttpContext.Current.Server;

            string sPath = oServer.MapPath("/Resources") + "\\Mattel Manual Licenciatarios.pdf";

            oResponse.ContentType = "application/pdf";
            oResponse.AppendHeader("Content-Disposition", "attachment; filename=Mattel Manual Licenciatarios.pdf");

            // Write the file to the Response
            const int bufferLength = 10000;

            byte[] buffer   = new Byte[bufferLength];
            int    length   = 0;
            Stream download = null;

            try
            {
                download = new FileStream(sPath, FileMode.Open, FileAccess.Read);
                do
                {
                    if (oResponse.IsClientConnected)
                    {
                        length = download.Read(buffer, 0, bufferLength);
                        oResponse.OutputStream.Write(buffer, 0, length);
                        buffer = new Byte[bufferLength];
                    }
                    else
                    {
                        length = -1;
                    }
                }while (length > 0);
                oResponse.Flush();
                oResponse.End();
            }
            finally
            {
                if (download != null)
                {
                    download.Close();
                }
            }
        }
예제 #28
0
        private void SendHeader(HproseHttpContext context)
        {
            if (OnSendHeader != null)
            {
                OnSendHeader(context);
            }
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            response.ContentType = "text/plain";
            if (p3pEnabled)
            {
                response.AppendHeader("P3P",
                                      "CP=\"CAO DSP COR CUR ADM DEV TAI PSA PSD " +
                                      "IVAi IVDi CONi TELo OTPi OUR DELi SAMi " +
                                      "OTRi UNRi PUBi IND PHY ONL UNI PUR FIN " +
                                      "COM NAV INT DEM CNT STA POL HEA PRE GOV\"");
            }
            if (crossDomainEnabled)
            {
                string origin = request.Headers["Origin"];
                if (origin != null && origin != "" && origin != "null")
                {
                    if (origins.Count == 0 || origins.ContainsKey(origin))
                    {
                        response.AppendHeader("Access-Control-Allow-Origin", origin);
                        response.AppendHeader("Access-Control-Allow-Credentials", "true");
                    }
                }
                else
                {
                    response.AppendHeader("Access-Control-Allow-Origin", "*");
                }
            }
            if (compressionEnabled)
            {
                string acceptEncoding = request.Headers["Accept-Encoding"];
                if (acceptEncoding != null)
                {
                    acceptEncoding = acceptEncoding.ToLower();
                    if (acceptEncoding.IndexOf("deflate") > -1)
                    {
                        response.AppendHeader("Content-Encoding", "deflate");
                    }
                    else if (acceptEncoding.IndexOf("gzip") > -1)
                    {
                        response.AppendHeader("Content-Encoding", "gzip");
                    }
                }
            }
        }
예제 #29
0
 public static void DownloadFile(HttpResponse argResp, StringBuilder argFileStream, string strFileName)
 {
     try
     {
         string value = "attachment; filename=" + strFileName;
         argResp.Clear();
         argResp.Buffer = true;
         argResp.AppendHeader("Content-Disposition", value);
         argResp.ContentType     = "application/ms-excel";
         argResp.ContentEncoding = Encoding.GetEncoding("utf-8");
         argResp.Write(argFileStream);
         argResp.Flush();
         argResp.End();
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #30
0
 public void DownloadFile(HttpResponse argResp, StringBuilder argFileStream, string strFileName)
 {
     try
     {
         string strResHeader = "attachment; filename=" + Guid.NewGuid().ToString() + ".csv";
         if (!string.IsNullOrEmpty(strFileName))
         {
             strResHeader = "inline; filename=" + strFileName;
         }
         argResp.AppendHeader("Content-Disposition", strResHeader); //attachment说明以附件下载,inline说明在线打开
         argResp.ContentType     = "application/ms-excel";
         argResp.ContentEncoding = Encoding.GetEncoding("GB2312");  // Encoding.UTF8;//
         argResp.Write(argFileStream);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
예제 #31
0
        /// <summary>
        /// 输入至Excel文件
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="FileName"></param>
        public static void CreateExcel(DataTable dt, string FileName)
        {
            HttpResponse resp = HttpContext.Current.Response;

            resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName + ".xls");
            string colHeaders = string.Empty;
            string ls_item    = string.Empty;

            DataRow[] myRow = dt.Select();
            int       cl    = dt.Columns.Count;

            for (int i = 0; i < cl; i++)
            {
                if (i == cl - 1)
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            resp.Write(colHeaders);

            foreach (DataRow dr in myRow)
            {
                for (int j = 0; j < cl; j++)
                {
                    if (j == cl - 1)
                    {
                        ls_item += dr[j].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += dr[j].ToString() + "\t";
                    }
                }
            }
            resp.Write(ls_item);
            ls_item = string.Empty;
            resp.End();
        }
 protected void ReturnImage(HttpResponse response, string path, string requestedETag)
 {
     response.Clear();
     var responseETag = LookupEtagFromInput(path);
     if (requestedETag == responseETag)
     {
         response.StatusCode = 304;
         response.StatusDescription = "Not Modified";
         response.AppendHeader("Content-Length", "0");
         response.AppendHeader("Connection", "Close");
         response.End();
     }
     
     response.ContentType = GetContentType(path);
     response.TransmitFile(path);
     response.AppendHeader("Connection", "Keep-Alive");
     // set cache info
     response.Cache.SetCacheability(HttpCacheability.ServerAndPrivate);
     response.Cache.VaryByHeaders["If-Modified-Since"] = true;
     response.Cache.VaryByHeaders["If-None-Match"] = true;
     response.Cache.SetLastModified(File.GetLastWriteTime(path));
     response.Cache.SetETag(responseETag);
     response.End();
 }
예제 #33
0
    public static int numFieldOfImportFile = 16; //number column of import file

    #endregion Fields

    #region Methods

    /// <summary>
    /// Export data to csv and response directly
    /// </summary>
    /// <param name="response">Current page response</param>
    /// <param name="fileName">export file name</param>
    /// <param name="listData">list data to export</param>
    public static void ExportCSV(HttpResponse response, string fileName, List<ImportExportFields> listData)
    {
        //prepare the output stream
        response.Clear();
        response.Buffer = true;
        // response.ContentType = "text/csv";
        response.ContentType = "application/octet-stream";//application/vnd.ms-excel";
        response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
        //response.ContentEncoding = Encoding.Unicode;
        response.ContentEncoding = System.Text.Encoding.UTF8;
        response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

        response.Write(DataToCsvString(listData));

        response.Flush();
        response.End();
    }
예제 #34
0
    /// <summary>
    /// Export excel with HTML format
    /// </summary>
    /// <param name="response">Current page response</param>
    /// <param name="fileName">export file name</param>
    /// <param name="tb">web html table</param>
    public static void ExportExcel(HttpResponse response, string fileName, Table tb)
    {
        try
        {
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

            response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));

            response.Charset = "utf-8";
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());

            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            tb.RenderControl(oHtmlTextWriter);
            response.Write(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
            response.Write(AddExcelStyling());
            string style = @"<style> .text { mso-number-format:\@; } </style>";
            response.Write(style);
            response.Write(oStringWriter.ToString());

            response.End();
        }
        catch (Exception ex)
        {
            Pollinator.Common.Logger.Error("Error occured at " + typeof(ImportExportUltility).Name + " ExportExcel().:", ex);
            response.End();
        }
    }
예제 #35
0
    /// <summary>
    /// Export excel with binary format using ClosedXml library 
    /// </summary>
    /// <param name="response">Current page response</param>
    /// <param name="dt">DataTabe</param>
    /// <param name="columnWidths">double array to define the with of column</param>
    public static void ExportExcel(HttpResponse response, string fileName, DataTable dt, double[] columnWidths)
    {
        try
        {
            int numColumn = columnWidths.Length;
            using (XLWorkbook wb = new XLWorkbook())
            {
                var ws = wb.Worksheets.Add(dt);

                using (MemoryStream MyMemoryStream = new MemoryStream())
                {
                    ws.Tables.First().ShowAutoFilter = false;
                    ws.Tables.First().ShowRowStripes = false;
                    ws.Tables.First().Theme = XLTableTheme.None;

                    ws.SheetView.FreezeRows(1);

                    ws.Row(1).Style.Font.FontColor = XLColor.Black;
                    ws.Row(1).Style.Font.Bold = true;
                    ws.Row(1).Style.Alignment.Indent = 1;
                    ws.Range(1, 1, 1, numColumn).Style.Fill.BackgroundColor = XLColor.LightGreen;

                    ws.Column(1).Width = columnWidths[0];
                    if (columnWidths.Length == 18)
                    {
                        ws.Column(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
                    }
                    ws.Column(1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;

                    for (int i = 1; i < numColumn; i++)
                    {
                        ws.Column(i + 1).Width = columnWidths[i];
                        ws.Column(i + 1).Style.Alignment.WrapText = true;
                        ws.Column(i + 1).Style.Alignment.Vertical = XLAlignmentVerticalValues.Top;
                    }

                    ws.RangeUsed().Style.Border.InsideBorderColor = XLColor.Black;
                    ws.RangeUsed().Style.Border.OutsideBorderColor = XLColor.Black;
                    ws.RangeUsed().Style.Border.InsideBorder = XLBorderStyleValues.Thin;
                    ws.RangeUsed().Style.Border.OutsideBorder = XLBorderStyleValues.Thin;

                    wb.SaveAs(MyMemoryStream);

                    response.Clear();
                    response.Buffer = true;
                    response.Charset = "";
                    response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                    response.AppendHeader("Content-Disposition", string.Format("attachment; filename={0}", fileName));
                    MyMemoryStream.WriteTo(response.OutputStream);
                    response.Flush();
                    response.End();
                }
            }
        }
        catch (Exception ex)
        {
            Pollinator.Common.Logger.Error("Error occured at " + typeof(ImportExportUltility).Name + " ExportExcel().:", ex);
            response.End();
        }
    }