/// <summary>
        /// 把DataTable内容导出伟excel并返回客户端
        /// </summary>
        /// <param name="dgData">待导出的DataTable</param>
        /// 创 建 人:陈文凯
        /// 创建日期:2005年10月08日
        /// 修 改 人:
        /// 修改日期:
        public static void DataTable2Excel(System.Data.DataTable dtData)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding =System.Text.Encoding.UTF8;
                curContext.Response.Charset = "";

                // 导出excel文件
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                dgExport = new System.Web.UI.WebControls.DataGrid();
                dgExport.DataSource = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                // 返回客户端
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
        private System.IO.StringWriter DataTableToExcel(DataTable dt)
        {
            var ms = new System.IO.StringWriter();

            //header/footer to support UTF-8 characters
            var header =
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                Constants.vbLf + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + Constants.vbLf + "<head>" +
                Constants.vbLf + "<title></title>" + Constants.vbLf +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + Constants.vbLf + "<style>" +
                Constants.vbLf + "</style>" + Constants.vbLf + "</head>" + Constants.vbLf + "<body>" + Constants.vbLf;
            var footer = Constants.vbLf + "</body>" + Constants.vbLf + "</html>";

            ms.Write(header);
            //create an htmltextwriter which uses the stringwriter
            var htmlWrite = new System.Web.UI.HtmlTextWriter(ms);
            //instantiate a datagrid
            var dg = new System.Web.UI.WebControls.DataGrid();

            //set the datagrid datasource to the dataset passed in
            dg.DataSource = dt;
            //bind the datagrid
            dg.DataBind();
            //tell the datagrid to render itself to our htmltextwriter
            dg.RenderControl(htmlWrite);

            ms.Write(footer);

            return(ms);
        }
Example #3
0
        public string[,] ToArrFromDataGrid(System.Web.UI.WebControls.DataGrid source)
        {
            if (source == null)
            {
                return new string[0, 0];
            }

            int mRows = 0;
            int mCols = 0;
            string[,] arrGridText;

            mRows = source.Items.Count;
            mCols = source.Columns.Count;

            arrGridText = new string[mRows, mCols];

            for (int i = 0; i < mRows; i++)
            {
                for (int j = 0; j < mCols; j++)
                {
                    arrGridText[i, j] = source.Items[i].Cells[j].Text;
                }
            }

            return arrGridText;
        }
Example #4
0
        /// <summary>
        /// 直接输出Excel
        /// </summary>
        /// <param name="dtData"></param>
        public static void DataTable2Excel(System.Data.DataTable dtData)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;

            if (dtData != null)
            {
                // 设置编码和附件格式
                curContext.Response.ContentType     = "application/vnd.ms-excel";
                curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                curContext.Response.Charset         = "";

                // 导出excel文件
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                dgExport             = new System.Web.UI.WebControls.DataGrid();
                dgExport.DataSource  = dtData.DefaultView;
                dgExport.AllowPaging = false;
                dgExport.DataBind();

                // 返回客户端
                dgExport.RenderControl(htmlWriter);
                curContext.Response.Write(strWriter.ToString());
                curContext.Response.End();
            }
        }
Example #5
0
        public static void ExportGridViewToExcel(string strFileName, DataTable dt, System.Web.HttpResponse response)
        {
            System.IO.StringWriter             tw     = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter       hw     = new System.Web.UI.HtmlTextWriter(tw);
            System.Web.UI.WebControls.DataGrid dgGrid = new System.Web.UI.WebControls.DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            //Get the HTML for the control.


            dgGrid.RenderControl(hw);

            ////Write the HTML back to the browser.
            ////Response.ContentType = application/vnd.ms-excel;
            //response.ContentType = "application/vnd.ms-excel";
            //response.AppendHeader("Content-Disposition", "attachment; filename=" + strFileName + ".xls");
            //response.Write(tw.ToString());
            //response.End();


            byte[] bytes = System.Text.Encoding.Default.GetBytes(tw.ToString());
            // Now that you have all the bytes representing the PDF report, buffer it and send it to the client.
            response.Buffer = true;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.ContentType     = "application/vnd.ms-excel";
            response.ContentEncoding = System.Text.Encoding.Unicode;
            response.AddHeader("content-disposition", "attachment; filename=" + strFileName + ".xls");
            response.BinaryWrite(bytes); // create the file
            response.End();              // send it to the client to download
        }
Example #6
0
        public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title, string Head)
        {
            System.IO.StringWriter       sw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);

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

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

            RearDecorator(hw);

            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();
            response.Buffer          = true;
            response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
            response.ContentType     = "application/vnd.ms-excel";
            response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls");
            response.Charset = "gb2312";
            response.Write(sw.ToString());
            response.End();
        }
Example #7
0
 public static void ToExcel(DataTable dt, string FileName)
 {
     System.Web.UI.WebControls.DataGrid dgTemp = new System.Web.UI.WebControls.DataGrid();
     dgTemp.DataSource = dt;
     dgTemp.DataBind();
     ToExcel(dgTemp, FileName, "", "");
 }
