导出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; ... 
随机推荐
- Error:gradle-resources-test:thymeleaf-in-action.main: java.lang.NoClassDefFoundError: org/apache/tools/ant/util/ReaderInputStream
			目录 Error:gradle-resources-test:thymeleaf-in-action.main: java.lang.NoClassDefFoundError: org/apache/ ... 
- 树莓派基于scratch2控制GPIO
			本文通过MetaWeblog自动发布,原文及更新链接:https://extendswind.top/posts/technical/raspberry_scratch2_gpio_control.m ... 
- MongoDB 数据库创建删除
			在MongoDB数据库里面是存在有数据库的概念,但是没有模式(所有的信息都是按照文档保存的),保存数据的结构就是JSON结构,只不过在进行一些数据处理的时候才会使用到MongoDB自己的一些操作符号 ... 
- debian10使用国内源安装docker以及一些使用方法
			首先, 我的环境是debian, 容器是centos debian 安装添加新存储库所需的依赖项 1 sudo apt install ca-certificates curl software-pr ... 
- TICK/TIGK运维栈安装运行 docker-compose【下】
			InfluxDB 构建Dockerfilevim /opt/influxdb-docker/Dockerfile FROM influxdb COPY influxdb.conf /etc/influ ... 
- 关于资源获取(请把https改为http)
			所有demo以及资源获取,请把https改为http. 
- C# 获取文件扩展信息-应用名称/作者等
			方案一:使用微乳封装的Shell包 添加nuget包:Microsoft.WindowsAPICodePack.Shell using Microsoft.WindowsAPICodePack.She ... 
- Python之pandas读取mysql中文乱码问题
			# -*- coding: utf-8 -*- # author:baoshan import pandas as pd import pymysql config = { "host&qu ... 
- (转)python3:类方法,静态方法和实例方法以及应用场景
			原文:https://blog.csdn.net/qq_34979346/article/details/83212716 1.实例方法在编程里经常用的是实例方法,直接用实例去调用, 只要 方法里有s ... 
- ingress Whitelisting白名单机制
			Whitelisting To restrict the service in a way that only a list of IPs can access it, modify the ingr ... 
