Excel,GridView导入导出

  //Excel转换为 DataSet 
public static DataSet ExcelToDataSet(string path,string Sheet)
    
{
        DataSet ds 
= new DataSet();
        
//string MyConnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + @System.Web.HttpContext.Current.Server.MapPath(".") + @"\" + ExcelName + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
        string MyConnectionstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
        
string MySQL = "SELECT * FROM [" + Sheet + "$]";
        OleDbConnection myconn 
= new OleDbConnection(MyConnectionstring);
        myconn.Open();
        OleDbDataAdapter adp 
= new OleDbDataAdapter(MySQL, myconn);
        adp.Fill(ds, 
"ExcelTemp");
        myconn.Close();
        
//读取后删除文件
        if (System.IO.File.Exists(path))
        
{
            System.IO.File.Delete(path);
        }

        
return ds;
    }

  //其中 path是Excel文件的路径,Sheet是Excel文件的 工作表名
  //下面是 导出Excel:
  //但首先要重写父类的一个方法
  //代码如下:
 protected void gvwUsers_RowDataBound(object sender, GridViewRowEventArgs e)
    
{
        
if (e.Row.RowType == DataControlRowType.DataRow)
            e.Row.Cells[
3].Attributes.Add("style""vnd.ms-excel.numberformat:@");
    }
//然后就是 导出的方法 其中 FileType为 Excel的文件类型:"application/ms-excel"    
//Export("application/ms-excel", "EmpInfos.xls");
 1 ======从GridView导出Excel模板========
posted @ 2008-03-30 20:33  Seven Shi  阅读(1795)  评论(0编辑  收藏  举报