C# 关于导出EXCEL功能

/// <summary>
        /// 导出Excel数据
        /// </summary>
        /// <param name="search"></param>
        /// <returns></returns>
        public ActionResult ExportExcel(SearchEntity search)//查询条件
        {

List<Models.PerLoan.PersonalLoanExcel> perLoanList = new List<Models.PerLoan.PersonalLoanExcel>();

  形成的excel对象[Description("贷款期限")] public int? LoanLimit { get; set; }  形成表标题

perLoanList = PersonalLoanDAL.GetProcessLoanExcelNew(city, search, status, CurrentUser.RoleId, CurrentUser.UserId, CurrentUser);//查询到的列表

string fileName = DateTime.Now.ToString("yyyyMMddHHmm") + "_个人业务查询";
            DAL.Common.ExportExcel<Models.PerLoan.PersonalLoanExcel> exportExcel = new DAL.Common.ExportExcel<Models.PerLoan.PersonalLoanExcel>(fileName, perLoanList);
            exportExcel.ResponseExcel(1);
            return View();
        }

public class ExportExcel<T> where T:class
    {
        public ExportExcel(string fileName, List<T> list)
        {
            _fileName = fileName;
            _listT = list;
        }

private HSSFWorkbook workbook;

private string _fileName;
        public string FileName
        {
            get { return _fileName; }
            set { _fileName = value; }
        }

private List<T> _listT;
        public List<T> ListT
        {
            get { return _listT; }
            set { _listT = value; }
        }

/// <summary>
        /// 向客户端输出Excel
        /// </summary>
        /// <param name="ordertype">1 个人  2 经纪人</param>
        public void ResponseExcel(int ordertype)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.ContentType = "application/vnd.ms-excel";
            response.HeaderEncoding = System.Text.Encoding.GetEncoding("gb2312");
            response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", _fileName + ".xls"));
            response.Clear();

InitialiseWorkBook();
            CreateExcelData(ordertype);

using (MemoryStream file = new MemoryStream())
            {
                workbook.Write(file);
                file.WriteTo(response.OutputStream);
            }
            response.End();
        }

private void InitialiseWorkBook()
        {
            workbook = new HSSFWorkbook();
            DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
            dsi.Company = "SouFun";
            workbook.DocumentSummaryInformation = dsi;

SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
            si.Subject = "Export data";
            workbook.SummaryInformation = si;
        }

/// <summary>
        /// 根据List中的内容生成excel数据
        /// </summary>
        /// <param name="ordertype">订单类型  1个人  2经纪人</param>
        private void CreateExcelData(int ordertype)
        {
            ISheet sheet = workbook.CreateSheet(_fileName);

IRow rowHead = sheet.CreateRow(0);

Type t = typeof(T);
            int column=0;
            int headNum = 0;
            foreach (PropertyInfo pi in t.GetProperties())
            {
                string headValue = string.Empty;
                object[] des = pi.GetCustomAttributes(typeof(DescriptionAttribute), true);
                if (des.Length > 0)
                {
                    DescriptionAttribute da = (DescriptionAttribute)des[0];
                    headValue = da.Description;
                    rowHead.CreateCell(headNum, CellType.STRING).SetCellValue(headValue);
                    headNum++;
                }
                
                column++;
            }

for (int r = 0; r < _listT.Count; r++)
            {
                IRow row = sheet.CreateRow(r + 1);

int c = 0;
                int c1 = 0;
                decimal money=0;
                decimal interviermoney = 0;
                decimal pidaimoney = 0;
                decimal fangkuanmoney = 0;
                decimal bankreturncharge = 0;
                decimal commissionrate = 0;
                int gender = -1;

foreach (PropertyInfo pi in t.GetProperties())
                {
                    string v = string.Empty;
                    object o = pi.GetValue(_listT[r], null);
                    object[] des = pi.GetCustomAttributes(typeof(DescriptionAttribute), true);
                    if (des.Length > 0)
                    {
                        if (o != null)
                        {
                            if (pi.Name.ToLower() == "status" || pi.Name.ToLower() == "prevstatus")
                            {
                                v = DAL.Common.Order.GetCurrentStatus(int.Parse(o.ToString()));
                            }
                            else if (pi.Name.ToLower() == "gender") //case when Gender = 0 then ‘女‘ when Gender = 1 then ‘男‘ else ‘‘ end as
                            {
                                gender = Convert.ToInt32(o);
                                if (o == null)
                                {
                                    v = "";
                                }
                                else
                                {
                                    if (gender==1)
                                    {
                                        v = "男";  
                                    }
                                    else if (gender == 0)
                                    {
                                        v = "女";
                                    }
                                }
                            }
                            else if (pi.Name.ToLower() == "datafrom")
                            {
                                v = DAL.Common.Order.GetOrderFrom(int.Parse(o.ToString()), ordertype);
                            }
                            else if (pi.Name.ToLower() == "interviewmoney")
                            {
                                interviermoney = Convert.ToDecimal(o);
                                v = interviermoney.ToString() + "万元";
                            }
                            else if(pi.Name.ToLower()=="allowappmoney")
                            {
                                pidaimoney = Convert.ToDecimal(o);
                                v = pidaimoney.ToString() + "万元";
                            }
                            else if (pi.Name.ToLower() == "fangkuanmoney")
                            {
                                fangkuanmoney = Convert.ToDecimal(o);
                                v = fangkuanmoney.ToString();
                            }
                            else if (pi.Name.ToLower() == "bankreturncharge")
                            {
                                bankreturncharge = Convert.ToDecimal(o);
                                v = bankreturncharge.ToString() + "%";
                            }
                            else if (pi.Name.ToLower() == "commissionrate")
                            {
                                commissionrate = Convert.ToDecimal(o);
                                v = commissionrate.ToString() + "%";
                            }
                            //else if (pi.Name.ToLower() == "nicknamefrom")
                            //{
                            //    if (o.ToString() == "0") { v = "金融"; }
                            //    else if (o.ToString() == "1") { v = "二手房"; }
                            //}
                            else if (pi.Name.ToLower() == "bankreturnmoney")
                            {
                                if (Convert.ToDecimal(o) <= 0M)
                                {
                                    if (interviermoney > 0) { money = interviermoney; }
                                    else if (pidaimoney > 0) { money = pidaimoney; }
                                    else if (fangkuanmoney > 0) { money = fangkuanmoney; }
                                    if (money > 0 && bankreturncharge > 0)
                                    {
                                        v = (money * 10000 * bankreturncharge / 100).ToString() + "元";
                                    }
                                }
                                else
                                {
                                    v = o.ToString() + "元";
                                }
                            }
                            else if (pi.Name.ToLower() == "commissionmoney")
                            {
                                if (interviermoney > 0) { money = interviermoney; }
                                else if (pidaimoney > 0) { money = pidaimoney; }
                                else if (fangkuanmoney > 0) { money = fangkuanmoney; }
                                if (money > 0 && commissionrate > 0)
                                {
                                    v = (money * commissionrate / 100).ToString() + "万元";
                                }
                            }
                            else if (pi.PropertyType.IsGenericType && pi.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
                            {
                                Type ptype = pi.PropertyType.GetGenericArguments()[0];
                                if (ptype == typeof(System.DateTime))
                                {
                                    v = Convert.ToDateTime(o).ToString("yyyy-MM-dd");
                                }
                                else
                                {
                                    v = o.ToString();
                                }
                            }
                            else
                            {
                                v = o.ToString();
                            }
                            
                        }
                        row.CreateCell(c1, CellType.STRING).SetCellValue(v);
                        c1++;
                    }
                    c++;
                }

}
        }
    }

