吐槽

最近新项目需要用到导出数据到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. Android GoogleMap 谷歌地图从零开始

    说明 由于国内使用v2最新的谷歌地图有很多限制,所有如果要在真机上测试运行要做一些准备 准备1: vpn必不可少啦 推荐cloud vpn或者betternet都是不错的免费vpn 准备2: 由于最新 ...

  2. MySQL快速创造百万测试数据

    CREATE TABLE `vote_record_memory` ( `id` INT (11) NOT NULL AUTO_INCREMENT, `user_id` VARCHAR (20) NO ...

  3. Outlook2010规则:尝试操作失败,找不到某个对象

    可以尝试通过清除规则的方法 启动 Outlook 并删除基于客户端的规则:outlook /cleanclientrules 如果失败,再执行这句 启动 Outlook 并删除基于服务器端的规则:ou ...

  4. ES : 软件工程学的复杂度理论及物理学解释

    系统论里面总是有一些通用的专业术语 比如复杂度.熵.焓,复杂度专门独立出来,成为复杂度理论 文章摘抄于:<非线性动力学> 刘秉政 编著  5.5 复杂性及其测度 热力学的几个专业术语 熵. ...

  5. macOS 不用任何第三方工具 简单两步使用 Automator 将截图转成@1x

    制作 Automator 脚本 打开 Automator -> 选择服务,左侧搜索 shell,双击打开,右侧粘贴以下内容,将上部 服务收到... 改成 没有输入,CMD+S保存,名称就叫 屏幕 ...

  6. CF div2 499 A. Stages

    Code: #include<cstdio> #include<algorithm> #include<iostream> using namespace std; ...

  7. TensorFlow+实战Google深度学习框架学习笔记(12)------Mnist识别和卷积神经网络LeNet

    一.卷积神经网络的简述 卷积神经网络将一个图像变窄变长.原本[长和宽较大,高较小]变成[长和宽较小,高增加] 卷积过程需要用到卷积核[二维的滑动窗口][过滤器],每个卷积核由n*m(长*宽)个小格组成 ...

  8. 实验一:JAVA实验环境搭建

    一. JDK的安装 1.输入 官网地址:http://www.oracle.com/technetwork/java/index.html 如图: 点击之后,就会进入这个界面,进入之后,往下拉点就会看 ...

  9. luogu 3768 简单的数学题 (莫比乌斯反演+杜教筛)

    题目大意:略 洛谷传送门 杜教筛入门题? 以下都是常规套路的变形,不再过多解释 $\sum\limits_{i=1}^{N}\sum\limits_{j=1}^{N}ijgcd(i,j)$ $\sum ...

  10. leetCode笔记--binary tree

    993. Cousins in Binary Tree In a binary tree, the root node is at depth 0, and children of each dept ...