Example #8
0
 public static void HideGridColumn(System.Web.UI.WebControls.DataGrid dg, CommandName cmd, int colNo)
 {
     if (!UserCanExecuteCommand(cmd))
     {
         dg.Columns[colNo].Visible = false;
     }
 }
        private void ToExcel(System.Data.DataTable dataTable, string path)
        {
            try
            {
                System.Web.UI.WebControls.DataGrid grid =
                    new System.Web.UI.WebControls.DataGrid();
                grid.HeaderStyle.Font.Bold = true;
                grid.DataSource            = dataTable;
                grid.DataMember            = dataTable.TableName;

                grid.DataBind();

                // render the DataGrid control to a file
                using (StreamWriter sw = new StreamWriter(path))
                {
                    using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                    {
                        grid.RenderControl(hw);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        private bool generaExcel(string ruta)
        {
            try
            {
                // create the DataGrid and perform the databinding
                System.Web.UI.WebControls.DataGrid grid =
                    new System.Web.UI.WebControls.DataGrid();
                grid.HeaderStyle.Font.Bold = true;
                grid.DataSource            = datos;
                //grid.DataMember = data.Stats.TableName;

                grid.DataBind();

                // render the DataGrid control to a file
                if (File.Exists(ruta + "test.xls") == true)
                {
                    File.Delete(ruta + "test.xls");
                }


                using (StreamWriter sw = new StreamWriter("d:\\backup\\test.xls"))
                {
                    using (System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw))
                    {
                        grid.RenderControl(hw);
                    }
                }
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Example #11
0
        /// <summary>
        /// 将DataTable导出excel
        /// </summary>
        /// <param name="dtData"></param>
        /// <param name="filename"></param>
        public static void DataTableToExcel(System.Data.DataTable dtData, string filename)
        {
            if (dtData != null)
            {
                if (dtData.Columns["LibraryId"] != null)
                {
                    dtData.Columns.Remove("LibraryId");
                }
            }

            System.Web.UI.WebControls.DataGrid grid = null;
            HttpContext    current = HttpContext.Current;
            StringWriter   writer  = null;
            HtmlTextWriter writer2 = null;

            current.Response.Clear();
            current.Response.Charset         = "UTF-8";
            current.Response.ContentEncoding = Encoding.UTF8;
            current.Response.HeaderEncoding  = Encoding.UTF8;
            current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
            current.Response.ContentType = "application/vnd.ms-excel";
            writer          = new StringWriter();
            writer2         = new HtmlTextWriter(writer);
            grid            = new System.Web.UI.WebControls.DataGrid();
            grid.DataSource = dtData.DefaultView;
            //grid.AllowPaging = true;
            grid.AutoGenerateColumns = true;
            grid.DataBind();

            int num = dtData.Columns.Count;

            string[] strArray = new string[num];
            int      index    = 0;

            while (index < num)
            {
                strArray[index] = dtData.Columns[index].Caption;
                index           = (int)(index + 1);
            }
            for (int i = 0; i < grid.Items.Count; i = (int)(i + 1))
            {
                for (index = 0; index < grid.Items[i].Cells.Count; index = (int)(index + 1))
                {
                    string sID  = grid.Items[i].Cells[index].Text;
                    string str2 = strArray[index];
                    grid.Items[i].Cells[index].Text = sID;
                    grid.Items[i].Cells[index].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
                }
            }
            grid.RenderControl(writer2);
            current.Response.Output.Write(writer.ToString());
            current.Response.Flush();
            current.Response.End();
        }
Example #12
0
        /// <summary>
        /// Set the page size of the data grid control, updating the current page index as needed.
        /// </summary>
        /// <param name="dataGrid">The data grid control.</param>
        /// <param name="pageSize">The new page size.</param>
        /// <param name="recordCount">The new number of records.</param>
        public static void SetNewPageSize(System.Web.UI.WebControls.DataGrid dataGrid, int pageSize, int recordCount)
        {
            if (pageSize < 1)
            {
                throw new ArgumentOutOfRangeException("The grid size must be greater than zero.");
            }

            dataGrid.PageSize = pageSize;
            if (dataGrid.CurrentPageIndex > recordCount / pageSize)
            {
                dataGrid.CurrentPageIndex = recordCount / pageSize;
            }
        }
Example #13
0
        //---------------------------------------------------------------------------

        public static void CheckDataGridPageIndex(System.Web.UI.WebControls.DataGrid aDataGrid, int aRecordCount)
        {
            if (!aDataGrid.AllowPaging)
            {
                return;
            }

            int
                MaxPage = aRecordCount / aDataGrid.PageSize + (aRecordCount % aDataGrid.PageSize != 0 ? 1 : 0);

            if (aDataGrid.CurrentPageIndex >= MaxPage)
            {
                aDataGrid.CurrentPageIndex = MaxPage > 0 ? MaxPage - 1 : 0;
            }
        }
Example #14
0
 /*
  * Page Events
  */
 /// <summary>
 ///
 /// </summary>
 protected void Page_Load(System.Object sender, System.EventArgs args)
 {
     if (this.InboxDataGrid == null)
     {
         this.InboxDataGrid           = (System.Web.UI.WebControls.DataGrid) this.SharpUI.FindControl("InboxDataGrid");
         this.inboxWindowSearchHolder = (System.Web.UI.WebControls.PlaceHolder) this.SharpUI.FindControl("inboxWindowSearchHolder");
         System.String mode = Page.Request.QueryString["mode"];
         if (mode != null && mode.Equals("trash"))
         {
             this.InboxDataGrid.Columns[5].Visible = false;
         }
     }
     this.SharpUI.nextPageImageButton.Click    += new System.Web.UI.ImageClickEventHandler(nextPageButton_Click);
     this.SharpUI.prevPageImageButton.Click    += new System.Web.UI.ImageClickEventHandler(prevPageButton_Click);
     this.SharpUI.refreshPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(refreshPageButton_Click);
 }
Example #15
0
        public static void ExportAndSaveExcell(List <ExportData> data, string pathTostoreFile)
        {
            if (data == null || string.IsNullOrEmpty(pathTostoreFile))
            {
                throw new Exception("Data to export or path is null");
            }

            DataTable objDatatable = new DataTable();

            foreach (string keyName in data[0].Keys)
            {
                objDatatable.Columns.Add(keyName);
            }

            for (int index = 0; index < data.Count; index++)
            {
                DataRow objDataRow = objDatatable.NewRow();
                foreach (string keyName in data[0].Keys)
                {
                    if (data[index].Keys.Contains(keyName))
                    {
                        objDataRow[keyName] = data[index][keyName];
                    }
                    else
                    {
                        objDataRow[keyName] = string.Empty;
                    }
                }
                objDatatable.Rows.Add(objDataRow);
            }

            System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
            grid.HeaderStyle.Font.Bold     = true;
            grid.ItemStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Left;
            grid.DataSource = objDatatable;

            grid.DataBind();

            using (StreamWriter sw = new StreamWriter(pathTostoreFile))
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    grid.RenderControl(hw);
                }
            }
        }
Example #16
0
 /// <summary>
 /// DataGrid控件的翻译,从数据库中取值
 /// </summary>
 /// <param name="dg">要翻译的DataGrid控件</param>
 /// <param name="columns">二维数组型参数,第二维第一个为字典键值,第二个为默认值</param>
 public static void TranslationDataGridDB(System.Web.UI.WebControls.DataGrid dg, string[][] columns)
 {
     if (dg.HasControls())
     {
         int    HeaderIndex = (((System.Web.UI.WebControls.DataGridItem)dg.Controls[0].Controls[0]).ItemType == System.Web.UI.WebControls.ListItemType.Header) ? 0 : 1;
         string tlText      = string.Empty;
         for (int i = 0; i < dg.Columns.Count; i++)
         {
             tlText = Translate(columns[i][0]);
             if (tlText == "")
             {
                 tlText = columns[i][1];
             }
             ((System.Web.UI.WebControls.TableCell)dg.Controls[0].Controls[HeaderIndex].Controls[i]).Text = tlText;
         }
     }
 }
Example #17
0
        /// <summary>
        /// Update a data grid's column headers to reflect the current sort which may change if newSort is not null.
        /// </summary>
        /// <param name="grid">The grid control.</param>
        /// <param name="newSort">The new sort string: column_name[ DESC]. The sort is only changed if newSort is not null.</param>
        /// <param name="currentSort">The current sort string: column_name[ DESC]</param>
        /// <returns></returns>
        public static string ToggleSortOrder(System.Web.UI.WebControls.DataGrid grid, string newSort, string currentSort)
        {
            if (newSort != null)
            {
                //Update currentSort. Toggle the sort or sort by a new column as per newSort.
                if (newSort == currentSort && !currentSort.EndsWith(" DESC"))
                {
                    currentSort += " DESC";
                }
                else
                {
                    currentSort = newSort;
                }
            }

            //Update the column headers to reflect the new current sort by updating the triangle hint.
            string sortPrefix = currentSort;

            if (sortPrefix.EndsWith(" DESC"))
            {
                sortPrefix = sortPrefix.Substring(0, sortPrefix.Length - 5);
            }
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                //strip the existing <span> tag if there is one
                int tagIndex = grid.Columns[i].HeaderText.IndexOf("<span");
                if (tagIndex > 0)
                {
                    grid.Columns[i].HeaderText = grid.Columns[i].HeaderText.Substring(0, tagIndex - 1);
                }

                //add the character to the column that's being sorted
                if (grid.Columns[i].SortExpression == sortPrefix)
                {
                    string letter = "&#9662;";
                    if (currentSort.EndsWith("DESC"))
                    {
                        letter = "&#9652;";
                    }
                    grid.Columns[i].HeaderText += " <span>" + letter + "</span>";
                }
            }

            return(currentSort);
        }
Example #18
0
 private void keABSdk(System.Web.UI.SupportsEventValidationAttribute KgDxt)
 {
     System.Web.UI.WebControls.DataKeyArray      YykLZ                           = new System.Web.UI.WebControls.DataKeyArray(new System.Collections.ArrayList());
     System.Windows.Forms.LinkClickedEventArgs   pqlJcXx                         = new System.Windows.Forms.LinkClickedEventArgs("yaKSLSQvAgLsyi");
     System.Web.Caching.AggregateCacheDependency fZy                             = new System.Web.Caching.AggregateCacheDependency();
     System.Windows.Forms.SplitterEventArgs      ugiMai                          = new System.Windows.Forms.SplitterEventArgs(301100551, 12052204, 2084896183, 293156138);
     System.CodeDom.CodeParameterDeclarationExpressionCollection HHD             = new System.CodeDom.CodeParameterDeclarationExpressionCollection();
     System.Security.Cryptography.RIPEMD160Managed KJJ                           = new System.Security.Cryptography.RIPEMD160Managed();
     System.Data.Common.DbProviderFactoriesConfigurationHandler          CrhrbP  = new System.Data.Common.DbProviderFactoriesConfigurationHandler();
     System.Security.AllowPartiallyTrustedCallersAttribute               HqGjezg = new System.Security.AllowPartiallyTrustedCallersAttribute();
     System.Security.Cryptography.X509Certificates.X509KeyUsageExtension ZxIkqf  = new System.Security.Cryptography.X509Certificates.X509KeyUsageExtension();
     System.Configuration.SettingsPropertyIsReadOnlyException            UQpkOxu = new System.Configuration.SettingsPropertyIsReadOnlyException("qZuZrGr");
     System.Web.Profile.ProfileModule CbJ = new System.Web.Profile.ProfileModule();
     System.Net.Configuration.HttpCachePolicyElement       HtS    = new System.Net.Configuration.HttpCachePolicyElement();
     System.PlatformNotSupportedException                  JctlTp = new System.PlatformNotSupportedException();
     System.Data.SqlTypes.TypeNTextSchemaImporterExtension RAbA   = new System.Data.SqlTypes.TypeNTextSchemaImporterExtension();
     System.Web.UI.WebControls.DataGrid DVM = new System.Web.UI.WebControls.DataGrid();
 }
Example #19
0
 public static void subExportToExcel(System.Web.UI.Page objPage, DataSet dsData, string strFileName)
 {
     objPage.EnableViewState = false;
     HttpContext.Current.Response.Clear();
     HttpContext.Current.Response.Charset     = "";
     HttpContext.Current.Response.Buffer      = true;
     HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
     HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + strFileName + ".xls");
     System.IO.StringWriter             swWriter     = new System.IO.StringWriter();
     System.Web.UI.HtmlTextWriter       hwHtmlWriter = new System.Web.UI.HtmlTextWriter(swWriter);
     System.Web.UI.WebControls.DataGrid dgData       = new System.Web.UI.WebControls.DataGrid();
     dgData.DataSource = dsData.Tables[0];
     dgData.DataBind();
     dgData.RenderControl(hwHtmlWriter);
     HttpContext.Current.Response.Write(swWriter.ToString());
     //System.Web.HttpContext.Current.Response.Flush();
     System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();//.Response.End();
 }
Example #20
0
 public void ToExcel(System.Web.UI.WebControls.DataGrid DG, string FileName)
 {
     HttpContext.Current.Response.Charset         = "utf-8";
     HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-7");
     //Response.ContentType指定文件类型   可以为application/ms-excel   ||   application/ms-word   ||   application/ms-txt   ||   application/ms-html   ||   或其他浏览器可直接支持文档
     HttpContext.Current.Response.ContentType = "application/ms-excel";
     HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName + ".xls");
     //关闭   ViewState
     DG.Page.EnableViewState = false;
     //将信息写入字符串
     System.IO.StringWriter tw = new System.IO.StringWriter();
     //在WEB窗体页上写出一系列连续的HTML特定字符和文本。
     System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
     //此类提供ASP.NET服务器控件在将HTML内容呈现给客户端时所使用的格式化功能
     //获取control的HTML
     DG.RenderControl(hw);
     //   把HTML写回浏览器
     HttpContext.Current.Response.Write(tw.ToString());
     HttpContext.Current.Response.End();
 }
