将查询到的数据导出到Excel终结版

2023-12-09 17:39

本文主要是介绍将查询到的数据导出到Excel终结版,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

    吐槽

      最近新项目需要用到导出数据到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 = 10,/// <summary>/// execl单元格的货币格式/// </summary>Number = 20}
}

>>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'?>
<Workbookxmlns='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 <= 0){return;}PropertyDescriptorCollection properties = FindProperties();if (properties.Count <= 0){return;}string content = string.Empty;for (int i = 0; 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 = 0; 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 != 0 && arrDesc[0].isExport){ExeclFiledType eft = arrDesc[0].execlType;string execlTypeStr = (int)eft == 0 ? "s1" : eft.ToString();string execlDataTypeStr = (int)eft == 0 ? "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 > 0){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 = 0; 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 != 0 && arrDesc[0].isExport){sb.Append("<Column ss:Width='100'/>");sheader.Append("<Cell  ss:StyleID='header'>\n<Data ss:Type='String'>");obj = arrDesc[0].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 > 0){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[0].GetCustomAttributes(typeof(ExportingField), false);return arrDesc == null || arrDesc.Length == 0 ? new ExportingField(false, string.Empty) : arrDesc[0];}}
}

 导出效果如下:

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

这篇关于将查询到的数据导出到Excel终结版的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/474551

相关文章

Linux下利用select实现串口数据读取过程

《Linux下利用select实现串口数据读取过程》文章介绍Linux中使用select、poll或epoll实现串口数据读取,通过I/O多路复用机制在数据到达时触发读取,避免持续轮询,示例代码展示设... 目录示例代码(使用select实现)代码解释总结在 linux 系统里,我们可以借助 select、

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

MyBatis Plus大数据量查询慢原因分析及解决

《MyBatisPlus大数据量查询慢原因分析及解决》大数据量查询慢常因全表扫描、分页不当、索引缺失、内存占用高及ORM开销,优化措施包括分页查询、流式读取、SQL优化、批处理、多数据源、结果集二次... 目录大数据量查询慢的常见原因优化方案高级方案配置调优监控与诊断总结大数据量查询慢的常见原因MyBAT

C#利用Free Spire.XLS for .NET复制Excel工作表

《C#利用FreeSpire.XLSfor.NET复制Excel工作表》在日常的.NET开发中,我们经常需要操作Excel文件,本文将详细介绍C#如何使用FreeSpire.XLSfor.NET... 目录1. 环境准备2. 核心功能3. android示例代码3.1 在同一工作簿内复制工作表3.2 在不同

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

Pandas处理缺失数据的方式汇总

《Pandas处理缺失数据的方式汇总》许多教程中的数据与现实世界中的数据有很大不同,现实世界中的数据很少是干净且同质的,本文我们将讨论处理缺失数据的一些常规注意事项,了解Pandas如何表示缺失数据,... 目录缺失数据约定的权衡Pandas 中的缺失数据None 作为哨兵值NaN:缺失的数值数据Panda

C++中处理文本数据char与string的终极对比指南

《C++中处理文本数据char与string的终极对比指南》在C++编程中char和string是两种用于处理字符数据的类型,但它们在使用方式和功能上有显著的不同,:本文主要介绍C++中处理文本数... 目录1. 基本定义与本质2. 内存管理3. 操作与功能4. 性能特点5. 使用场景6. 相互转换核心区别

java读取excel文件为base64实现方式

《java读取excel文件为base64实现方式》文章介绍使用ApachePOI和EasyExcel处理Excel文件并转换为Base64的方法,强调EasyExcel适合大文件且内存占用低,需注意... 目录使用 Apache POI 读取 Excel 并转换为 Base64使用 EasyExcel 处

python库pydantic数据验证和设置管理库的用途

《python库pydantic数据验证和设置管理库的用途》pydantic是一个用于数据验证和设置管理的Python库,它主要利用Python类型注解来定义数据模型的结构和验证规则,本文给大家介绍p... 目录主要特点和用途:Field数值验证参数总结pydantic 是一个让你能够 confidentl