1、这个功能就是在MVC框架中,将页面绑定的数据直接导出到Excel  中,数据源借助绑定页面的数据源,数据源需要在下载Excel 的地方按照ListJson 的方式加载上去。

1.1 准备工作(只读):ListJson 绑定数据方式如下:

此处显示到页面的数据我改成了下面的PageShoModel 中,方便导出Excel 的时候通用,如下:

修改后的ListJson 如下

1.2:前台 js 点击下载按钮设置将页面的列(cols) 传递向后台

代码:

//下载Excel
$("#btndownexcel").click(function () {

// cols 为页面绑定的列信息
var jsondata = {
Id: $("#Id").val(),
files: cols,
Values: {}
};

$(".inputform .datafield").each(function () {
jsondata.Values[$(this).attr("data-fieldname")] = $(this).val();
});
location.href = "/Plan/BigRepair/DownExcel?jsondata=" + JSON.stringify(jsondata);
})

2、后台通用导出方法

using Aspose.Cells;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace WY.ViewModels.Base
{
public class ComExportData
{
#region ExportExlData

/// <summary>
/// 将页面数据导出成 Excel
/// </summary>
/// <typeparam name="T"> list 显示转换的实体</typeparam>
/// <param name="jsondata">页面传递Json 有格式要求</param>
/// <param name="list">list 实体数据</param>
/// <returns></returns>
public static byte[] ExportExlData<T>(string jsondata, List<T> list)
{
byte[] bt = null;

JsonExportDataModel model = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonExportDataModel>(jsondata);

//页面传递的数据转换为需要的格式数据
string files_str = JsonConvert.SerializeObject(model.files);
files_str = files_str.Substring(1, files_str.Length - 2);

//标题
var listheader = JsonConvert.DeserializeObject<List<JsonExportHeaderModel>>(files_str);

//过滤掉隐藏列
listheader = listheader.Where(p => p.hidden == false && p.field != "op" && p.title != "").ToList();

Workbook workbook = new Workbook(); //工作簿
Worksheet sheet = workbook.Worksheets[0]; //工作表
Cells cells = sheet.Cells;//单元格

#region 样式

Style style1 = workbook.Styles[workbook.Styles.Add()];//新增样式
Style style2 = workbook.Styles[workbook.Styles.Add()];//新增样式
Style style4 = workbook.Styles[workbook.Styles.Add()];//新增样式

style1.HorizontalAlignment = TextAlignmentType.Center;
style1.Font.Name = "宋体";//文字字体
style1.Font.Size = 12;//文字大小
style1.Font.IsBold = true;//粗体
style1.Font.Color = Color.Black;//粗体
style1.BackgroundColor = Color.Green;
style1.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style1.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style1.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style1.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

style2.HorizontalAlignment = TextAlignmentType.Left;
style2.Font.Name = "宋体";//文字字体
style2.Font.Size = 12;//文字大小
style2.Font.IsBold = true;//粗体
style2.Font.Color = Color.Black;//粗体
style2.BackgroundColor = Color.Green;
style2.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style2.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

style4.HorizontalAlignment = TextAlignmentType.Center;//
style4.Font.Size = 10;
style4.Font.IsBold = false;
style4.Font.Color = Color.Black;//粗体
style4.ForegroundColor = Color.SlateBlue;
style4.ForegroundColor = Color.FromArgb(153, 204, 0);
style4.IsTextWrapped = true;
style4.Borders[BorderType.LeftBorder].LineStyle = CellBorderType.Thin;
style4.Borders[BorderType.RightBorder].LineStyle = CellBorderType.Thin;
style4.Borders[BorderType.TopBorder].LineStyle = CellBorderType.Thin;
style4.Borders[BorderType.BottomBorder].LineStyle = CellBorderType.Thin;

#endregion

#region 标题

//填写标题
for (int i = 0; i < listheader.Count(); i++)
{
cells[0, i].PutValue(listheader[i].title); //填写内容
cells[0, i].SetStyle(style1); //给单元格关联样式
cells.SetRowHeight(i, 20);
cells.SetColumnWidth(i, 25);
}

#endregion

#region 绑定数据

//var service = new TB_RepairPlanService();
数据源
//var list = service.PageList3All().Select(p => new ShowClass(p)).ToList();

//将需要导出的数据源按照列绑定成一个datatable
DataTable table = SetData<T>(list, listheader);

//绑定数据(第一行列已经绑定)
for (int row = 1; row < table.Rows.Count + 1; row++)
{
for (int col = 0; col < listheader.Count; col++)
{
cells[row, col].PutValue(table.Rows[row - 1][listheader[col].field]);//内容
cells[row, col].SetStyle(style4);
}
}

#endregion

#region 输出文件流

cells = sheet.Cells;
int columnCount = cells.MaxColumn; //获取表页的最大列数
int rowCount = cells.MaxRow; //获取表页的最大行数

for (int col = 0; col < columnCount; col++)
{
sheet.AutoFitColumn(col, 0, rowCount);
}
for (int col = 0; col < columnCount; col++)
{
cells.SetColumnWidthPixel(col, cells.GetColumnWidthPixel(col) + 30);
}

System.IO.MemoryStream ms = workbook.SaveToStream();//生成数据流
bt = ms.ToArray();

#endregion

return bt;
}

#endregion

#region SetData

/// <summary>
/// 将数据转换为DataTable 方便绑定到excel 中
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="items"></param>
/// <param name="jsonheader"></param>
/// <returns></returns>
private static DataTable SetData<T>(List<T> items, List<JsonExportHeaderModel> jsonheader)
{
List<string> listHeader = new List<string>();

//标题field
foreach (var header in jsonheader)
{
listHeader.Add(header.field.ToLower());
}

DataTable tb = new DataTable();

PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);

//总列数
int total_cols = 0;
//table 添加 columns
foreach (PropertyInfo prop in props)
{
//匹配列
if (listHeader.Contains(prop.Name.ToLower()))
{
Type t = GetCoreType(prop.PropertyType);
tb.Columns.Add(prop.Name, t);
total_cols++;
}
}

var values = new object[total_cols];

//列数
int col_index = 0;

//table 添加 rows
foreach (T item in items)
{
for (int i = 0; i < props.Length; i++)
{
//匹配列
if (listHeader.Contains(props[i].Name.ToLower()))
{
values[col_index] = props[i].GetValue(item, null);
col_index++;
}
}

tb.Rows.Add(values);
}

return tb;
}

/// <summary>
/// Determine of specified type is nullable
/// </summary>
private static bool IsNullable(Type t)
{
return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}

/// <summary>
/// Return underlying type if type is Nullable otherwise return the type
/// </summary>
private static Type GetCoreType(Type t)
{
if (t != null && IsNullable(t))
{
if (!t.IsValueType)
{
return t;
}
else
{
return Nullable.GetUnderlyingType(t);
}
}
else
{
return t;
}
}

#endregion

}
}