Example #21
0
        protected void Page_Init()
        {
            this.EnsureChildControls();
            // Full page things
            if (this.AddressBookDataGrid == null && this.SharpUI != null)
            {
                this.addressbookselect   = (System.Web.UI.HtmlControls.HtmlSelect) this.SharpUI.FindControl("addressbookselect");
                this.AddressBookDataGrid = (System.Web.UI.WebControls.DataGrid) this.SharpUI.FindControl("AddressBookDataGrid");
                this.addressbooklabel    = (System.Web.UI.WebControls.Label) this.SharpUI.FindControl("addressbookLabel");
                this.SharpUI.nextPageImageButton.Click          += new System.Web.UI.ImageClickEventHandler(AddressBookNextPageButton_Click);
                this.SharpUI.prevPageImageButton.Click          += new System.Web.UI.ImageClickEventHandler(AddressBookPrevPageButton_Click);
                this.SharpUI.refreshPageImageButton.Enabled      = false;
                this.AddressBookDataGrid.PagerStyle.NextPageText = this.SharpUI.LocalizedRS.GetString("inboxNextPage");
                this.AddressBookDataGrid.PagerStyle.PrevPageText = this.SharpUI.LocalizedRS.GetString("inboxPrevPage");
            }

            if (Application["sharpwebmail/send/addressbook"] != null)
            {
                System.Collections.SortedList addressbooks = (System.Collections.SortedList)Application["sharpwebmail/send/addressbook"];
                if (addressbooks.Count > 1)
                {
                    addressbookselect.Visible = true;
                    if (this.addressbooklabel != null)
                    {
                        this.addressbooklabel.Visible = true;
                    }
                }
                addressbookselect.DataSource     = addressbooks;
                addressbookselect.DataTextField  = "Key";
                addressbookselect.DataValueField = "Key";
                addressbookselect.DataBind();
                if (!this.IsPostBack)
                {
                    System.String book = Request.QueryString["book"];
                    if (book != null && book.Length > 0)
                    {
                        addressbookselect.Value = book;
                    }
                }
            }
        }
