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();
Type type = typeof(T);
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(type); //Data Header
ICell cell1 = dtRow.CreateCell();
cell1.SetCellValue("创建时间");
ICell cell2 = dtRow.CreateCell();
cell2.SetCellValue("昵称");
ICell cell3 = dtRow.CreateCell();
cell3.SetCellValue("手机号");
ICell cell4 = dtRow.CreateCell();
cell4.SetCellValue("安全密码");
ICell cell5 = dtRow.CreateCell();
cell5.SetCellValue("手机验证");
ICell cell6 = dtRow.CreateCell();
cell6.SetCellValue("状态"); int rowIndex = ;
foreach (T data in datas)
{
object o = data;
dtRow = sheet.CreateRow(rowIndex);
for (int j = ; j < properties.Count; j++)
{
PropertyDescriptor property = properties[j];
object value = property.GetValue(o);
ICell cell = dtRow.CreateCell(j);
if (j == )
{
if (value.ToString()== "true")
{
value = "是";
}
else
{
value = "否";
}
}
if (j == )
{
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(, , ) + (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(, filePath.Length - );
var description = "导出日期:" + DateTime.Now.ToString();
//CMSLogUtility.WriteLog("导出OLO新注册用户", Guid.Empty, string.Empty, description);
return Json(new { Code = , 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("由于网络原因,导出失败!");
}
});
});

export to excel的更多相关文章

  1. [Stephen]Export from Excel to ALM

    1.根据当前安装的ALM版本和Excel版本到https://hpln.hp.com/page/alm-excel-addin-page中对应的插件进行下载安装,安装时Excel需要关闭.安装成功后, ...

  2. 进阶-案例九: WD中实现export 到Excel,Doc,Txt.

    1.导出excel 文件代码 导出事件代码: METHOD onactionimport . *导出excel: DATA: lo_node TYPE REF TO if_wd_context_nod ...

  3. How to Export to Excel

    https://simpleisbetterthancomplex.com/tutorial/2016/07/29/how-to-export-to-excel.html Export data to ...

  4. 笔记11 export to excel

    参考两篇博客:http://blog.csdn.net/zyming0815/article/details/5939104 http://blog.csdn.net/g710710/article/ ...

  5. We refined export to Excel for SharePoint

    http://sysmagazine.com/posts/208948/ http://sharepointwikipedia.blogspot.kr/2013/05/export-to-spread ...

  6. csharp: DataTable export to excel,word,csv etc

    http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...

  7. 笔记12 export to excel (NPOI)

    1:filestream 熟悉关于文件操作 ==>fs.Seek(0, SeekOrigin.Begin);//每次打开文件, ==>若果重写覆盖的话,必须先清空 fs.SetLength ...

  8. javascript export excel

    <input type="button" onclick="tableToExcel('tablename', 'name')" value=" ...

  9. [Rodbourn's Blog]How to export Excel plots to a vector image (EPS, EMF, SVG, etc.)

    This is a bit of a workaround, but it's the only way I know of to export an Excel plot into a vector ...

随机推荐

  1. lombok自带的slfj使用方法

    1.pom.xml <dependency> <groupId>org.projectlombok</groupId> <artifactId>lomb ...

  2. delphi从TRichEdit获得RTF格式文本(PC版本)

    function GetRTF(RE: TRichedit): string;varstrStream: TStringStream;beginstrStream := TStringStream.C ...

  3. 匿名函数gc分析

    测试一:使用member function创建action会产生gc,不管该函数是否访问外部变量: private System.Action memberAct = null; // gc 112B ...

  4. oracle sql语句实现累加、累减、累乘、累除

    在oracle开发过程中经常会遇到累加.减.乘.除的问题.下面对这个做个小的总结 ---创建测试表 CREATE TABLE TEST( PARENT_ID NUMBER, PART_ID NUMBE ...

  5. gsoap入门:C/C++代码生成及编译--包含soapcpp2 -qname添加命名空间后报错的解决方法--可用

    gsoap是什么 先来一段百度百科,说说gsoap是什么: gSOAP一种跨平台的开源的C/C++软件开发工具包.生成C/C++的RPC代码,XML数据绑定,对SOAP Web服务和其他应用形成高效的 ...

  6. 使用 Postman 取得 Token 打另一隻 API

    使用 Postman 取得 Token 打另一隻 API Spring MVC token 统一校验和user 信息自动获取 使用token和SpringMVC来实现安全的RESTFul接口 spri ...

  7. 解决webdiyer:AspNetPager分页控件在IE模式下点击页号不能翻页的问题。

    在网站根目录下新建ie.browser文件, 然后用记事本打开. 将以下代码粘贴进去,保存即可,目的是让其与IE11的 UserAgent 匹配,使 .net framework 认识这是一个已知的浏 ...

  8. C#项目”XXXXX”针对的是”.NETFramework,Version=v4.7.1”但此计算机没有安装它

    遇到这样一个问题:C#项目”XXXXX”针对的是”.NETFramework,Version=v4.7.1”但此计算机没有安装它 就是我在打开别人的项目,发现别人的项目.Net Framework的版 ...

  9. Oracle 10G 安装文档

    Oracle 10G安装指导 1. 解压文件10201_database_win32.zip,并双击解压目录下的setup.exe,出现安装界面,如下: 2. 输入口令和确认口令,如:password ...

  10. 为 git设置代理

    普通设置 git config --global http.proxy 'socks5://127.0.0.1:1080'git config --global https.proxy 'socks5 ...