导出表格数据到word文档

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>");
       }




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值