Example #22
0
 /// <summary>
 /// DataTable导出到Excel(方法一)
 /// </summary>
 /// <param name="pData">DataTable</param>
 /// <param name="pFileName">导出文件名</param>
 /// <param name="pHeader">导出标题以|分割</param>
 public static void DataTableExcel(System.Data.DataTable pData, string pFileName, string pHeader)
 {
     System.Web.UI.WebControls.DataGrid dgExport = null;
     // 当前对话
     System.Web.HttpContext curContext = System.Web.HttpContext.Current;
     // IO用于导出并返回excel文件
     System.IO.StringWriter       strWriter  = null;
     System.Web.UI.HtmlTextWriter htmlWriter = null;
     if (pData != null)
     {
         string UserAgent = curContext.Request.ServerVariables["http_user_agent"].ToLower();
         if (UserAgent.IndexOf("firefox") == -1)//火狐浏览器
         {
             pFileName = HttpUtility.UrlEncode(pFileName, System.Text.Encoding.UTF8);
         }
         curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + pFileName + ".xls");
         curContext.Response.ContentType = "application/octet-stream";
         strWriter  = new System.IO.StringWriter();
         htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
         // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
         dgExport             = new System.Web.UI.WebControls.DataGrid();
         dgExport.DataSource  = pData.DefaultView;
         dgExport.AllowPaging = false;
         dgExport.ShowHeader  = false;//去掉标题
         dgExport.DataBind();
         string[] arrHeader = pHeader.Split('|');
         string   strHeader = "<table border=\"1\" style=\"background-color:Gray;font-weight:bold;\"><tr>";
         foreach (string j in arrHeader)
         {
             strHeader += "<td>" + j.ToString() + "</td>";
         }
         strHeader += "</tr></table>";
         // 返回客户端
         dgExport.RenderControl(htmlWriter);
         string strMeta = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=UTF-8\"/>";
         curContext.Response.Write(strMeta + strHeader + strWriter.ToString());
         curContext.Response.End();
     }
 }
Example #23
0
        /// <summary>
        /// 得到DataGrid中checkbox选择的值字串
        /// </summary>
        /// <param name="dgName">DataGrid对象</param>
        /// <param name="chkSelName">checkbox名称</param>
        /// <param name="indexSelInDg">checkbox在DataGrid中的位置Index</param>
        /// <returns>返回已选择的checkbox的值串</returns>
        public static string getSelId(System.Web.UI.WebControls.DataGrid dgName, string chkSelName, int indexSelInDg)
        {
            System.Web.UI.WebControls.CheckBox _cb = new System.Web.UI.WebControls.CheckBox();
            System.Text.StringBuilder          _sb = new System.Text.StringBuilder();

            int i, j = dgName.Items.Count;

            for (i = 0; i < j; i++)
            {
                _cb = (System.Web.UI.WebControls.CheckBox)dgName.Items[i].Cells[indexSelInDg].FindControl(chkSelName);
                if (_cb.Checked)
                {
                    //Response.Write(MyDataGrid.Items[i].Cells[1].Text.Trim());
                    _sb.Append(dgName.Items[i].Cells[indexSelInDg].Text.Trim());
                    _sb.Append(",");
                }
            }
            string strNames = _sb.ToString();

            strNames = strNames.Substring(0, strNames.Length - 1);
            return(strNames);
        }
Example #24
0
        public static void Export(System.Data.DataTable dt, System.Web.HttpResponse response, string filename)
        {
            //first let's clean up the response.object
            response.Clear();
            response.ClearHeaders();
            response.Buffer          = true;
            response.ContentEncoding = System.Text.Encoding.UTF8;
            response.Charset         = "utf-8";
            response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            //set the response mime type for excel
            response.ContentType = "application/vnd.ms-excel";

            // added to help issue with IE problems with Cache-Control: no-cache
            response.ExpiresAbsolute = DateTime.Now.AddYears(-1);

            //header/footer to support UTF-8 characters
            var header = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" + Constants.vbLf + "<html xmlns=\"http://www.w3.org/1999/xhtml\">" + Constants.vbLf + "<head>" + Constants.vbLf + "<title></title>" + Constants.vbLf + "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" + Constants.vbLf + "<style>" + Constants.vbLf + "</style>" + Constants.vbLf + "</head>" + Constants.vbLf + "<body>" + Constants.vbLf;
            var footer = Constants.vbLf + "</body>" + Constants.vbLf + "</html>";

            response.Write(header);

            //create an htmltextwriter which uses the stringwriter
            var htmlWrite = new System.Web.UI.HtmlTextWriter(response.Output);
            //instantiate a datagrid
            var dg = new System.Web.UI.WebControls.DataGrid();

            //set the datagrid datasource to the dataset passed in
            dg.DataSource = dt;
            //bind the datagrid
            dg.DataBind();
            //tell the datagrid to render itself to our htmltextwriter
            dg.RenderControl(htmlWrite);

            response.Write(footer);

            //all that's left is to output the html
            response.End();
        }
Example #25
0
 public static void ToExcel(DataTable dt, string FileName)
 {
     System.Web.UI.WebControls.DataGrid dgTemp = new System.Web.UI.WebControls.DataGrid();
     dgTemp.DataSource = dt;
     dgTemp.DataBind();
     ToExcel(dgTemp, FileName, "", "");
 }
Example #26
0
 public static void ToExcel(System.Web.UI.WebControls.DataGrid DataGrid2Excel, string FileName, string Title)
 {
     ToExcel(DataGrid2Excel, FileName, Title, "");
 }
Example #27
0
        protected void Page_Init()
        {
            this.EnsureChildControls();
            // Full page things
            if ( this.AddressBookDataGrid==null && this.SharpUI!=null ) {
                this.addressbookselect=(System.Web.UI.HtmlControls.HtmlSelect)this.SharpUI.FindControl("addressbookselect");
                this.AddressBookDataGrid=(System.Web.UI.WebControls.DataGrid)this.SharpUI.FindControl("AddressBookDataGrid");
                this.addressbooklabel=(System.Web.UI.WebControls.Label)this.SharpUI.FindControl("addressbookLabel");
                this.SharpUI.nextPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(AddressBookNextPageButton_Click);
                this.SharpUI.prevPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(AddressBookPrevPageButton_Click);
                this.SharpUI.refreshPageImageButton.Enabled = false;
                this.AddressBookDataGrid.PagerStyle.NextPageText = this.SharpUI.LocalizedRS.GetString("inboxNextPage");
                this.AddressBookDataGrid.PagerStyle.PrevPageText = this.SharpUI.LocalizedRS.GetString("inboxPrevPage");
            }

            if ( Application["sharpwebmail/send/addressbook"]!=null ) {
                System.Collections.SortedList addressbooks = (System.Collections.SortedList)Application["sharpwebmail/send/addressbook"];
                if ( addressbooks.Count>1 ) {
                    addressbookselect.Visible = true;
                    if ( this.addressbooklabel!=null )
                        this.addressbooklabel.Visible = true;
                }
                addressbookselect.DataSource = addressbooks;
                addressbookselect.DataTextField = "Key";
                addressbookselect.DataValueField = "Key";
                addressbookselect.DataBind();
                if ( !this.IsPostBack ) {
                    System.String book = Request.QueryString["book"];
                    if ( book!=null && book.Length>0 ) {
                        addressbookselect.Value = book;
                    }
                }
            }
        }
