1 点击导出事件
protected void Button1_Click(object sender, EventArgs e)
{
Download();
}
//导出方法
public void Download()
{
Random rd = new Random();
string fileName = DateTime.Now.ToString("yyyyMMddhhmm") + rd.Next() + ".doc";
//存储路径
string path = "c:\\"+fileName;
//创建字符输出流
StreamWriter sw = new StreamWriter(path, true, System.Text.UnicodeEncoding.UTF8);
Write(sw);
sw.Close();
Response.Clear();
Response.Buffer = true;
this.EnableViewState = false;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.ContentType = "application/octet-stream";
Response.WriteFile(path);
Response.Flush();
Response.Close();
Response.End();
}
private void Write(StreamWriter sw)
{
try
{
DataSet ds = null;//业务逻辑查询数据
if (m_ds != null && m_ds.Tables.Count > 1)
{
WriteFileByDt(sw,m_ds.Tables[1]);
}
}
catch (Exception ex)
{
throw ex;
}
}
private void WriteFileByDt(StreamWriter sw,DataTable dt)
{
sw.Write("<table cellpadding='0' cellspacing='0' style='border-top: 1px solid black'>");
string flgDepartmentName = "";
string flgPersonName = "";
int flgDepartmentNameCount = 0;
int flgPersonNameCount = 0;
foreach (DataRow item in dt.Rows)
{
string strHtml = @"
<td style='border-left: 1px solid black;border-bottom: 1px solid black;text-align: left; font-size: 18px; width: 20px'>
" + item["NO"] + @"
</td>
<td style='border-left: 1px solid black;border-bottom: 1px solid black; border-right: 1px solid black;width: 50px; text-align: center; font-size: 18px;' >
" + item["Weight"] + @"
</td>
</tr>
";
sw.Write(strHtml);
}
sw.Write("</table>");
}