c#怎么把查询出来的数据写到excel中
1个回答
展开全部
将sql数据导出excel表格
protected void Button1_Click(object sender, EventArgs e)
{
string strsql = "select * from TreeViewTemp where parentID=0";
DataTable dt = db.GetDataTable(strsql);
StringWriter sw = new StringWriter();
//StreamWriter sw = new StreamWriter("d:\\test.xls",false,System.Text.Encoding.Default); 本地保存
ExportExcel(dt, sw);
Response.AddHeader("Content-Disposition", "attachment; filename=PDSDATA.xls");//远程下载
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
public void ExportExcel(DataTable dt, StringWriter w)
{
try
{
for (int i = 0; i < dt.Columns.Count; i++)
{
w.Write(dt.Columns[i]);
w.Write('\t');
}
w.Write("\r\n");
object[] values = new object[dt.Columns.Count];
foreach (DataRow dr in dt.Rows)
{
values = dr.ItemArray;
for (int i = 0; i < dt.Columns.Count; i++)
{
w.Write(values[i]);
w.Write('\t'); //修改语句
}
w.Write("\r\n"); //修改语句
}
w.Flush();
w.Close();
}
catch
{
w.Close();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string strsql = "select * from TreeViewTemp where parentID=0";
DataTable dt = db.GetDataTable(strsql);
StringWriter sw = new StringWriter();
//StreamWriter sw = new StreamWriter("d:\\test.xls",false,System.Text.Encoding.Default); 本地保存
ExportExcel(dt, sw);
Response.AddHeader("Content-Disposition", "attachment; filename=PDSDATA.xls");//远程下载
Response.ContentType = "application/ms-excel";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.Write(sw);
Response.End();
}
public void ExportExcel(DataTable dt, StringWriter w)
{
try
{
for (int i = 0; i < dt.Columns.Count; i++)
{
w.Write(dt.Columns[i]);
w.Write('\t');
}
w.Write("\r\n");
object[] values = new object[dt.Columns.Count];
foreach (DataRow dr in dt.Rows)
{
values = dr.ItemArray;
for (int i = 0; i < dt.Columns.Count; i++)
{
w.Write(values[i]);
w.Write('\t'); //修改语句
}
w.Write("\r\n"); //修改语句
}
w.Flush();
w.Close();
}
catch
{
w.Close();
}
}
参考资料: http://blog.csdn.net/chenguang79/archive/2010/03/16/5386910.aspx
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询