吐槽

最近新项目需要用到导出数据到Excel,试了试之前写的一篇博文,但是感觉那个不太好,主要原因是没能实现样式控制,今天我们就来介绍一种新的导出Excel方法,而且这种方法很轻量级,它利用xml生成,然后加不同后缀进行导出不同格式的文件。

正文

1.前台实现(这里直接使用submit将参数post到后台即可。)

 function download() {
$('form').submit();
}

2.控制器实现

return new XmlExcelResult<MemberMessageListDto>(list, "会籍公海");

3.帮助类实现

>>ExportingField.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Cloud.Arch.Utility.Excel
{
[AttributeUsage(AttributeTargets.Property
, AllowMultiple = false, Inherited = true)]
public class ExportingField : System.Attribute
{
public bool isExport;
public string exportTitle;
/// <summary>
/// execl格式串
/// </summary>
public ExeclFiledType execlType;
public ExportingField() { }
public ExportingField(bool isexport, string exporttitle)
{
isExport = isexport;
exportTitle = exporttitle;
}
public ExportingField(bool isexport, string exporttitle, ExeclFiledType execltype)
{
isExport = isexport;
exportTitle = exporttitle;
execlType = execltype;
}
}
public enum ExeclFiledType
{
/// <summary>
/// execl单元格的文本
/// </summary>
String = ,
/// <summary>
/// execl单元格的货币格式
/// </summary>
Number =
}
}

