日期:2014-05-19  浏览次数:20682 次

DataGridli里的数据怎么导入到Excel?
求解

------解决方案--------------------
倒入Excel
下面我举个实际的例子,以下的代码测试已通过

//在.cs 里

using System.Configuration; //须在Config中指定连接的数据库
using common_function; //声明 namespace
using System.Data .SqlClient;

private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
BindGrid();
}
}

private void BindGrid()

{

string sql_str= "select * from repair_now where repair_sort_id= ' ' ";
MyDataGrid.DataSource =Public_Class.Get_Select_Table(sql_str); //调用公共类返回datatable
MyDataGrid.DataBind();

//导入Excel表时,先求数量
string sql_count= "select count(*) from repair_now ";
string temp=Public_Class.Judge_Repeat(sql_count);
ViewState[ "count "]=temp;

}

private string Table_Name()
{
string tn= "To_Excel ";
return tn;
}
private void ToExcel(System.Web.UI.Control ctl,string Table_Name)
{
HttpContext.Current.Response.AppendHeader( "Content- Disposition ", "attachment;filename= "+ " "+Table_Name+ ".xls ");
HttpContext.Current.Response.Charset = "gb-2312 ";
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default ;
HttpContext.Current.Response.ContentType = "application/ms-excel/ms- word ";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
ctl.Page.EnableViewState =true;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);

ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
}

private void Button_Excel_Click(object sender, System.Web.UI.ImageClickEventArgs e)//倒入Excel按钮事件
{
MyDataGrid.PageSize=Convert.ToInt32(ViewState[ "count "].ToString());
BindGrid();
MyDataGrid.PagerStyle.Visible =false;
ToExcel(MyDataGrid,Table_Name());
}

以下是被调用公共类 Public_Class.cs

using System.Data .SqlClient ;
using System.Configuration;

public class Public_Class
{

private static string ConnectString = ConfigurationSettings.AppSettings[ "ConnectString "];

public static DataTable Get_Select_Table(string sql_str) //执行查询,返回DataTable
{
SqlConnection myConnection;
myConnection = new SqlConnection( ConnectString);
SqlDataAdapter myCommand = new SqlDataAdapter(sql_str, myConnection);
DataSet ds = new DataSet();
myCommand.Fill(ds, "t1 ");
return ds.Tables [ "t1 "];

}

public static string Judge_Repeat(string sql_str)
{

SqlConnection myConnection = new SqlConnection(ConnectString);
SqlCommand myCommand = new SqlCommand (sql_str,myConnection);
myCommand.Connection.Open();
SqlDataReader Dr;
Dr=myCommand.ExecuteReader();
try
{
Dr.Read();
return Dr[0].ToString ();

}
catch(Exception err)
{
return " ";
}
finally
{
Dr.Close();
myCommand.Connection.Close();
}

}

}

------解决方案--------------------
string conn = @ "provider=Microsoft.Jet.OLEDB.4.0;data source=C:\Documents and Settings\hf.mao\My Documents\bveera.mdb ";
OleDbConnection cn = new OleDbConnection(conn);
OleDbCommand cmd;
cn.Open();

string sql;//= "select count(*) from news ";