export to excel

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
npoi是重点。

定义一个exporttoexcel的类

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsServer.Log;

namespace Zige.Wechat.Common
{
    public class ExportToExcel
    {
        private static readonly Logger _logger = LogManager.GetCurrentClassLogger();

        public static void RenderToExcel2003<T>(List<T> datas, Stream stream)
        {
            IWorkbook workbook = null;
            ISheet sheet = null;
            IRow dtRow = null;

            try
            {
                workbook = new HSSFWorkbook();
                sheet = workbook.CreateSheet("会员表");
                dtRow = sheet.CreateRow(0);
                Type type = typeof(T);
                PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type);

                //Data Header
                ICell cell1 = dtRow.CreateCell(0);
                cell1.SetCellValue("创建时间");
                ICell cell2 = dtRow.CreateCell(1);
                cell2.SetCellValue("昵称");
                ICell cell3 = dtRow.CreateCell(2);
                cell3.SetCellValue("手机号");
                ICell cell4 = dtRow.CreateCell(3);
                cell4.SetCellValue("安全密码");
                ICell cell5 = dtRow.CreateCell(4);
                cell5.SetCellValue("手机验证");
                ICell cell6 = dtRow.CreateCell(5);
                cell6.SetCellValue("状态");


                int rowIndex = 1;
                foreach (T data in datas)
                {
                    object o = data;
                    dtRow = sheet.CreateRow(rowIndex);
                    for (int j = 0; j < properties.Count; j++)
                    {
                        PropertyDescriptor property = properties[j];
                        object value = property.GetValue(o);
                        ICell cell = dtRow.CreateCell(j);
                        if (j == 4) 
                        {
                            if (value.ToString()== "true")
                            { 
                                value = "";
                            }
                            else 
                            {
                                value = "";
                            }
                        }
                        if (j == 5)
                        {
                            if (value.ToString() == "true")
                            {
                                value = "";
                            }
                            else
                            {
                                value = "";
                            }
                        }
                        SetCellValue(cell, value);
                    }
                    rowIndex++;
                }

                workbook.Write(stream);
                stream.Flush();
            }
            catch (Exception ex)
            {
                _logger.ErrorException("Failed to export to excel.", ex);
            }
            finally
            {
                stream.Close();
                sheet = null;
                workbook = null;
            }
        }

        public static void SetCellValue(ICell cell, object value)
        {
            try
            {
                if (value is DateTime)
                {
                    cell.SetCellType(CellType.String);
                    cell.SetCellValue(((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss"));
                }
                else if (value is TimeSpan)
                {
                    cell.SetCellValue(new DateTime(1900, 1, 1) + (TimeSpan)value);
                }
                else if (value is int || value is short || value is float || value is double)
                {
                    cell.SetCellValue(Convert.ToDouble(value));
                }
                else
                {
                    cell.SetCellValue(value.ToString());
                }
            }
            catch(Exception ex)
            {
                _logger.ErrorException("Failed to set cell value.", ex);
            }
        }

    }
}

然后在api中调用方法

   using (ZigeDbContext db = Heart.CreateZigeDbContext())
            {
                try
                {
                    //var orders_1 = db.Database.SqlQuery<Order>(sqlText).ToList();
                    var parents = db.Parents.Select(p => new ParentInfo
                    {
                        CreatedTime = p.CreatedTime,
                        NickName=p.NickName,
                        PhoneNumber=p.PhoneNumber,
                        ProtectionPassword = p.ProtectionPassword,
                        IsPhoneNumberVerified=p.IsPhoneNumberVerified,
                        IsEnabled=p.IsEnabled,
                    }).OrderBy(or => or.CreatedTime).ToList();
                    //List<UserAccountInfo> users = db.Database.SqlQuery<UserAccountInfo>(sqlText, sqlParamterStartTime, sqlParameterEndTime).ToList();


                    string filePath = "~/Content/UploadFolder/" + "会员表" + "(导出时间" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm") + ").xls";
                    if (System.IO.File.Exists(Server.MapPath(filePath)))
                    {
                        System.IO.File.Delete(Server.MapPath(filePath));
                    }

                    FileStream file = new FileStream(Server.MapPath(filePath), FileMode.Create);
                    ExportToExcel.RenderToExcel2003<ParentInfo>(parents, file);
                    var url = filePath.Substring(2, filePath.Length - 2);
                    var description = "导出日期:" + DateTime.Now.ToString();
                    //CMSLogUtility.WriteLog("导出OLO新注册用户", Guid.Empty, string.Empty, description);
                    return Json(new { Code = 1, Message = url }, JsonRequestBehavior.AllowGet);
                }
                catch (Exception ex)
                {

                    throw (ex);
                }
            }

在js调用api

 $("#exportToExcel").on("click", function () {
        var url = getRawUrl("Parents/ExportToExcel");
       // $("#loading").show();
        $.ajax({
            url: url,
            type: "GET",
            cache: false,
            success: function (result) {
                $("#loading").hide();
                location.href = "http://" + location.host + baseServerUrl + result.Message;
            }, error: function () {
                //$("#loading").hide();
                alert("由于网络原因,导出失败!");
            }
        });
    });

 

转载于:https://www.cnblogs.com/tomahawk/p/4544523.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值