>>XMLExcelResult.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Mvc; namespace Cloud.Arch.Utility.Excel
{
/// <summary>
/// 提供将泛型集合数据导出Excel文档。 要转换的类型的属性必须用ExportingField声明 才能识别
/// </summary>
/// <typeparam name="T"></typeparam>
public class XmlExcelResult<T> : ActionResult where T : new()
{
public XmlExcelResult(IList<T> entity, string fileName)
{
this.Entity = entity;
DateTime time = DateTime.Now;
this.FileName = string.Format("{0}{1}", fileName,
time.ToString("yyMMddhhmmss"));
} public XmlExcelResult(IList<T> entity)
{
this.Entity = entity;
DateTime time = DateTime.Now;
this.FileName = string.Format("{0}_{1}_{2}_{3}",
time.Month, time.Day, time.Hour, time.Minute);
} public IList<T> Entity
{
get;
set;
}
public string FileName
{
get;
set;
} public override void ExecuteResult(ControllerContext context)
{
if (Entity == null)
{
new EmptyResult().ExecuteResult(context);
return;
}
SetResponse(context);
} /// <summary>
/// 设置并向客户端发送请求响应。
/// </summary>
/// <param name="context"></param>
private void SetResponse(ControllerContext context)
{
StringBuilder sBuilder = ConvertEntity();
byte[] bytestr = Encoding.UTF8.GetBytes(sBuilder.ToString());
context.HttpContext.Response.Clear();
context.HttpContext.Response.ClearContent();
context.HttpContext.Response.Buffer = true;
context.HttpContext.Response.Charset = "GB2312";
context.HttpContext.Response.ContentEncoding = System.Text.Encoding.UTF8;
context.HttpContext.Response.ContentType = "text/xml";
context.HttpContext.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ".xls");
context.HttpContext.Response.AddHeader("Content-Length", bytestr.Length.ToString());
context.HttpContext.Response.Write(sBuilder);
context.HttpContext.Response.Flush();
context.HttpContext.Response.End();
} /// <summary>
/// 把泛型集合转换成组合Excel表格的字符串。
/// </summary>
/// <returns></returns>
private StringBuilder ConvertEntity()
{
StringBuilder sb = new StringBuilder();
sb.Append(@"<?xml version='1.0'?>
<?mso-application progid='Excel.Sheet'?>
<Workbook
xmlns='urn:schemas-microsoft-com:office:spreadsheet'
xmlns:o='urn:schemas-microsoft-com:office:office'
xmlns:x='urn:schemas-microsoft-com:office:excel'
xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet'
xmlns:html='http://www.w3.org/TR/REC-html40'>
<DocumentProperties xmlns='urn:schemas-microsoft-com:office:office'>
<Author>Darl McBride</Author>
<LastAuthor>Bill Gates</LastAuthor>
<Created>2007-03-15T23:04:04Z</Created>
<Company>SCO Group, Inc.</Company>
<Version>11.8036</Version>
</DocumentProperties>
<ExcelWorkbook xmlns='urn:schemas-microsoft-com:office:excel'>
<WindowHeight>6795</WindowHeight>
<WindowWidth>8460</WindowWidth>
<WindowTopX>120</WindowTopX>
<WindowTopY>15</WindowTopY>
<ProtectStructure>False</ProtectStructure>
<ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
<Styles>
<Style ss:ID='Default' ss:Name='Normal'>
<Alignment ss:Vertical='Bottom' />
<Borders />
<Font />
<Interior />
<NumberFormat />
<Protection />
</Style>
<Style ss:ID='s1' ss:Name='s1'>
<Borders>
<Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/>
</Borders>
</Style>
<Style ss:ID='header' ss:Name='Header'>
<Font ss:FontName='宋体' x:CharSet='134' ss:Size='11' ss:Color='#FFFFFF'/>
<Alignment ss:Horizontal='Center' ss:Vertical='Center'/>
<Interior ss:Color='#0070C0' ss:Pattern='Solid'/>
<Borders>
<Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/>
</Borders>
</Style>
<Style ss:ID='Number'>
<Borders>
<Border ss:Position='Bottom' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Left' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Right' ss:LineStyle='Continuous' ss:Weight='1'/>
<Border ss:Position='Top' ss:LineStyle='Continuous' ss:Weight='1'/>
</Borders>
<NumberFormat ss:Format='&quot;¥&quot;#,##0;&quot;¥&quot;\-#,##0'/>
</Style> </Styles>
<Worksheet ss:Name='Sheet1'>
<Table x:FullColumns='1' x:FullRows='1'>
");
AddTableHead(sb);
AddTableBody(sb);
sb.Append(@"</Table> <WorksheetOptions xmlns='urn:schemas-microsoft-com:office:excel'>
<Print>
<ValidPrinterInfo />
<HorizontalResolution>600</HorizontalResolution>
<VerticalResolution>600</VerticalResolution>
</Print>
<Selected />
<Panes>
<Pane>
<Number>3</Number>
<ActiveRow>5</ActiveRow>
<ActiveCol>1</ActiveCol>
</Pane>
</Panes>
<ProtectObjects>False</ProtectObjects>
<ProtectScenarios>False</ProtectScenarios>
</WorksheetOptions></Worksheet></Workbook>");
return sb;
} /// <summary>
/// 根据IList泛型集合中 用ExportingField特性标示的属性值来组合Excel表格。
/// </summary>
/// <param name="sb"></param>
private void AddTableBody(StringBuilder sb)
{ if (Entity == null || Entity.Count <= )
{
return;
}
PropertyDescriptorCollection properties = FindProperties(); if (properties.Count <= )
{
return;
}
string content = string.Empty;
for (int i = ; i < Entity.Count; i++)
{
Type t = Entity[i].GetType();
PropertyInfo[] fields = t.GetProperties();
sb.Append("<Row ss:AutoFitHeight='0' ss:Height='20'>\n");
for (int j = ; j < fields.Length; j++)
{
string sign = string.Empty;
ExportingField[] arrDesc = (ExportingField[])fields[j].GetCustomAttributes(typeof(ExportingField), false);
object obj = null;
if (arrDesc != null && arrDesc.Length != && arrDesc[].isExport)
{
ExeclFiledType eft = arrDesc[].execlType;
string execlTypeStr = (int)eft == ? "s1" : eft.ToString();
string execlDataTypeStr = (int)eft == ? "String" : eft.ToString();
sb.Append("<Cell ss:StyleID='" + execlTypeStr + "'>\n<Data ss:Type='" + execlDataTypeStr + "'>"); obj = fields[j].GetValue(Entity[i], null);
content = obj == null ? string.Empty : obj.ToString();
//var arr = content.Split("<br/>".ToCharArray());
var arr = Regex.Split(content, "<br/>", RegexOptions.IgnoreCase);
if (arr != null && arr.Length > )
{
foreach (var s in arr)
{
if (!string.IsNullOrWhiteSpace(s))
{
sb.Append("<![CDATA[");
sb.Append(s);
sb.Append("]]>");
sb.Append("<br/>");
}
}
}
sb.Append("</Data>\n</Cell>");
} }
sb.Append("</Row>\n");
}
} /// <summary>
/// 根据指定类型T的所有根用ExportingField特性标示的属性值来组合Excel表头。
/// </summary>
/// <param name="sb"></param>
private void AddTableHead(StringBuilder sb)
{
Type t = typeof(T);
PropertyInfo[] fields = t.GetProperties();
StringBuilder sheader = new StringBuilder();//存储标题行信息
sheader.Append("<Row ss:AutoFitHeight='0' ss:Height='20'>\n");
string content = string.Empty;
for (int j = ; j < fields.Length; j++)
{
string sign = string.Empty;
ExportingField[] arrDesc = (ExportingField[])fields[j].GetCustomAttributes(typeof(ExportingField), false);
object obj = null;
if (arrDesc != null && arrDesc.Length != && arrDesc[].isExport)
{
sb.Append("<Column ss:Width='100'/>");
sheader.Append("<Cell ss:StyleID='header'>\n<Data ss:Type='String'>");
obj = arrDesc[].exportTitle;
content = obj == null ? string.Empty : obj.ToString();
// var arr = content.Split("<br/>".ToCharArray());
var arr = Regex.Split(content, "<br/>", RegexOptions.IgnoreCase);
if (arr != null && arr.Length > )
{
foreach (var s in arr)
{
if (!string.IsNullOrWhiteSpace(s))
{
sheader.Append("<![CDATA[");
sheader.Append(s);
sheader.Append("]]>");
sheader.Append("<br/>");
}
}
}
sheader.Append("</Data>\n</Cell>\n");
} }
sheader.Append("</Row>");
sb.Append(sheader.ToString());
} /// <summary>
/// 返回指定类型T的属性集合。
/// </summary>
/// <returns></returns>
private static PropertyDescriptorCollection FindProperties()
{
return TypeDescriptor.GetProperties(typeof(T));
}
/// <summary>
/// 获取枚举类型的描述信息
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public static ExportingField GetDescription(object obj)
{
string objName = obj.ToString();
Type t = obj.GetType();
FieldInfo[] fields = t.GetFields(); ExportingField[] arrDesc = (ExportingField[])fields[].GetCustomAttributes(typeof(ExportingField), false); return arrDesc == null || arrDesc.Length == ? new ExportingField(false, string.Empty) : arrDesc[];
}
}
}

导出效果如下:

如何要更改样式的话,可以通过调整文件样式,然后导出为xml格式,然后把程序里面的xml替换掉就OK了。具体自己可以试试~

将查询到的数据导出到Excel终结版的更多相关文章

  1. 在ASP.NET MVC中利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。

    正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的'好'东西记 ...

  2. 利用Aspose.cells 将查询出的数据导出为excel,并在浏览器中下载。

    正题前的唠叨 本人是才出来工作不久的小白菜一颗,技术很一般,总是会有遇到一些很简单的问题却不知道怎么做,这些问题可能是之前解决过的.发现这个问题,想着提升一下自己的技术水平,将一些学的新的‘好’东西记 ...

  3. 使用POI把查询到的数据表数据导出到Excel中,一个表一个sheet.最详细!!!

    一.需求 我们会遇到开发任务: 经理:小王,你来做一下把数据库里的数据导出到Excel中,一个表是一个sheet,不要一个表一个Excel. 小王:好的,经理.(内心一脸懵逼) 二.前期准备 首先我们 ...

  4. 机房收费系统——在VB中将MSHFlexGrid控件中的数据导出到Excel

    机房收费系统中,好多查询的窗体都包含同一个功能:将数据库中查询到的数据显示在MSHFlexGrid控件中,然后再把MSHFlexGrid控件中的数据导出到Excel表格中. 虽然之前做过学生信息管理系 ...

  5. abp中文件下载,将内存数据导出到Excel并下载

    1.数据导出为Excel的Stream using System; using System.Collections.Generic; using System.IO; using Abp.Colle ...

  6. Delphi 数据导出到Excel

    好多办公软件特别是财务软件,都需要配备把数据导出到Excel,下面就来介绍两种数据导出方法 1.ADODB导出查询结果(此方法需要安装Excel) 2.二维表数据导出(根据Excel文件结构生成二进制 ...

  7. Pl/sql 如何将oracle的表数据导出成excel文件?

    oracle将表数据导出成excel文件的方法 1)在SQL窗体上,查询需要导出的数据 --查询数据条件-- ; 结果视图 2)在查询结果的空白处,右键选择Copy to Excel 3) 查看导出e ...

  8. 大批量数据导出到Excel的实现

    在平时的项目中,将数据导出到Excel的需求是很常见的,在此对一些常见的方法做以总结,并提供一种大数据量导出的实现. OLEDB   使用OLEDB可以很方便导出Excel,思路很简单,处理时将Exc ...

  9. struts2结合poi-3.7实现数据导出为excel

    我们在处理数据的时候,有可能要将数据导出到excel文件中,那么java中是怎么实现的呢?apache开发的poi就可以帮我们实现啦,它也是开源的代码,导入相应的jar包,就可以轻松实现,下面让我们来 ...

