导出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打印.这样在我们实 ...
随机推荐
- mysql 安装到最后一步时,start service 为失败状态
容易出现的问题:mysql 安装到最后一步时,start service 为失败状态. 解决方法: 方式1 MySQL安装是出现could not start the service mysql ...
- react-native 打包apk
如果你是学习Android的和我一样的话那一定会用一些软件开发,如WebStore 等等 那么这里我就来讲一下在WebStore 开发的App 如何打包成一个手机可以安装的apk软件 1.首先你的Ap ...
- 【Java集合系列】目录
2017-07-29 13:49:40 一.Collection的全局继承关系 二.系列文章 [Java集合系列一]ArrayList解析 备注: 1.ArrayList本质上就是一个数组,所有对外提 ...
- Scrapy爬虫框架中的两个流程
下面对比了Scrapy爬虫框架中的两个流程—— ① Scrapy框架的基本运作流程:② Spider或其子类的几个方法的执行流程. 这两个流程是互相联系的,可对比学习. 1 ● Scrapy框架的基本 ...
- ES6函数的特性(箭头语法)
//ES5中的函数的定义 var fn=function(){ console.log(111); } //ES6中函数的定义 let fn=()=>{ console.log(222); } ...
- java基础知识点学习
基础学习总结 1.锁sync/lock都有哪些方法,底层实现 synchronized ['sɪŋkrənaɪzd] 2.线程池的参数.线程池执行的流程,当到达线程池到达最大数,队列也满了,出现的异常 ...
- Python 进程池的同步方法和异步方法
import time from multiprocessing import Process,Pool def f1(n): time.sleep(0.5) # print(n) return n* ...
- Ubuntu16.04 用Nomachine进行远程控制的配置
本文介绍如何在Ubuntu16.04环境下运用Nomachine进行远程控制. 一. NoMachine介绍 NoMachine是一款基于NX技术进行远程控制的软件,最大的优势是跨平台,简单,可以实现 ...
- pytorch中,不同的kernel对不同的feature map进行卷积之后输出某一个channel对应的多个feature map如何得到一个channel的feature map
实际上在卷积操作的时候,比如说,我某一层输出的feature map的size为4713*13 channel的数目为7,设经过某卷积层之后,网络输出的feature map的channel的数目为1 ...
- 【Java】字符串工具类
import android.annotation.SuppressLint; import java.io.UnsupportedEncodingException; import java.uti ...