//类 JsonExportDataModel

public class JsonExportDataModel
{
public int Id { get; set; }

public dynamic files { get; set; }

public JObject Values { get; set; }

}

//类 JsonExportHeaderModel(此处可更具cols 扩展)

public class JsonExportHeaderModel
{
/// <summary>
/// 数据源 列名
/// </summary>
public string field { get; set; }

/// <summary>
/// Page 列名
/// </summary>
public string title { get; set; }

/// <summary>
/// Page 是否隐藏
/// </summary>
public bool hidden { get; set; }

}

3、后台通用导出调用。

[IgnoreAuthorizeFilter]
public ActionResult DownExcel(string jsondata)
{
var service = new TB_RepairPlanService();
//数据源
var list = service.PageList3All().Select(p => new PageShowClass(p)).ToList();
var bt = ComExportData.ExportExlData<PageShowClass>(jsondata, list);

//客户端保存的文件名
string fileName = "工作票列表.xls";

Response.Charset = "UTF-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fileName));
Response.BinaryWrite(bt);
Response.Flush();
Response.End();

return new EmptyResult();
}

4、注意:导出的地方需要使用到  Aspose.Cells.dll  、 Newtonsoft.Json.dll

转载于:https://www.cnblogs.com/MyLBlogs/p/6656951.html