随机推荐

  1. c++ 编译期与运行期

    分享到 一键分享 QQ空间 新浪微博 百度云收藏 人人网 腾讯微博 百度相册 开心网 腾讯朋友 百度贴吧 豆瓣网 搜狐微博 百度新首页 QQ好友 和讯微博 更多... 百度分享 转自:http://h ...

  2. winform右键菜单

    public partial class Form1 : Form { ContextMenuStrip cms; Bitmap bm ; public Form1() { InitializeCom ...

  3. 用来生成get set string 方法

    https://projectlombok.org/ 主要是用来生成get set string 方法等等 原理是注解

  4. PIC EEPROM问题

    1.通过export出来的Hex烧录,EEPROM内容会根据Hex中关于EEPROM的定义而改变. 2.通过编译源文件烧录,如果没有勾选Preserve EEPROM on program则EEPRO ...

  5. [Intermediate Algorithm] - Sum All Primes

    题目 求小于等于给定数值的质数之和. 只有 1 和它本身两个约数的数叫质数.例如,2 是质数,因为它只能被 1 和 2 整除.1 不是质数,因为它只能被自身整除. 给定的数不一定是质数. 提示 For ...

  6. (转) shiro权限框架详解04-shiro认证

    http://blog.csdn.net/facekbook/article/details/54906635 shiro认证 本文介绍shiro的认证功能 认证流程 入门程序(用户登录和退出) 自定 ...

  7. In-Out Parameters inout keyword

    You write an in-out parameter by placing the inout keyword right before a parameter’s type. An in-ou ...

  8. 前端html之------>Table实现表头固定

    文章来源于:https://www.cnblogs.com/dacuotecuo/p/3657779.html,请尊重原创,转载请注明出处. 说明:这里主要实现了表头的固定和上下滚动的滑动实现:时间的 ...

  9. jQuery样式操作

    获取样式和设置样式 <p class='myClass'  title='this is p'>this is p</p> 样式其实就是class属性所以设置和获取样式都能用a ...

  10. TensorFlow+实战Google深度学习框架学习笔记(11)-----Mnist识别【采用滑动平均,双层神经网络】

    模型:双层神经网络 [一层隐藏层.一层输出层]隐藏层输出用relu函数,输出层输出用softmax函数 过程: 设置参数 滑动平均的辅助函数 训练函数 x,y的占位,w1,b1,w2,b2的初始化 前 ...