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();
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的更多相关文章
- [Stephen]Export from Excel to ALM
1.根据当前安装的ALM版本和Excel版本到https://hpln.hp.com/page/alm-excel-addin-page中对应的插件进行下载安装,安装时Excel需要关闭.安装成功后, ...
- 进阶-案例九: WD中实现export 到Excel,Doc,Txt.
1.导出excel 文件代码 导出事件代码: METHOD onactionimport . *导出excel: DATA: lo_node TYPE REF TO if_wd_context_nod ...
- How to Export to Excel
https://simpleisbetterthancomplex.com/tutorial/2016/07/29/how-to-export-to-excel.html Export data to ...
- 笔记11 export to excel
参考两篇博客:http://blog.csdn.net/zyming0815/article/details/5939104 http://blog.csdn.net/g710710/article/ ...
- We refined export to Excel for SharePoint
http://sysmagazine.com/posts/208948/ http://sharepointwikipedia.blogspot.kr/2013/05/export-to-spread ...
- csharp: DataTable export to excel,word,csv etc
http://code.msdn.microsoft.com/office/Export-GridView-to-07c9f836 https://exporter.codeplex.com/ htt ...
- 笔记12 export to excel (NPOI)
1:filestream 熟悉关于文件操作 ==>fs.Seek(0, SeekOrigin.Begin);//每次打开文件, ==>若果重写覆盖的话,必须先清空 fs.SetLength ...
- javascript export excel
<input type="button" onclick="tableToExcel('tablename', 'name')" value=" ...
- [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 ...
随机推荐
- 5个最好用AngularJS构建应用程序框架
如果你打算建立自己的Web应用与AngularJS,那么现在是时候开始了.如果这个想法吓到你了,删除所有的恐慌,从你的头脑中有一些框架,AngularJS提供方便的支持.有一些预先的框架,使用框架可以 ...
- 再杀掉app之后 删除NSUserDefault存在本地的数据
这两天在处理 app退出后删除本地数据 在appDelegate里的这个函数里设置发现进不去 - (void)applicationWillTerminate:(UIApplication*)ap ...
- 利用pentestbox打造ms17-010移动"杀器"
本文首发Freebuf,属原创奖励计划,未经许可禁止转载. 链接:http://www.freebuf.com/articles/system/132274.html 一. 前言 前段时间Shadow ...
- 【iCore4 双核心板_ARM】例程三十:U_DISK_IAP_FPGA实验——更新升级FPGA
实验现象及操作说明: 1.将升级文件拷入U盘system文件夹中,通过U盘转接线将U盘连接到iCore4 USB OTG接口. 2.烧写程序成功,绿色ARM·LED灯点亮,三色FPGA·LED灯循环点 ...
- IIS 配置详解 请求长度限制调整
当上传一个超过30M的文件时,服务器会重定向至404.13页面,报错如下: HTTP Error 404.13 - Not Found The request filtering module is ...
- 【QT】文件读写操作
读取输出: QFile file("D:/Englishpath/QTprojects/1.dat"); if(!file.open(QIODevice::ReadOnly)) { ...
- javascript:没有定义的变量和没有定义的属性
1. 没有定义的变量 window.onload = function() { alert(a); // 报错: Uncaught ReferenceError: a is not defined / ...
- 【App】不通过App Store实现ios应用分发下载安装(转)
转自:https://www.cnblogs.com/star91/p/5018995.html 最近公司的项目准备着手宣传工作了,宣传手册上要印制App的下载地址二维码,但是客户端应用还未上线, ...
- vim不支持鼠标中键拷贝粘贴
ubuntu 和mint默认安装的vim是不支持系统剪切.粘贴版的,需要执行以下安装:sudo apt-get install vim-gnome
- 算法-KMP
KMP算法的作用在于在一个主串中查找一个主串. 传统查找子串的方法是一个字符一个字符的比较,代码如下: public static int notKMP(String main,String sub) ...