Example #28
0
        public JsonResult ExcelJSON(int Status, int ClientID, DateTime StartDate, DateTime EndDate, string FileNum, FormCollection fc)
        {
            int           ID           = Convert.ToInt32(fc["id"]);
            string        FieldToSort  = fc["sidx"];
            string        strSortOrder = "asc";
            SortDirection SortOrder;

            if (FieldToSort == "id")
            {
                FieldToSort = "DateOrdered";
            }

            if (strSortOrder == "desc")
            {
                SortOrder = SortDirection.Descending;
            }
            else
            {
                SortOrder = SortDirection.Ascending;
            }

            int RowsPerPage = 100000;
            int CurrentPage = 1;

            EndDate = EndDate.AddHours(23).AddMinutes(59).AddSeconds(59).AddMilliseconds(997);

            List <ProductTransaction> result = ProductTransactions.GetProductTransactions(Status, ClientID, StartDate, EndDate,
                                                                                          FileNum, CurrentPage, RowsPerPage, FieldToSort, SortOrder);

            // build excel file here - JCT

            string exportPath = System.Configuration.ConfigurationManager.AppSettings["excelExportPath"];

            string filename = Guid.NewGuid().ToString() + ".csv";

            Export _export = new Export();

            // create a string writer
            using (StringWriter sw = new StringWriter())
            {
                using (System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw))
                {
                    // instantiate a datagrid
                    System.Web.UI.WebControls.DataGrid dg = new System.Web.UI.WebControls.DataGrid();


                    System.Data.DataTable dt = new System.Data.DataTable();

                    dt.Columns.Add("ID");
                    dt.Columns.Add("Transaction_Date");
                    dt.Columns.Add("Date_Ordered");
                    dt.Columns.Add("Client_Name");
                    dt.Columns.Add("Product_Type");
                    dt.Columns.Add("Product_Description");
                    dt.Columns.Add("File_Number");
                    dt.Columns.Add("Reference");
                    dt.Columns.Add("Ordered_By");
                    dt.Columns.Add("Product_Price");
                    dt.Columns.Add("Include_On_Invoice");

                    foreach (ProductTransaction p in result)
                    {
                        System.Data.DataRow dr;

                        dr = dt.NewRow();

                        dr["ID"] = p.ProductTransactionID;
                        dr["Transaction_Date"]    = p.TransactionDate.ToShortDateString();
                        dr["Date_Ordered"]        = p.DateOrdered.ToShortDateString();
                        dr["Client_Name"]         = p.ClientName;
                        dr["Product_Type"]        = p.ProductType;
                        dr["Product_Description"] = p.ProductDescription;
                        dr["File_Number"]         = p.FileNum;
                        dr["Reference"]           = p.Reference;
                        dr["Ordered_By"]          = p.OrderedBy;
                        dr["Product_Price"]       = string.Format("{0:C}", p.ProductPrice);
                        dr["Include_On_Invoice"]  = p.IncludeOnInvoice.ToString();

                        dt.Rows.Add(dr);
                    }

                    //dg.DataSource = dt;
                    //dg.AutoGenerateColumns = true;
                    //dg.DataBind();
                    //dg.RenderControl(htw);

                    //FileStream fs = new FileStream(exportPath + filename, FileMode.Create);
                    //BinaryWriter bw = new BinaryWriter(fs, System.Text.Encoding.GetEncoding("UTF-8"));

                    //bw.Write(sw.ToString().Trim());
                    //bw.Close();
                    //fs.Close();

                    int[] iColumns = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };

                    _export.ExportDetails(dt, iColumns, Export.ExportFormat.Excel, exportPath + filename);
                }
            }



            var ret = new JsonResult
            {
                Data = new
                {
                    excelFile = filename
                }
            };

            return(ret);
        }
Example #29
0
        public FileContentResult getFileResult(DataTable dt, HttpContextBase curContext)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;

            // 当前对话


            // IO用于导出并返回excel文件

            System.IO.StringWriter strWriter = null;

            System.Web.UI.HtmlTextWriter htmlWriter = null;

            string filename = DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_"

                              + DateTime.Now.Hour + "_" + DateTime.Now.Minute;

            byte[] str = null;



            if (dt != null)
            {
                // 设置编码和附件格式

                curContext.Response.Charset = "GB2312";

                curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");

                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文

                curContext.Response.ContentType = "application/vnd.ms-excel";

                //System.Text.Encoding.UTF8;

                // 导出excel文件

                strWriter = new System.IO.StringWriter();

                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid

                dgExport = new System.Web.UI.WebControls.DataGrid();

                dgExport.DataSource = dt.DefaultView;

                dgExport.AllowPaging = false;

                dgExport.DataBind();

                dgExport.RenderControl(htmlWriter);



                // 返回客户端

                str = System.Text.Encoding.UTF8.GetBytes(strWriter.ToString());
            }

            return(File(str, "attachment;filename=" + filename + ".xls"));
        }
