博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
export to excel
阅读量:7174 次
发布时间:2019-06-29

本文共 6650 字,大约阅读时间需要 22 分钟。

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
(List
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
(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
users = db.Database.SqlQuery
(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
(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个最酷的linux单行命令
查看>>
【MySQL运维】解决由于中继日志报错导致主从故障一例
查看>>
myeclipse 10 在mac retina 屏幕下显示字体模糊解决方法
查看>>
创建自定义的指令
查看>>
javascript对象中判断属性
查看>>
git删除分支与合并分支
查看>>
Python元组
查看>>
HD TUNE以及所有其他硬盘检测工具都不能使用的情况
查看>>
Linux内存分析
查看>>
vSphere 5.5 vCenter迁移至分布式交换机
查看>>
排序 遍历
查看>>
第二次作业
查看>>
Mysql主从复制
查看>>
高斯消元法解非奇异线性方程组的MATLAB程序
查看>>
CSS3 3d环境实现立体 魔方效果代码
查看>>
全面总结sizeof的用法(定义、语法、指针变量、数组、结构体、类、联合体、位域位段)...
查看>>
python2升级到python3
查看>>
做好该做的把未来交给明天
查看>>
脚本里添加crontab的方法
查看>>
configure:error: Package requirements (libffi >= 3.0.0) were not met
查看>>