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 ...
随机推荐
- 【LeetCode】二叉搜索树的前序,中序,后续遍历非递归方法
前序遍历 public List<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> list = n ...
- Oracle分析函数-nulls first/nulls last
select * from criss_sales; 通过rank().dense_rank().row_number()对记录进行全排列.分组排列取值但有时候,会遇到空值的情况,空值会影响得到的结果 ...
- vs 2015 项目筛选器没了,.h头文件和.cpp文件混在一起了
场景: git 拉取 VS 2015 项目,打开之后,.h头文件和.cpp文件混在一起了. 解决方案: 需要XXX..vcxproj.filters 文件.
- iOS企业版打包 发布在线安装包 plist
本文转载至 http://blog.csdn.net/u011452278/article/details/49511385 原文转载:http://blog.csdn.net/pang040328/ ...
- 如何优雅的选择字体(font-family)
大家都知道,在不同操作系统.不同游览器里面默认显示的字体是不一样的,并且相同字体在不同操作系统里面渲染的效果也不尽相同,那么如何设置字体显示效果会比较好呢?下面我们逐步的分析一下: 一.首先我们看看各 ...
- Node bak
process.on('uncaughtException', function (err) { logger.info('Local Server Exception: ') logger.info ...
- JBPM工作流(四)——管理流程定义
概念: ProcessDefinition,流程定义:一个流程的步骤说明,如一个请假流程.报销流程.是一个规则. ProcessDefinition,流程定义对象,是解析.jpdl.xml文件得到流程 ...
- 13 form表单
form表单中可包括 <input > 类型包括 text(name,value) password(name,value) checkbox(name,value) radio(chec ...
- ajax里post 设置请求头的编码格式
我们常用的ajax形式就是post和get.post需要设置请求头,那么问题来了: 首先,为什么get不需要设置编码格式? 其次:不设置post请求头编码格式可以吗? 还有:常用的请求头编码格式有哪些 ...
- centOS 安装gitlab-runner
1. curl -L https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.rpm.sh | sud ...