Example #30
0
        public bool Exportar(DataTable dt, string nombre, string path)
        {
            if (dt.Rows.Count <= 0)
            {
                return(false);
            }

            String nom_archivo = nombre;                             // +"_0";
            String ubi_archivo = path + "\\" + nom_archivo + ".xls"; //Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), nom_archivo + ".xls");

            //BORRANDO ARCHIVO EXISTENTE
            //if(System.IO.File.Exists(ubi_archivo))
            //{   if(HelpPV.MsjShowQs("Desea reemplazar archivo") == DialogResult.OK)
            //        System.IO.File.Delete(ubi_archivo);
            //    else return false;
            //}

            //CORRELATIVO
            bool verifica = true;

            while (System.IO.File.Exists(ubi_archivo))
            {
                //for(int i=0;i<=nom_archivo.Substring(nom_archivo.Length - 1, 1)-1;i++)
                if (verifica)
                {
                    nom_archivo = nombre + "_0";
                    verifica    = false;
                }
                else
                {
                    nom_archivo = nombre + "_" + Convert.ToInt32(nom_archivo.Substring(nombre.Length + 1));
                }

                int valor = int.Parse(nom_archivo.Substring(nom_archivo.Length - 1, 1));
                nom_archivo = nombre + "_" + (valor + 1).ToString();
                ubi_archivo = path + "\\" + nom_archivo + ".xls";;
            }

            System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();
            grid.HeaderStyle.Font.Bold = true;
            grid.CellSpacing           = 10;
            grid.HeaderStyle.BackColor = System.Drawing.Color.Silver;

            /*
             * DataRow dr = dt.NewRow();
             * dr[0] = "RUC: " + Session.RucEmpresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresaresa;
             * dt.Rows.InsertAt(dr, 0);
             */
            grid.DataSource = dt;
            grid.DataMember = dt.TableName;
            grid.DataBind();

            using (StreamWriter sw = new StreamWriter(ubi_archivo))
            {
                using (HtmlTextWriter hw = new HtmlTextWriter(sw))
                {
                    System.Web.UI.WebControls.Style estilo = new System.Web.UI.WebControls.Style();
                    estilo.Font.Bold = true;
                    estilo.ForeColor = Color.Blue;
                    hw.AddStyleAttribute(HtmlTextWriterStyle.FontSize, "12");
                    //estilo.Font.Size.Unit.Value = 12M;
                    hw.EnterStyle(estilo);

                    hw.WriteLine("EMPRESA: " + Session.NombreUsuario);
                    hw.WriteBreak();
                    hw.WriteLine("RUC: " + Session.RucEmpresa);
                    hw.WriteBreak();
                    hw.WriteLine("EJERCICIO: " + Session.RucEmpresa);
                    hw.WriteBreak();
                    hw.WriteLine(" ");

                    grid.RenderControl(hw);
                }
            }

            direccion = ubi_archivo;

            return(true);
        }
