//导出数据到Excel
protected void btn_ToExcel_Click(object sender, EventArgs e)
{
DataTable dt = bll_orders.GetList(" 1=1 " + where).Tables[0];
CreateExcel(this.Response, dt, "aaa.xls");
}
#region
/// <summary>
/// datable 直接转流输出
/// </summary>
/// <param name="response"></param>
/// <param name="dt"></param>
/// <param name="fileName"></param>
public void CreateExcel(HttpResponse response, DataTable dt, string fileName)
{
response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
response.ContentType = "application/ms-excel";
response.Charset = "UTF-8";
response.ContentEncoding = System.Text.Encoding.Default;
try
{
//response.AddFileDependency
string colHeaders = @"", rowContent = @"";
//列与行对象
int colCount = dt.Columns.Count;
int rowsCount = dt.Rows.Count;
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
for (int i = 0; i < colCount; i++)
{
if (i == (colCount - 1))//最后一列,加\n
{
colHeaders += dt.Columns[i].Caption.ToString() + "\n";
}
else
{
colHeaders += dt.Columns[i].Caption.ToString() + "\t";
}
}
response.Write(colHeaders);
//向HTTP输出流中写入取得的数据信息
//逐行处理数据
for (int j = 0; j < rowsCount; j++)
{
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
for (int i = 0; i < colCount; i++)
{
if (i == (colCount - 1))//最后一列,加\n
{
rowContent += dt.Rows[j][i].ToString().Replace("\r", "").Replace("\n", "") + "\n";
}
else
{
rowContent += dt.Rows[j][i].ToString().Replace("\r", "").Replace("\n", "") + "\t";
}
}
response.Write(rowContent);
rowContent = @"";
}
}
catch
{ }
response.Flush();
response.End();
}
#endregion