发布网友 发布时间:2022-04-24 16:05
共1个回答
热心网友 时间:2023-10-21 10:32
沾过去直接就可以用
//参数dt是数据表,fileName是生成Excel的名字
private void CreateExcel(DataTable dt, 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();
}
//生成xml
protected void Button3_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SqlConnection conn = new SqlConnection("database=库;server=.;uid=sa;pwd=;");
string sql1 = "select * from 表";
SqlDataAdapter da = new SqlDataAdapter(sql1, conn);
da.Fill(ds);
DataTable dt = ds.Tables[0].Copy();
CreateExcel(dt, "table");
}