时间: 2024-10-21 01:23:24

C# 关于导出EXCEL功能的相关文章

扩展GridView导出Excel功能

using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Runtime.CompilerServices;using System.Text;using System.Web;using System.Web.Compilation;using System.Web.UI;using System.Web.UI.WebControls; namespace Web{ 

flex 导出Excel功能实现

方法一: 1.Excel导出主要代码: try   {    var bytes: ByteArray = new ByteArray();    bytes.writeMultiByte(DataGridExporter.exportSCV(dataGrid),"cn-gb");    var fr:FileReference = new FileReference();    var date:Date = new Date();    var dateTime:String =

项目笔记:导出Excel功能分sheet页插入数据

导出Excel功能分sheet页处理数据: /*导出EXCEL*/ public void createExcel() { log.info("导出Excel功能已经启动-BEGIN"); JxlUtil jsl = new JxlUtil(); List<Device> dataList =new ArrayList<Device>(); List<DeviceExport> list = new ArrayList<DeviceExport

laravel-admin 自定义导出excel功能,并导出图片

https://www.jianshu.com/p/91975f66427d 最近用laravel-admin在做一个小项目,其中用到了excel导出功能. 但是laravel-admin自带的导出功能不带图片,并且导出的数据有很多冗余的字段,并非我所需要的功能. 所以参考官方文档调整代码,实现了自定义导出excel文件,并且带上图片: 步骤如下: 1. 安装laravel-excel插件 可参考laravel5.5 中使用laravel-excel composer require maatw

asp.net core web的导入导出excel功能

这里主要记录下asp.net core web页面上进行导入导出excel的操作. 主要是导入,因为现在使用的很多前端框架(例如kendo ui)本身就有导出的功能. 这里使用到EPPlus.Core,其实对于excel的导入导出还可以使用NPOI, 这里讲解EPPlus的方式 1.创建asp.net core web (mvc)项目 效果图如下 2.在项目上右键,进入nuget管理器,安装EPPlus.Core 3.添加一个XlsxController控制器,在其中添加导入和导出功能 usin

thinkphp导出excel功能封装

官网http://phpexcel.codeplex.com/下载最新PHPExcel放到tp框架的核心目录ThinkPHP里面的Vendor下 1 public function test(){ 2 $xlsName = "用户"; 3 4 //注意 数组第一个字段必须是小写 数组第二个(列标题)根据你的情况填写 5 $xlsCell = array( 6 array('字段1','账号序列'), 7 array('字段2','登录账户'), 8 array('字段3','账户昵称'

Atitit.导出excel功能的设计 与解决方案

1.1. 项目起源于背景1 1.2. Js  jquery方案(推荐)jquery.table2excel1 1.3. 服务器方案2 1.4. 详细信息2 1.5. 参考4 1.1. 项目起源于背景 正好我们项目也正好在研究更快速的导出excel的方法..昨天终于有了结论..除了我们常用的后端导出excel,前端js导出excel效果也不错,估计可以覆盖90%的领域...所以更好的导出方案就是 js导出(90%)+后端语言导出(10%),取长补短,结合使用 1.2. Js  jquery方案(推

java、jsp导出excel功能备份

问题踩坑: ajax请求不能下载文件 必须这样: <a href="/media">点击下载Excel</a> 或者 location.href = '/media'; js取表单数据: p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 20.0px Consolas; color: #788d93 } span.s1 { color: #c39900 } span.s2 { color: #2fafa9 } var s

DataTable 更改在有数据列的类型方法+DataTable 导出excel功能

/// <summary> /// 导出功能 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btn_export_Click(object sender, EventArgs e) { try { string strSql = CreateStrWhere