[置顶] ASP.NET 中导出表格

 下面给出一个简单的导出Excel的方法!具体的可以自己改,


   public void CreateExcelTable()


{
            //获取实例,当然这些都是我分装好的类  
            BLL.Attendence attendence = new BLL.Attendence();  
            string strWhere = " AttendenceName ='" + attendenceName + "'and ManagerUserName='" + MyUserName + "'and ProjectId='" + mycurrentProjectId + "'";
           //获取数据,存放在内存当中
            DataSet ds = attendence.GetList(strWhere);
            //这个count为测试的时候,看table中究竟有多少条数据,我比较喜欢这样,用事实说话嘛!
            int count = ds.Tables[0].Rows.Count;
            if(count==0)
            {
                //这也是封装好的一个方法,,其实就是alert('当前没有数据,请选择数据项后在导出!');
                PageUtil.ShowMsgBox(this,"当前没有数据,请选择数据项后在导出!");
                return;
            }
            //创建Excel对象
            Excel.Application excel = new Excel.Application();
            int rowindex = 1;
            int colindex = 0;
            //添加Workbooks
            excel.Application.Workbooks.Add(true);
            System.Data.DataTable table = ds.Tables[0];
            excel.Cells[1, 1] = "序号";
            excel.Cells[1, 2] = "用户名";
            excel.Cells[1, 3] = "姓名";
            excel.Cells[1, 4] = "考勤状态";

            int count2 = table.Rows;

foreach (DataColumn col in table.Columns)

{
                //添加列明
                colindex++;
                excel.Cells[1, colindex] = col.ColumnName;
            }
            foreach (DataRow row in table.Rows)
            {
                //添加数据
                rowindex++;
                colindex = 0;
                foreach (DataColumn col in table.Columns)
                {
                    colindex++;
                    excel.Cells[rowindex, colindex] = row[col.ColumnName].ToString();

                }
            }
            excel.Visible=false;
            excel.DisplayAlerts=false;
           //保存表格
            excel.Save(MapPath(("ExcelDB/ExcelTable.xls")));
            excel.Application.Workbooks.Close();
            excel.Application.Quit();
            //释放对象
            System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);
            GC.Collect();  //收集内存
        }

posted @ 2012-12-09 20:30  shouqiang Wei  阅读(137)  评论(0编辑  收藏  举报