MVC 中通用导出页面数据到Excel相关推荐

  1. oracle 数据 导出 excel 自动分多个文件,从oracle数据库中导出大量数据到excel中为什么自动分成了好几个excel文件《excel表格新手入门》...

    EXCEL中一个单元格中多行文本如何导入或复制到SQL SERVER 数据库表中? 保留换行符保存进数据表啊,读取出来显示的时候根据需要进行转换就行了,比如要在网页上显示,可以把换行符转换成HTML的 ...

  2. vue中导出json数据为excel表格并保存到本地

    继我上次成功利用vue和elemen把excel的数据导入至前端vue,因为excel表中的数据有些必填项没有填写或者填写错误(比如写错字)所以就要将没有成功导入的数据导出成一份excel表并保存至本 ...

  3. 使用poi导出大量数据到excel遇到的问题

    最近在工作遇到利用poi导出大量数据到excel并提供下载的运用场景,并遇到了一个问题,当数据量过大时(几十万),后台在进行数据写入excel中的过程会非常耗时,导致迟迟没有响应前台,结果数据还没导完 ...

  4. js+PHP利用PHPExcel导出表格数据到excel

    这里写自定义目录标题 前言 通过js筛选出表格数据 PHP利用PHPExcel导出表格数据到excel 前言 因为在开发平台的时候遇到了需要将表格数据导出到Excel的情况,通过百度找到了PHP插件P ...

  5. asp.net导出GridView数据到Excel

    最近做了一个导出GridView数据到Excel中的例子,把代码和遇到的一些问题放出来.  1        Response.Clear();  2        Response.Buffer = ...

  6. java 导出excel教程,[Java教程]导出大量数据到Excel的一种方式

    [Java教程]导出大量数据到Excel的一种方式 0 2012-07-09 17:00:11 在Java Web开发中,经常需要导出大量的数据到Excel,使用POI.JXL直接生成Excel,很容 ...

  7. php输出json到表格,Vue如何导出json数据到Excel电子表格方法

    本文主要介绍了Vue导出json数据到Excel电子表格的示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考,希望能帮助到大家. 一.安装依赖(前面基本一样) npm install file- ...

  8. php按列导出excel2010,excel2010官方下载 免费完整版 PHP导出MySQL数据到Excel文件fputcsv...

    这里的方法是利用fputcsv写CSV文件的方法,直接向浏览器输出Excel文件. 复制代码 代码如下: // 输出Excel文件头,可把user.csv换成你要的文件名 header('Conten ...

  9. php mysql生成excel文件,PHP导出MySQL数据到Excel文件简单示例

    这篇文章主要为大家详细介绍了PHP导出MySQL数据到Excel文件简单示例,具有一定的参考价值,可以用来参考一下. 对phpPHP导出MySQL数据到Excel文件简单示例感兴趣的小伙伴,下面一起跟 ...

最新文章

  1. api分层内部外部 spring_java - Spring boot restful API分层架构验证 - SO中文参考 - www.soinside.com...
  2. Mouse Without Borders 一套鼠标键盘控制多台电脑
  3. jQuery对象和DOM对象
  4. Linux Container 研究报告
  5. CVPR 2021 《Causal Attention for Vision-Language Tasks》论文笔记
  6. DFN封装系列ESD静电保护器件
  7. android activity 渐变,关于Android的径向渐变高级编程的实现
  8. Spring事务管理介绍
  9. Windows下断言的类型及实现
  10. 【Python3网络爬虫开发实战】3.1.2-处理异常
  11. Ubuntu如何定时清理内存
  12. 使用root安装nginx后使用非root运行方法
  13. asp.net+sql数据库学生信息管理系统
  14. PAT-A1013. 数素数 (20)
  15. 给新一代IT人的分享
  16. 揭秘摄像头黑产链:暴露在外的80端口
  17. GameCenter 使用指南
  18. 《linux内核分析》第三次课 实验作业
  19. 深度学习系列2:框架tensorflow
  20. 微软Project项目管理软件简介

热门文章

  1. pip 清华大学镜像_pip源很慢,更改成清华的镜像地址
  2. python写sql语句_python3将变量写入SQL语句的实现方式
  3. python 服务监控_promethues + python + flask监控后端服务状态
  4. 已知原函数和导函数的关系_根据函数表达式该如何求函数值
  5. 顺序执行命令需要哪个符号链接_18年MBA联考如何安排答题时间及顺序
  6. java 中之循环(for while do-while)详解
  7. 71计算机组装与维修期中,《计算机维修》期中考试卷
  8. linux安装java路径_Linux环境中查看java的安装路径,设置环境变量
  9. html 二维表_焦虑症自测量表SAS焦虑症自测表
  10. matlab泛函分析,Matlab数字图像处理的学习建议 – MATLAB中文论坛