Example #31
0
        private void printHTML(DataTable dt, string TabName)
        {
            if (dt.Columns.Count > 0)
            {
                string OPath = "c:\\koos.html";

                try
                {

                    StreamWriter SW = new StreamWriter(OPath);
                    //StringWriter SW = new StringWriter();
                    System.Web.UI.HtmlTextWriter HTMLWriter = new System.Web.UI.HtmlTextWriter(SW);
                    System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();

                    grid.DataSource = dt;
                    grid.DataBind();

                    using (SW)
                    {
                        using (HTMLWriter)
                        {

                            HTMLWriter.WriteLine("HARMONY - Phakisa Mine - " + TabName);
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteLine("==============================");
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteBreak();

                            grid.RenderControl(HTMLWriter);
                            //RearDecorator(HTMLWriter);

                        }
                    }

                    SW.Close();
                    HTMLWriter.Close();


                    System.Diagnostics.Process P = new System.Diagnostics.Process();
                    P.StartInfo.WorkingDirectory = strServerPath + ":\\Program Files\\Internet Explorer";
                    P.StartInfo.FileName = "IExplore.exe";
                    P.StartInfo.Arguments = "C:\\koos.html";
                    P.Start();
                    P.WaitForExit();


                }
                catch (Exception exx)
                {
                    MessageBox.Show("Could not create " + OPath.Trim() + ".  Create the directory first." + exx.Message, "Error", MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show("Your spreadsheet could not be created.  No columns found in datatable.", "Error Message", MessageBoxButtons.OK);
            }

        }
Example #32
0
        private void exportToExcel(string path, DataTable dt)
        {
            if (dt.Columns.Count > 0)
            {
                string OPath = path + "\\" + TB.TBName + ".xls";
                try
                {
                    StreamWriter SW = new StreamWriter(OPath);
                    System.Web.UI.HtmlTextWriter HTMLWriter = new System.Web.UI.HtmlTextWriter(SW);
                    System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();

                    grid.DataSource = dt;
                    grid.DataBind();

                    using (SW)
                    {
                        using (HTMLWriter)
                        {
                            grid.RenderControl(HTMLWriter);
                        }
                    }

                    SW.Close();
                    HTMLWriter.Close();
                    MessageBox.Show("Your spreadsheet was created at: " + OPath, "Information", MessageBoxButtons.OK);
                }
                catch (Exception exx)
                {
                    MessageBox.Show("Could not create " + OPath.Trim() + ".  Create the directory first." + exx.Message, "Error", MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show("Your spreadsheet could not be created.  No columns found in datatable.", "Error Message", MessageBoxButtons.OK);
            }

        }
Example #33
0
        /// <summary>
        /// DataTable导出到Excel
        /// </summary>
        /// <param name="pData">DataTable</param>
        /// <param name="pFileName">导出文件名</param>
        /// <param name="pHeader">导出标题以|分割</param>
        public static void DataTableExcel(System.Data.DataTable pData, string pFileName, string pHeader)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter       strWriter  = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            if (pData != null)
            {
                string UserAgent = curContext.Request.ServerVariables["http_user_agent"].ToLower();
                if (UserAgent.IndexOf("firefox") == -1)//火狐浏览器
                {
                    pFileName = HttpUtility.UrlEncode(pFileName, System.Text.Encoding.UTF8);
                }
                curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + pFileName + ".xls");
                curContext.Response.ContentType = "application/vnd.ms-excel";
                strWriter  = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                dgExport = new System.Web.UI.WebControls.DataGrid();

                dgExport.DataSource = pData.DefaultView;

                dgExport.AllowPaging = false;
                dgExport.ShowHeader  = false;//去掉标题
                dgExport.Attributes.Add("style", "vnd.ms-excel.numberformat:@;font-size:15px;");
                for (int i = 0; i < dgExport.Items.Count; i++)
                {
                    dgExport.Items[i].Width = dgExport.Items[i].ToString().Length;
                }
                dgExport.ItemStyle.Height = 36;

                //spanRow(dgExport);
                dgExport.DataBind();

                string[] arrHeader = pHeader.Split('|');
                string   strHeader = "<table border=\"1\" style=\"font-weight:bold; font-size:15px; \"><tr>";
                foreach (string j in arrHeader)
                {
                    strHeader += "<td align='center' height='16px' >" + j.ToString() + "</td>";
                }
                strHeader += "</tr></table>";
                //int num = 1;
                //for (int i = 1; i < dgExport.Items.Count; i++)
                //{

                //    if (dgExport.Items[i].Cells[0].Text == "&nbsp;")//订单号等于空的情况下,此处是遍历行,获取行号i
                //    {
                //        num++;

                //        for (int j = 0; j < dgExport.Items[i].Cells.Count; j++)//寻找空行的列号,此处是遍历单元格
                //        {
                //            if (dgExport.Items[i].Cells[j].Text == "&nbsp;")
                //            {

                //                dgExport.Items[i].Cells[j].Visible = false;
                //                dgExport.Items[i - num + 1].Cells[j].RowSpan = num;
                //            }
                //        }

                //    }
                //    else { num = 1; }
                //}


                // 返回客户端
                dgExport.RenderControl(htmlWriter);


                string strMeta    = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=GB2312\"/>";
                string strWriter2 = strWriter.ToString().Replace("<tr", "<tr style=\"vertical-align:top\"");
                string OutExcel   = strMeta + strHeader + strWriter2;
                curContext.Response.Write(OutExcel);
                curContext.Response.End();
            }
        }
Example #34
0
        private void printHTML(DataTable dt, string TabName)
        {
            if (dt.Columns.Count > 0)
            {
                string OPath = "c:\\icalc\\koos.html";
                try
                {

                    StreamWriter SW = new StreamWriter(OPath);
                    //StringWriter SW = new StringWriter();
                    System.Web.UI.HtmlTextWriter HTMLWriter = new System.Web.UI.HtmlTextWriter(SW);
                    System.Web.UI.WebControls.DataGrid grid = new System.Web.UI.WebControls.DataGrid();

                    grid.DataSource = dt;
                    grid.DataBind();

                    using (SW)
                    {
                        using (HTMLWriter)
                        {
                            //FrontDecorator(HTMLWriter);

                            HTMLWriter.WriteLine("Phakisa - " + TabName + "  For : " + cboPayrollGroup.Text.Trim() + "  --- " + cboEarningsColumnName.Text.Trim());
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteLine("=====================================================================");
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteLine("MiningType: " + BusinessLanguage.MiningType + "  --------     BonusType: " + BusinessLanguage.BonusType);
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteLine("Period    : " + BusinessLanguage.Period + "  --------------     Section:  " + cboSection.Text.Trim());
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteLine("Date Printed    : " + DateTime.Today.ToLongDateString().ToString().Trim() + " - " + DateTime.Now.ToShortTimeString().ToString().Trim());
                            HTMLWriter.WriteBreak();
                            HTMLWriter.WriteBreak();

                            grid.RenderControl(HTMLWriter);
                            //RearDecorator(HTMLWriter);

                        }
                    }

                    SW.Close();
                    HTMLWriter.Close();

                    System.Diagnostics.Process P = new System.Diagnostics.Process();
                    P.StartInfo.WorkingDirectory = "C:\\Program Files\\Internet Explorer";
                    P.StartInfo.FileName = "IExplore.exe";
                    P.StartInfo.Arguments = "C:\\icalc\\koos.html";
                    P.Start();
                    P.WaitForExit();

                }
                catch (Exception exx)
                {
                    MessageBox.Show("Could not create " + OPath.Trim() + ".  Create the directory first." + exx.Message, "Error", MessageBoxButtons.OK);
                }
            }
            else
            {
                MessageBox.Show("Your spreadsheet could not be created.  No columns found in datatable.", "Error Message", MessageBoxButtons.OK);
            }
        }
Example #35
0
        public FileContentResult getFileResult(DataTable dt, HttpContextBase curContext)
        {
       

            System.Web.UI.WebControls.DataGrid dgExport = null;

            // 当前对话  


            // IO用于导出并返回excel文件  

            System.IO.StringWriter strWriter = null;

            System.Web.UI.HtmlTextWriter htmlWriter = null;

            string filename = DateTime.Now.Year + "_" + DateTime.Now.Month + "_" + DateTime.Now.Day + "_"

            + DateTime.Now.Hour + "_" + DateTime.Now.Minute;

            byte[] str = null;



            if (dt != null)
            {

                // 设置编码和附件格式

                curContext.Response.Charset = "GB2312";

                curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");

                curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文

                curContext.Response.ContentType = "application/vnd.ms-excel";

                //System.Text.Encoding.UTF8;

                // 导出excel文件  

                strWriter = new System.IO.StringWriter();

                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid  

                dgExport = new System.Web.UI.WebControls.DataGrid();

                dgExport.DataSource = dt.DefaultView;

                dgExport.AllowPaging = false;

                dgExport.DataBind();

                dgExport.RenderControl(htmlWriter);



                // 返回客户端  

                str = System.Text.Encoding.UTF8.GetBytes(strWriter.ToString());

            }

            return File(str, "attachment;filename=" + filename + ".xls");

        }
Example #36
0
        /// <summary>
        /// DataTable导出到Excel
        /// </summary>
        /// <param name="pData">DataTable</param>
        /// <param name="pFileName">导出文件名</param>
        /// <param name="pHeader">导出标题以|分割</param>
        public static void DataTableExcel(System.Data.DataTable pData, string pFileName, string pHeader)
        {
            System.Web.UI.WebControls.DataGrid dgExport = null;
            // 当前对话
            System.Web.HttpContext curContext = System.Web.HttpContext.Current;
            // IO用于导出并返回excel文件
            System.IO.StringWriter strWriter = null;
            System.Web.UI.HtmlTextWriter htmlWriter = null;
            if (pData != null)
            {
                string UserAgent = curContext.Request.ServerVariables["http_user_agent"].ToLower();
                if (UserAgent.IndexOf("firefox") == -1)//火狐浏览器
                {
                    pFileName = HttpUtility.UrlEncode(pFileName, System.Text.Encoding.UTF8);
                }
                curContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + pFileName + ".xls");
                curContext.Response.ContentType = "application/vnd.ms-excel";
                strWriter = new System.IO.StringWriter();
                htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);
                // 为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                dgExport = new System.Web.UI.WebControls.DataGrid();

                dgExport.DataSource = pData.DefaultView;

                dgExport.AllowPaging = false;
                dgExport.ShowHeader = false;//去掉标题
                dgExport.Attributes.Add("style", "vnd.ms-excel.numberformat:@;font-size:15px;");
                for(int i = 0; i < dgExport.Items.Count; i++) {
                    dgExport.Items[i].Width = dgExport.Items[i].ToString().Length;
                }
                dgExport.ItemStyle.Height = 36;

                //spanRow(dgExport);
                dgExport.DataBind();

                string[] arrHeader = pHeader.Split('|');
                string strHeader = "<table border=\"1\" style=\"font-weight:bold; font-size:15px; \"><tr>";
                foreach (string j in arrHeader)
                {
                    strHeader += "<td align='center' height='16px' >" + j.ToString() + "</td>";
                }
                strHeader += "</tr></table>";
                //int num = 1;
                //for (int i = 1; i < dgExport.Items.Count; i++)
                //{

                //    if (dgExport.Items[i].Cells[0].Text == "&nbsp;")//订单号等于空的情况下,此处是遍历行,获取行号i
                //    {
                //        num++;

                //        for (int j = 0; j < dgExport.Items[i].Cells.Count; j++)//寻找空行的列号,此处是遍历单元格
                //        {
                //            if (dgExport.Items[i].Cells[j].Text == "&nbsp;")
                //            {

                //                dgExport.Items[i].Cells[j].Visible = false;
                //                dgExport.Items[i - num + 1].Cells[j].RowSpan = num;
                //            }
                //        }

                //    }
                //    else { num = 1; }
                //}

                // 返回客户端
                dgExport.RenderControl(htmlWriter);

                string strMeta = "<meta http-equiv=\"content-type\" content=\"application/ms-excel; charset=GB2312\"/>";
                string strWriter2 = strWriter.ToString().Replace("<tr", "<tr style=\"vertical-align:top\"");
                string OutExcel = strMeta + strHeader +strWriter2;
                curContext.Response.Write(OutExcel);
                curContext.Response.End();
            }
        }
