将dataset中的数据保存到excel中思路:
1、获取数据到asp.net,
2、根据页面布局的数据设计excel表头,以及填充的数据
3、点击保存,调用createExcel方法,生成excel并且在固定sheet保存数据。
页面加载连接数据源,获取数据到dataset中:
protected void Page_Load(object sender, EventArgs e)
{
//建立连接
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=.;Initial Catalog=Northwind;Integrated Security=True";
//创建一个SqlCommand对你
SqlCommand cmd = new SqlCommand("select * from Customers", con);
con.Open();
SqlDataAdapter ad = new SqlDataAdapter(cmd);
DataSet set = new DataSet();
ad.Fill(set);
string fileName = "myexecl";
CreateExcel(set, fileName);
con.Close();
}
创建excel并保存数据:
public void CreateExcel(DataSet ds, string FileName)
{
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
string colHeaders = "", ls_item = "";
//定义表对象与行对象,同时用DataSet对其值进行初始化
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select();//可以类似dt.Select("id>10")之形式达到数据筛选目的
int i = 0;
int cl = dt.Columns.Count;
//取得数据表各列标题,各标题之间以t分割,最后一个列标题后加回车符
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
colHeaders += dt.Columns[i].Caption.ToString() + "/n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "/t";
}
}
resp.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
foreach (DataRow row in myRow)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (i = 0; i < cl; i++)
{
if (i == (cl - 1))//最后一列,加n
{
ls_item += row[i].ToString() + "/n";
}
else
{
ls_item += row[i].ToString() + "/t";
}
}
resp.Write(ls_item);
ls_item = "";
}
resp.End();
}
做过
解决方法:
定义一个新的DataTable,把Dataset中的数据组装到DataTable的对象中去
循环新的DataTable,把每行中的每一列数据填充进Excel中
导出Excel,当你打开Excel里面就有数据
希望对你有用!
protected void ExportToExcel(object sender, EventArgs e)
{
ExportToExcel(dsResult.Tables[0], "test");
}
protected void ExportToExcel(DataTable dt, string FileName)
{
if (dt.Rows.Count > 0)
{
string filename = FileName + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
DataGrid dgGrid = new DataGrid();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.RenderControl(hw);
Response.ContentType = "application/vnd.ms-excel";
Response.AppendHeader("Content-Disposition",
"attachment; filename=" + filename + "");
this.EnableViewState = false;
Response.Write(tw.ToString());
Response.End();
}
}