导出Excel实现 (ASP.NET C# 代码部分)
背景: 实现导出Excel功能.
技术: ASP.NET , 采用`Aspose.Cells`第三方组件, C# 实现通用部分.
根据前台Ext Grid完成导入Excel中文列与实际存储列的对应关系. 组织完 Workbook 组织, 保存到Server临时目录, 返回地址下载, 每次都为新故文件名 采用了 随机数:
//_reportName :Excel名称
//_reportName: 报表名称
//_headerStruct: 包含数据库列与Excel中文列的对应关系. (此处取Ext表头) public string ExportServerExcelFile(Aspose.Cells.Workbook w, string fileName)
{
if (!Directory.Exists(Server.MapPath("~/ExportFile/")))
Directory.CreateDirectory(Server.MapPath("~/ExportFile/")); w.Save(Server.MapPath("~/ExportFile/") + fileName); return "http://" + Request.Url.Host + ":" + Request.Url.Port + "/ExportFile/" + fileName;
} public string ExportExcelAll(string queryP, string _reportName, string _headerStruct)
{
DataTable dt = ....; //取查到库中数据
string jsonData = Ext.Net.JSON.Serialize(dt); Workbook w = this.CreateWorkbook(jsonData, _reportName, _headerStruct);
string fileName = _reportName.Split('(')[0] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx"; return this.ExportServerExcelFile(w, fileName);
} public Workbook CreateWorkbook(string jsonData, string _reportName, string _headerStruct)
{
var w = new Workbook(); Worksheet ws = (Worksheet)w.Worksheets[0];
if (!string.IsNullOrEmpty(_headerStruct))
SerHeader1(JSON.Deserialize<dynamic[]>(_headerStruct), ws);
RangeHeader(ws);
//设置标题
ws.Cells[0, 0].PutValue(_reportName);
Range titleRange = ws.Cells.CreateRange(0, 0, 1, lastColIndex); #region ===样式
var style = new Style { HorizontalAlignment = TextAlignmentType.Center, Font = { Size = 25, IsBold = true } };
style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
var styleFlag = new StyleFlag
{
HorizontalAlignment = true,
VerticalAlignment = true,
Font = true,
FontSize = true,
FontBold = true,
Borders = true
};
titleRange.ApplyStyle(style, styleFlag);
titleRange.RowHeight = 26;
titleRange.Merge(); var cellStyle1 = new Style();
cellStyle1.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
cellStyle1.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
cellStyle1.IsTextWrapped = true; var cellStyleNumber = new Style();
cellStyleNumber.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
cellStyleNumber.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
cellStyleNumber.Number = 2;
#endregion //列集合
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
List<grid> _Test = serializer.Deserialize<List<grid>>(_headerStruct); var companies = JSON.Deserialize<Dictionary<string, string>[]>(jsonData); for (int i = 0; i < companies.Length; i++)
{
int tmpColIndex = 0;
foreach (var item in companies[i])
{
if (headerNames.IndexOf(item.Key) > -1)
{
var list = _Test.Where(p => p.DataIndex == item.Key).ToList(); //获取列名称
var cColumn = list[0]; //初始样式
ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].SetStyle(cellStyle1, true); if (cColumn.DataType == "float" || cColumn.DataType == "decimal") //1. 数字类型
{
if (IsDecimal(item.Value))
{
ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(ToDouble(item.Value));//金额保留2位数
//ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].SetStyle(cellStyleNumber);
}
}
else if (cColumn.DataType == "date") //2. 日期类型
{
ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(
(string.IsNullOrWhiteSpace(item.Value) ? "" : Convert.ToDateTime(item.Value).ToString("yyyy-MM-dd hh:mm:ss"))
);
}
else //3. 字符串和集合类型auto
{
ws.Cells[lastLevel + 1 + i, headerNames.IndexOf(item.Key)].PutValue(item.Value);
} //★获得要隐藏的列
if (cColumn.Hiden == true)//列需要隐藏: 字典类型
{
var index = headerNames.IndexOf(item.Key);//列索引
ws.Cells.HideColumn(index);
}
}
tmpColIndex++;
}
} return w;
}
private void RangeHeader(Worksheet ws)
{
for (int row = 1; row <= lastLevel; row++)
{
for (int col = 0; col < lastColIndex; col++)
{
var style = new Style
{
HorizontalAlignment = TextAlignmentType.Center,
VerticalAlignment = TextAlignmentType.Center
};
style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
var styleFlag = new StyleFlag
{
HorizontalAlignment = true,
VerticalAlignment = true,
Font = true,
FontSize = true,
FontBold = true,
Borders = true
}; ws.Cells[row, col].SetStyle(style);
if (ws.Cells[row, col].Value != null)
{
RangeCell(ws, row, col);
}
}
}
foreach (Range item in rc.Where(m => m != null))
{
var style = new Style
{
HorizontalAlignment = TextAlignmentType.Center,
VerticalAlignment = TextAlignmentType.Center
};
style.Borders.SetStyle(Aspose.Cells.CellBorderType.Thin);
style.Borders.DiagonalStyle = Aspose.Cells.CellBorderType.None;
var styleFlag = new StyleFlag
{
HorizontalAlignment = true,
VerticalAlignment = true,
Font = true,
FontSize = true,
FontBold = true,
Borders = true
}; item.ApplyStyle(style, styleFlag);
try
{
item.Merge();
}
catch (Exception)
{
}
}
}
/// <summary>
/// grid表头
/// </summary>
[Serializable]
public class grid
{
public string Text { get; set; }
public string DataIndex { get; set; }
public string Width { get; set; }
public List<grid> Cols { get; set; }
public bool Hiden { get; set; }
public string xtype { get; set; }
public string DataType { get; set; }//列类型
}
其中, 传入
_headerStruct
参数格式截图所示, 包括grid 类用于反序列化, 类似于, 关键用到了Text, DataType, DataIndex 关键, 特殊处理了Ext的多表头, 例如Cols 非末级就忽略了(函数
RangeHeader的作用
):
导出Excel实现 (ASP.NET C# 代码部分)的更多相关文章
- vue项目中导出Excel文件功能的前端代码实现
在项目中遇到了两种不同情况, 1.get请求导出文件,实现起来相对简单 // 导出数据 exportData() { window.location.href = `/oes-content-mana ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- [转]Java中导入、导出Excel
原文地址:http://blog.csdn.net/jerehedu/article/details/45195359 一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样 ...
- easyui datagrid导出excel
[第十四篇]easyui datagrid导出excel <a class="btn btn-app" onclick="exportExcel()" ...
- Java中导入、导出Excel
原文:Java中导入.导出Excel 一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已 ...
- Java中使用poi导入、导出Excel
一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际 ...
- Npoi导出excel整理(附源码)
前些日子做了一个简单的winform程序,需要导出的功能,刚开始省事直接使用微软的组件,但是导出之后发现效率极其低下,绝对像web那样使用npoi组件,因此简单的进行了整理,包括直接根据DataTab ...
- 【转载】Java导入导出excel
转自:https://blog.csdn.net/jerehedu/article/details/45195359 目前,比较常用的实现Java导入.导出Excel的技术有两种Jakarta POI ...
- Java中导入导出Excel -- POI技术
一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实 ...
随机推荐
- ceph crush的问题
ceph crush的问题看一遍忘一遍,现将<ceph源码分析>一书中相关章节摘抄如下: 4.2.1 层级化的Cluster Map例4-1 Cluster Map定义层级化的Cluste ...
- 关于规范NOIP试题管理办法的通知
由CCF主办的NOIP赛事举行在即,保密起见,现将有关规定发给各省赛区组织单位. 1.NOI各省组织单位负责试题保密工作. 2.NOIP初赛试卷为纸质版,复赛试卷为电子版. 3.在初赛进行中,如有选手 ...
- DOM获取元素的方法
DOM:document object module 文档对象模型 DOM就是描述整个html页面中节点关系的图谱,如下图. 1,通过ID,获取页面中元素的方法:(上下文必须是document) do ...
- springboot+thymeleaf+springbootJPA实现一个简单的增删改查
1.springboot是什么,给我们带来了什么方便? 通过阅读springboot的书籍发现springboot最便利的是为我们自动配置了很多的东西,几乎可以实现无xml,甚至简单的无sql,为我们 ...
- C#磁性窗体设计
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using Sy ...
- componentWillMount和componentDidMount的区别
1.componentWillMount 将要装载,在render之前调用: componentDidMount,(装载完成),在render之后调用 2.componentWillMount 每 ...
- python爬虫解析页面数据的三种方式
re模块 re.S表示匹配单行 re.M表示匹配多行 使用re模块提取图片url,下载所有糗事百科中的图片 普通版 import requests import re import os if not ...
- hdu 1754 I Hate It (单点修改+区间最值+裸题)
Time Limit: 9000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Submission(s) ...
- CodeForces - 444C
F - DZY Loves Colors DZY loves colors, and he enjoys painting. On a colorful day, DZY gets a colorfu ...
- 前后端如何保持长连接?---websocket
1. pc端的应用,一般会采用前端定时请求后台; 2. app定时去访问后台的话,对用户来说并不友好,会消耗大量的流量,移动端最好的方式就是后台主动向app推送信息; 3. H5提供了一种比较好的方式 ...