datagrid下载Excel类

        /// <summary>
        /// Outputs the rendered HTML content of given DataGrid to the client with Response.Write.
        /// Every cells are marked as text format.
        /// </summary>
        /// <param name="dataGrid">The DataGrid to output.</param>
        /// <param name="filename">The filename to output.</param>
        public static void DownloadHtmlExcelFile(DataGrid dataGrid, string filename) { DownloadHtmlExcelFile(dataGrid, filename, null); }
        /// <summary>
        /// Outputs the rendered HTML content of given DataGrid to the client with Response.Write.
        /// </summary>
        /// <param name="dataGrid">The DataGrid to output.</param>
        /// <param name="filename">The filename to output.</param>
        /// <param name="nonTextFormatColumns">The columns that should not be marked as text format. When the given value is -1, no column will be marked as text format.</param>
        public static void DownloadHtmlExcelFile(DataGrid dataGrid, string filename, params int[] nonTextFormatColumns)
        {
            HttpResponse httpResponse = HttpContext.Current.Response;
            // Sets content type to Excel.
            httpResponse.Clear();
            //httpResponse.ContentType = "application/vnd.ms-excel"
            httpResponse.ContentType = "application/octet-stream";
            httpResponse.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlPathEncode(filename));

            // Disables the view state.
            // Me.EnableViewState = False

            // Clears controls within DataGrid.
            ClearControls(dataGrid);

            // Sets columns to text format
            bool textFormat = nonTextFormatColumns == null || nonTextFormatColumns.Length == 0 || Array.IndexOf(nonTextFormatColumns, -1) != -1;
            for (int row = 0; row <= dataGrid.Items.Count - 1; row++)
                for (int col = 0; col <= dataGrid.Items[row].Cells.Count - 1; col++)
                    if (textFormat || Array.IndexOf(nonTextFormatColumns, col) == -1)
                        dataGrid.Items[row].Cells[col].Attributes.Add("class", "text");

            // Outputs BOM for unicode files and enables Excel correctly parsing file content
            using (StreamWriter sw = new StreamWriter(httpResponse.OutputStream, Encoding.UTF8))
            {
                // Outputs CSS
                sw.Write("<style>.text {mso-number-format:\"\\@\";}</style>");
                HtmlTextWriter htw = new HtmlTextWriter(sw);
                dataGrid.RenderControl(htw);
                sw.Flush();
            }

            // Terminates
            httpResponse.End();
        }

 

posted @ 2014-06-19 15:22  清风君  阅读(336)  评论(0)    收藏  举报