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 ...
随机推荐
- netstat实现原理
因为最近接手的项目是基于嵌入式Linux openwrt的,一开始以为会跟之前的服务器开发没什么大的区别,但是遇到问题去分析的时候才发现,工具链还是有些差别的,openwrt的netstat是属于一个 ...
- Android 反编译apk
工具介绍: apktool 作用:资源文件获取,可以提取出图片文件和布局文件进行使用查看 下载地址:https://bitbucket.org/iBotPeaches/apktool/downl ...
- 使用PgBouncer连接池
1.pgbouncer 的介绍 pgbouncer是一个针对PostgreSQL数据库的轻量级连接池,任何目标应用都可以把 pgbouncer 当作一个 PostgreSQL/Greenplum 服务 ...
- JavaScript Practices
不定时更新:https://github.com/zhengyeye/JS-practices Day1:关于创建对象的几种方式: Day3:原型 早前一篇:https://www.cnblogs.c ...
- JavaScript通过递归合并JSON
通过递归合并JSON: function mergeJSON(o, n) { let oType = Object.prototype.toString.call(o); let nType = Ob ...
- jenkins之 Throttle Concurrent Builds使用
Jenkins控制并发插件 Throttle Concurrent Builds介绍,管网见:https://github.com/jenkinsci/throttle-concurrent-buil ...
- nw.js---开发一个百度浏览器
使用nw.js开发一个简单的百度浏览器就很简单了,只需要在配置里面写入: { // "main": "index.html", "main" ...
- poj 1228
就是给你一堆点,看这些点能否构成一个 稳定的凸包. 凸包每条边上有3个及以上的点就可以了. #include <cstdio> #include <cstring> #incl ...
- 20.react库 入门
vue插件: 使用方式:Vue.use(插件名称); {}/function 1.对象 export default { install(Vue,options){ } } 2.函数 export d ...
- C++打开剪切板,获取剪切板数据
if (::OpenClipboard(NULL) && ::IsClipboardFormatAvailable(CF_HDROP)) { HDROP hDrop = (HDROP) ...