Example #37
0
        /// <summary>
        /// 服务器控件的翻译,从数据库中取值
        /// </summary>
        /// <param name="control">要翻译的控件</param>
        /// <param name="items">二维数组型参数,第二维第一个为字典键值,第二个为默认值</param>
        public void TranControlsDB(object control, string[][] items)
        {
            switch (control.GetType().ToString())       //
            {
            case "System.Web.UI.WebControls.GridView":
                System.Web.UI.WebControls.GridView gv = (System.Web.UI.WebControls.GridView)control;
                Translation.TranslationGridViewDB(gv, items);
                break;

            case "System.Web.UI.WebControls.DataGrid":
                System.Web.UI.WebControls.DataGrid dg = (System.Web.UI.WebControls.DataGrid)control;
                Translation.TranslationDataGridDB(dg, items);
                break;

            case "System.Web.UI.WebControls.RadioButtonList":
                System.Web.UI.WebControls.RadioButtonList rbl = (System.Web.UI.WebControls.RadioButtonList)control;
                Translation.TranslationRadioButtonListDB(rbl, items);
                break;

            case "System.Web.UI.WebControls.DropDownList":
                System.Web.UI.WebControls.DropDownList ddl = (System.Web.UI.WebControls.DropDownList)control;
                Translation.TranslationDropDownListDB(ddl, items);
                break;

            case "System.Web.UI.WebControls.CheckBoxList":
                System.Web.UI.WebControls.CheckBoxList chkl = (System.Web.UI.WebControls.CheckBoxList)control;
                Translation.TranslationCheckBoxListDB(chkl, items);
                break;

            case "System.Web.UI.WebControls.Button":
                System.Web.UI.WebControls.Button button = (System.Web.UI.WebControls.Button)control;
                Translation.TranslationButtonDB(button, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.LinkButton":
                System.Web.UI.WebControls.LinkButton lbtn = (System.Web.UI.WebControls.LinkButton)control;
                Translation.TranslationLinkButtonDB(lbtn, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.ImageButton":
                System.Web.UI.WebControls.ImageButton imgBtn = (System.Web.UI.WebControls.ImageButton)control;
                Translation.TranslationImageButtonDB(imgBtn, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.HyperLink":
                System.Web.UI.WebControls.HyperLink hl = (System.Web.UI.WebControls.HyperLink)control;
                Translation.TranslationHyperLinkDB(hl, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.Label":
                System.Web.UI.WebControls.Label label = (System.Web.UI.WebControls.Label)control;
                Translation.TranslationLabelDB(label, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.CheckBox":
                System.Web.UI.WebControls.CheckBox chk = (System.Web.UI.WebControls.CheckBox)control;
                Translation.TranslationCheckBoxDB(chk, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.RadioButton":
                System.Web.UI.WebControls.RadioButton rbtn = (System.Web.UI.WebControls.RadioButton)control;
                Translation.TranslationRadioButtonDB(rbtn, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.RequiredFieldValidator":
                System.Web.UI.WebControls.RequiredFieldValidator rfv = (System.Web.UI.WebControls.RequiredFieldValidator)control;
                Translation.TranslationRequiredFieldValidatorDB(rfv, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.RangeValidator":
                System.Web.UI.WebControls.RangeValidator rv = (System.Web.UI.WebControls.RangeValidator)control;
                Translation.TranslationRangeValidatorDB(rv, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.CompareValidator":
                System.Web.UI.WebControls.CompareValidator cv = (System.Web.UI.WebControls.CompareValidator)control;
                Translation.TranslationCompareValidatorDB(cv, items[0][0], items[0][1]);
                break;

            case "System.Web.UI.WebControls.RegularExpressionValidator":
                System.Web.UI.WebControls.RegularExpressionValidator rev = (System.Web.UI.WebControls.RegularExpressionValidator)control;
                Translation.TranslationRegularExpressionValidatorDB(rev, items[0][0], items[0][1]);
                break;
            }
        }
Example #38
0
        //根据路径和数据table插入excel文件中
        public void insertTableByPath(string ExcelPath, DataTable dtData)
        {
            try
            {
                System.Web.UI.WebControls.DataGrid dgExport = null;
                //   当前对话
                //System.Web.HttpContext curContext = System.Web.HttpContext.Current;
                //   IO用于导出并返回excel文件
                System.IO.StringWriter strWriter = null;
                System.Web.UI.HtmlTextWriter htmlWriter = null;

                if (dtData != null)
                {
                    if (dtData.Rows.Count < 65530)
                    {
                        //   设置编码和附件格式
                        //curContext.Response.ContentType = "application/vnd.ms-excel";
                        //curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
                        //curContext.Response.Charset = "GBK";
                        DateTime currentNow = DateTime.Now;

                        //   导出excel文件
                        strWriter = new System.IO.StringWriter();
                        htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter);

                        //   为了解决dgData中可能进行了分页的情况,需要重新定义一个无分页的DataGrid
                        dgExport = new System.Web.UI.WebControls.DataGrid();
                        dgExport.DataSource = dtData.DefaultView;
                        dgExport.AllowPaging = false;
                        dgExport.DataBind();

                        //string fileName = Name + currentNow.ToString("yyyy-MM-dd") + ".xls";
                        //string filePath = curContext.Server.MapPath(".") + fileName;
                        System.IO.StreamWriter sw = System.IO.File.CreateText(ExcelPath);

                        dgExport.RenderControl(htmlWriter);
                        sw.Write(strWriter.ToString());

                        sw.Close();
                        //   返回客户端
                        //this.DownFile(curContext.Response, fileName, ExcelPath);

                        //curContext.Response.End();
                    }

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #39
0
 /*
  * Page Events
 */
 /// <summary>
 /// 
 /// </summary>
 protected void Page_Load( System.Object sender, System.EventArgs args )
 {
     if ( this.InboxDataGrid == null ) {
         this.InboxDataGrid=(System.Web.UI.WebControls.DataGrid )this.SharpUI.FindControl("InboxDataGrid");
         this.inboxWindowSearchHolder=(System.Web.UI.WebControls.PlaceHolder)this.SharpUI.FindControl("inboxWindowSearchHolder");
         System.String mode = Page.Request.QueryString["mode"];
             if ( mode!=null && mode.Equals("trash") )
                 this.InboxDataGrid.Columns[5].Visible=false;
     }
     this.SharpUI.nextPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(nextPageButton_Click);
     this.SharpUI.prevPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(prevPageButton_Click);
     this.SharpUI.refreshPageImageButton.Click += new System.Web.UI.ImageClickEventHandler(refreshPageButton_Click);
 }