110,499
社区成员
发帖
与我相关
我的任务
分享
static void Main(string[] args)
{
//连接数据库字符串
SqlConnection myConnection = new SqlConnection("Integrated Security=SSPI;Initial Catalog=Northwind;server=(local)");
DataTable myDataTable = new DataTable();
//sql语句 建立数据命令对象
SqlCommand myCommand = new SqlCommand("select top 10 * from Orders", myConnection);
myConnection.Open();
SqlDataReader dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
myDataTable.Load(dr);
Export(myDataTable,"SqlQuerySaveToTxt");
//关闭连接
myConnection.Close();
dr.Close();
dr.Dispose();
myCommand.Dispose();
}
//导出到txt文本
private void Export(DataTable tb, string fileName)
{
HttpContext.Current.Response.Clear();
string FileName = fileName + ".txt";
HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = Encoding.UTF7;
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
HttpContext.Current.Response.ContentType = "application/ms-text";
System.IO.StringWriter sw = new System.IO.StringWriter();
for (int i = 0; i < tb.Rows.Count; i++)
{
for (int j = 0; j < tb.Columns.Count; j++)
{
sw.WriteLine(tb.Rows[i][j].ToString().Trim() + "\t");
}
sw.WriteLine("\r\n");
}
HttpContext.Current.Response.Write(sw.ToString());
sw.Close();
HttpContext.Current.Response.End();
}