欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net excel导出功能

程序员文章站 2022-07-07 09:08:23
以下是我在项目开发中所做的关于Excel导出功能,不足之处还望大家指正,相互学习指正 ......

以下是我在项目开发中所做的关于Excel导出功能,不足之处还望大家指正,相互学习

protected void btn_Export_Click(object sender, EventArgs e)
    {
        string FileID = "";
        if (Request.QueryString["fujian"] != null && Request.QueryString["fujian"].ToString() != "")
        {
            FileID = Request.QueryString["fujian"].ToString();
        }
        string title = GetFileTile(FileID);//文件标题
        Workbook workbook = new Workbook(); //工作簿 
        Worksheet sheet = workbook.Worksheets[0]; //工作表
        Cells cells = sheet.Cells; //单元格         
        //列宽
        cells.SetColumnWidth(0, 20.00);
        cells.SetColumnWidth(1, 30.00);
        cells.SetColumnWidth(2, 30.00);
        cells.Merge(0, 0, 1, 3);//合并单元格

        cells[0, 0].PutValue(title + "/文件已学人员名单");
        cells[0, 1].PutValue("");
        cells[0, 2].PutValue("");
        cells[1, 0].PutValue("序号");
        cells[1, 1].PutValue("姓名");
        cells[1, 2].PutValue("时间");
        string sql = "order by StudyTime";
        ds = PublishBLL.GetCommentCount(FileID, sql);
        if (ds.Tables[0].Rows.Count > 0)
        {

            for (int i = 1; i < ds.Tables[0].Rows.Count + 1; i++)
            {
                //Aspose.Cells.Style styleTitle = workbook.Styles[workbook.Styles.Add()];//新增样式 
                //styleTitle.HorizontalAlignment = TextAlignmentType.Center;//文字居中 
                //styleTitle.Font.Name = "宋体";//文字字体 
                //styleTitle.Font.Size = 18;//文字大小 
                //styleTitle.Font.IsBold = true;//粗体 
                cells[i + 1, 0].PutValue("" + i.ToString().PadLeft(3, '0') + "");
                cells[i + 1, 1].PutValue("" + ds.Tables[0].Rows[i - 1]["StudyName"].ToString() + "");
                cells[i + 1, 2].PutValue("" + ds.Tables[0].Rows[i - 1]["StudyTime"].ToString() + "");
            }
        }
        string filename = "统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
        string path = ConfigurationManager.AppSettings["StudyFile"] + @"\" + filename + "";
        workbook.Save(path);//保存到硬盘 

        #region 下载
        System.IO.MemoryStream ms1 = workbook.SaveToStream();//生成数据流 
        byte[] bt1 = ms1.ToArray();
        string fileName = "统计" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";//客户端保存的文件名 
        //以字符流的形式下载文件
        Response.ContentType = "application/vnd.ms-excel"; //通知浏览器下载文件而不是打开

        Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
        Response.BinaryWrite(bt1);
        Response.Flush();
        Response.End();
        #endregion
    }