导出Excel的2个方法
导出到Excel的两种方法
第一种:
1、首先创建Excle模板,另存为 “xml”文件。使用记事本等编辑软件打开文件的代码。然后另存为视图文件“Export.cshtml”;
2、控制器操作
public ActionResult Export()
{
#region Excel下载设置
Response.Clear();
Response.ClearContent();
Response.Buffer = true;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "application/ms-excel";
string downloadFileName = "文件名" + ".xls";
if (Request.UserAgent != null && Request.UserAgent.ToLower().IndexOf("msie", System.StringComparison.CurrentCultureIgnoreCase) > -)
{
downloadFileName = HttpUtility.UrlPathEncode(downloadFileName);
}
if (Request.UserAgent != null && Request.UserAgent.ToLower().IndexOf("firefox", System.StringComparison.CurrentCultureIgnoreCase) > -)
{
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
}
else
Response.AddHeader("Content-Disposition", "attachment;filename=" + downloadFileName); #endregion
return View();
}
3、添加一个页面,用来点击导出按钮,触发导出事件
<a type="button" class="btn btn-orange" data-icon='file-excel-o' href="javascript:" onclick="ConfirmAndExport('@(Url.Action("Export"))', '您确定要导出吗?')" >导出</a>
4、jquery:
function ConfirmAndExport(url, msg) {
$(this).alertmsg('confirm',msg, {
okCall: function () {
var data = $("#pagerForm", $.CurrentNavtab).serialize();
var inputs = '';
jQuery.each(data.split('&'), function () {
var pair = this.split('=');
inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
});
jQuery('<form action="' + url + '" method="post">' + inputs + '</form>').appendTo('body').submit().remove();
}
});
return false;
}
function ConfirmAndExport(url) {
alertMsg.confirm("确定要导出当前数据吗?", {
okCall: function () {
var data = $("#pagerForm", navTab.getCurrentPanel()).serialize();
var inputs = '';
jQuery.each(data.split('&'), function () {
var pair = this.split('=');
inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
});
jQuery('<form action="' + url + '" method="post">' + inputs + '</form>').appendTo('body').submit().remove();
}
});
return false;
}
第二种、使用npoi
页面代码很简单
就是一个触发下载的按钮
js代码也同上
点击按钮,触发js,跳转到控制器。
然后在控制器里调用要给公共方法,如下:
创建一个公共方法供以后使用:
/// <summary>
/// Excel导出
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public static string Export(DataTable dt)
{
try
{
IWorkbook workbook = new XSSFWorkbook();
ISheet sheet1 = workbook.CreateSheet("导出记录");
int cellCount = dt.Columns.Count;//列数 IRow rowHead = sheet1.CreateRow(); //创建表头
//绑定字体样式到表头
IFont headfont = workbook.CreateFont();
headfont.FontName = "黑体";
headfont.Color = HSSFColor.Black.Index;
headfont.FontHeightInPoints = ; //绑定字体到样式上
ICellStyle Headstyle = workbook.CreateCellStyle();
Headstyle.VerticalAlignment = VerticalAlignment.Center; //垂直居中
Headstyle.Alignment = HorizontalAlignment.Center; //横向居中 Headstyle.SetFont(headfont);
//边框颜色
Headstyle.BorderBottom = BorderStyle.Thin;
Headstyle.BottomBorderColor = HSSFColor.Grey40Percent.Index;
Headstyle.BorderLeft = BorderStyle.Thin;
Headstyle.LeftBorderColor = HSSFColor.Grey40Percent.Index;
Headstyle.BorderRight = BorderStyle.Thin;
Headstyle.RightBorderColor = HSSFColor.Grey40Percent.Index;
Headstyle.BorderTop = BorderStyle.Thin;
Headstyle.TopBorderColor = HSSFColor.Grey40Percent.Index;
//创建表头列
for (int j = ; j < cellCount; j++)
{
ICell cell = rowHead.CreateCell(j);
string[] arr = dt.Columns[j].ColumnName.Split('_');
cell.SetCellValue(arr[]);
cell.CellStyle = Headstyle;
if (arr.Length > )
{
sheet1.SetColumnWidth(j, Utils.StrToInt(arr[], ) * );
}
else
{
sheet1.SetColumnWidth(j, * );
}
}
rowHead.Height = * ; //填充内容
//绑定字体样式到表格内容
IFont font = workbook.CreateFont(); //字体样式
font.FontName = "黑体";
font.Color = HSSFColor.Black.Index;
font.FontHeightInPoints = ;
ICellStyle style = workbook.CreateCellStyle();
style.SetFont(font);
style.WrapText = true;//设置换行这个要先设置
//垂直居中
style.VerticalAlignment = VerticalAlignment.Center;
style.Alignment = HorizontalAlignment.Center;
//边框样式
style.BorderBottom = BorderStyle.Thin;
style.BottomBorderColor = HSSFColor.Grey40Percent.Index;
style.BorderLeft = BorderStyle.Thin;
style.LeftBorderColor = HSSFColor.Grey40Percent.Index;
style.BorderRight = BorderStyle.Thin;
style.RightBorderColor = HSSFColor.Grey40Percent.Index;
style.BorderTop = BorderStyle.Thin;
style.TopBorderColor = HSSFColor.Grey40Percent.Index; for (int i = ; i < dt.Rows.Count; i++)
{
IRow row = sheet1.CreateRow((i + ));
for (int j = ; j < cellCount; j++)
{
ICell cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
cell.CellStyle = style;
}
row.Height = * ;
} string path = Path.Combine("~/Uploads/" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "/");
if (!Directory.Exists(HttpContext.Current.Server.MapPath(path)))
{
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(path));
}
string fileName = Guid.NewGuid().ToString() + ".xlsx";
var fullPath = path + fileName;
FileStream sw = File.Create(HttpContext.Current.Server.MapPath(fullPath));
workbook.Write(sw);
sw.Close();
return fullPath;
}
catch (Exception ex)
{
throw ex;
return ex.Message;
}
} 返回下载文件的地址。 那我们如何将List集合转换为DataTable呢?
接着往下看:
public static DataTable List2DataTable<T>(IEnumerable<T> array)
{
var dt = new DataTable();
//创建表头
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
dt.Columns.Add(dp.Name, dp.PropertyType);
foreach (T item in array)
{
var Row = dt.NewRow();
foreach (PropertyDescriptor dp in TypeDescriptor.GetProperties(typeof(T)))
Row[dp.Name] = dp.GetValue(item);
dt.Rows.Add(Row);
} return dt;
} string MapProperty<T>(T t)
{
var name=new StringBuilder();
var value = new StringBuilder();
PropertyInfo[] propertyInfos = t.GetType().GetProperties(); if(propertyInfos.Length>)
{
foreach(var info in propertyInfos)
{
name.Append(info.Name);
name.Append(" = ");
name.Append(info.GetValue(t)+"\t");
name.Append(info.PropertyType +"\n");
}
}
return name.ToString();
}
导出Excel的2个方法的更多相关文章
- DataGird导出EXCEL的几个方法
DataGird导出EXCEL的几个方法(WebControl) using System;using System.Data;using System.Text;using System.Web;u ...
- 传参导出Excel表乱码问题解决方法
业务场景 先描述一下业务场景,要实现的功能是通过搜索框填写参数,然后点击按钮搜索数据,将搜索框的查询参数获取,附加在链接后面,调导Excel表接口,然后实现导出Excel功能.其实做导Excel表功能 ...
- .NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...
- [转帖].NET导出Excel的四种方法及评测
.NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...
- Asp.net导出Excel(HTML输出方法)
主要思路: 实例化Gridview,将值绑定后输出...(用烂了的方法) 贴上核心代码: public static void ExportToExcel(DataTable dataList, st ...
- Asp.net导出Excel乱码的解决方法
通过跟踪Asp.net服务器代码,没有乱码,然而导出Excel到浏览器后,打开时出现乱码. 解决方法是添加编码格式的前缀字节码:Response.BinaryWrite(System.Text.Enc ...
- POI导出Excel文档通用工具方法
import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; imp ...
- net npoi将List<实体>导出excel的最简单方法
只是临时导数据用的.方便.最基本的方法, [HttpGet] [Route("ExportEnterprise")] public BaseResponse ExportEnter ...
- asp.net 导出excel的一种方法
项目用到的一种导出excel 的方法予以记录:(具体的业务类可更具情况替换使用) protected void Export(string filename, List<ComponentCon ...
- html table表格导出excel的方法 html5 table导出Excel HTML用JS导出Excel的五种方法 html中table导出Excel 前端开发 将table内容导出到excel HTML table导出到Excel中的解决办法 js实现table导出Excel,保留table样式
先上代码 <script type="text/javascript" language="javascript"> var idTmr; ...
随机推荐
- 缺陷的优先程度(Priority)
测试人员希望程序员什么时间哪个版本修改该bug (1)Urgent 立即修改否则影响开发进度 (2)Veryhigh 本版本修改 (3)High 下个版本修改 (4)Medium 发布前修改 (5)L ...
- Cannot read property '_withTask' of undefined
前言 Cannot read property '_withTask' of undefined 突然一下子,就报这个错了,刚刚还好好呢 Bug分析 1.是在template中调用了某个方法,但是你没 ...
- Netty集成Protobuf
一.创建Personproto.proto 创建Personproto.proto文件 syntax = "proto2"; package com.example.protobu ...
- InvalidSelectorError: Compound class names not permitted报错处理
InvalidSelectorError: Compound class names not permitted报错处理 环境:python3.6 + selenium 3.11 + chromed ...
- POST请求BODY格式区别
在PostMan中用Post方式,Body有form-data,x-www-form-urlencoded,raw,binary四种. Request Header示例:POST /upload.do ...
- CNeo编程语言概述
C语言诞生于1970年,当时在AT&T实验室由Dennis Ritchie主导开发的.据说当时仅用了一周的时间就做好了C语言编译器,所以尽管C语言从90年正式纳入ISO标准委员会,其编号为IS ...
- Jmeter多业务混合场景如何设置各业务所占并发比例
在进行多业务混合场景测试中,需要分配每个场景占比. 具体有两种方式: 1.多线程组方式: 2.逻辑控制器控制: 第一种: jmeter一个测试计划可以添加多个线程组,我们把不同的业务放在不同的线程组中 ...
- 上传base64图片并压缩
elementUI+react 布局 <Dialog title="充值" visible={ dialogVisible } onCancel={ () => thi ...
- Python的传递引用
在研究神经网络的反向传播的时候,不解一点,就是修改的是神经网络的paramets,为什么影响内部的神经元(层),比如Affine层:因为除了创建的时候,使用params作为Affine层的构造函数参数 ...
- python自动化测试之连接几组测试包实例
python自动化测试之连接几组测试包实例 本文实例讲述了python自动化测试之连接几组测试包的方法,分享给大家供大家参考.具体方法如下: 具体代码如下: class RomanNumera ...