一个关于Excel的处理类(部分参考网络上)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.OleDb;
using System.IO;
namespace Northwind.Web.common
{
    
public class ExcelHelper
    {
        
//将控件转换为Excel表
        public static void ExportToExcel(Control c, string fileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Buffer 
= true;
            HttpContext.Current.Response.Charset 
= "utf-7";//不行就改为utf-7
            HttpContext.Current.Response.AppendHeader("Content-Disposition"string.Format("attachment;filename={0}.xls", fileName));
            HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("utf-7");//设置输出流为简体中文
            HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
            
//this.EnableViewState = false;
            System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN"true);
            System.IO.StringWriter oStringWriter 
= new System.IO.StringWriter(myCItrad);
            System.Web.UI.HtmlTextWriter oHtmlTextWriter 
= new System.Web.UI.HtmlTextWriter(oStringWriter);
            c.RenderControl(oHtmlTextWriter);
            HttpContext.Current.Response.Write(oStringWriter.ToString());
            HttpContext.Current.Response.End();
        }
        
//判断有没有相同的列,暂时只支持一列
        public static bool CanImport(string filename, string sheetName, string column)
        {
            
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
            
if (column != "")
            {
                
using (OleDbConnection conn = new OleDbConnection(strConn))
                {
                    OleDbDataAdapter oada 
= new OleDbDataAdapter(string.Format("select {0} from [{1}$] group by {0} having count({0})=2", column, sheetName), strConn);
                    DataTable dt 
= new DataTable();
                    oada.Fill(dt);
                    conn.Close();
                    
if (dt.Rows.Count > 0) { return false; }
                }
            }
            
return true;
        }
        
//将excel数据转换为DataTable
        public static DataTable ImportToTable(string filename, string sheetName)
        {
            DataTable dt 
= new DataTable();
            
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filename + ";Extended Properties=Excel 8.0;";
            
using (OleDbConnection conn = new OleDbConnection(strConn))
            {
                OleDbDataAdapter oada 
= new OleDbDataAdapter(string.Format("select * from [{0}$]", sheetName), strConn);
                oada.Fill(dt);
            }
            
return dt;
        }
        
//从gridview导出Excel
        public static void ExportFromGridview(string fileName, GridView gv)
        {
             HttpContext.Current.Response.Clear();
             HttpContext.Current.Response.Charset 
= "utf-7";
             HttpContext.Current.Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("utf-7");//设置输出流为简体中文
        HttpContext.Current.Response.AddHeader(
            
"content-disposition"string.Format("attachment; filename={0}.xls", fileName));
        HttpContext.Current.Response.ContentType 
= "application/ms-excel";

        
using (StringWriter sw = new StringWriter())
        {
            
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
            {
                
//  Create a form to contain the grid
                Table table = new Table();

                
//  add the header row to the table
                if (gv.HeaderRow != null)
                {
                    PrepareControlForExport(gv.HeaderRow);
                    table.Rows.Add(gv.HeaderRow);
                }

                
//  add each of the data rows to the table
                foreach (GridViewRow row in gv.Rows)
                {
                    PrepareControlForExport(row);
                    table.Rows.Add(row);
                }

                
//  add the footer row to the table
                if (gv.FooterRow != null)
                {
                    PrepareControlForExport(gv.FooterRow);
                    table.Rows.Add(gv.FooterRow);
                }

                
//  render the table into the htmlwriter
                table.RenderControl(htw);

                
//  render the htmlwriter into the response
                HttpContext.Current.Response.Write(sw.ToString());
                HttpContext.Current.Response.End();
            }
        }
        }
        
//处理gridview里面的特殊控件,如下拉列表或文本框等
        private static void PrepareControlForExport(Control control)
        {
            
for (int i = 0; i < control.Controls.Count; i++)
            {
                Control current 
= control.Controls[i];
                
if (current is LinkButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, 
new LiteralControl((current as LinkButton).Text));
                }
                
else if (current is ImageButton)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, 
new LiteralControl((current as ImageButton).AlternateText));
                }
                
else if (current is HyperLink)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, 
new LiteralControl((current as HyperLink).Text));
                }
                
else if (current is DropDownList)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, 
new LiteralControl((current as DropDownList).SelectedItem.Text));
                }
                
else if (current is CheckBox)
                {
                    control.Controls.Remove(current);
                    control.Controls.AddAt(i, 
new LiteralControl((current as CheckBox).Checked ? "True" : "False"));
                }

                
if (current.HasControls())
                {
                    PrepareControlForExport(current);
                }
            }
        }
    }
}
posted @ 2008-03-17 12:46  Awen  阅读(376)  评论(0编辑  收藏  举报