导出到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个方法的更多相关文章

  1. DataGird导出EXCEL的几个方法

    DataGird导出EXCEL的几个方法(WebControl) using System;using System.Data;using System.Text;using System.Web;u ...

  2. 传参导出Excel表乱码问题解决方法

    业务场景 先描述一下业务场景,要实现的功能是通过搜索框填写参数,然后点击按钮搜索数据,将搜索框的查询参数获取,附加在链接后面,调导Excel表接口,然后实现导出Excel功能.其实做导Excel表功能 ...

  3. .NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 导出Excel是.NET的常见需求,开源社区.市场上,都提供了不少各式各样的Excel操作相关包.本文,我将使用NPOI.EPPlus.OpenXML.Aspo ...

  4. [转帖].NET导出Excel的四种方法及评测

    .NET导出Excel的四种方法及评测 https://www.cnblogs.com/sdflysha/p/20190824-dotnet-excel-compare.html 导出Excel是.N ...

  5. Asp.net导出Excel(HTML输出方法)

    主要思路: 实例化Gridview,将值绑定后输出...(用烂了的方法) 贴上核心代码: public static void ExportToExcel(DataTable dataList, st ...

  6. Asp.net导出Excel乱码的解决方法

    通过跟踪Asp.net服务器代码,没有乱码,然而导出Excel到浏览器后,打开时出现乱码. 解决方法是添加编码格式的前缀字节码:Response.BinaryWrite(System.Text.Enc ...

  7. POI导出Excel文档通用工具方法

    import java.lang.reflect.InvocationTargetException; import java.util.List; import java.util.Map; imp ...

  8. net npoi将List<实体>导出excel的最简单方法

    只是临时导数据用的.方便.最基本的方法, [HttpGet] [Route("ExportEnterprise")] public BaseResponse ExportEnter ...

  9. asp.net 导出excel的一种方法

    项目用到的一种导出excel 的方法予以记录:(具体的业务类可更具情况替换使用) protected void Export(string filename, List<ComponentCon ...

  10. 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; ...

随机推荐

  1. GitHub 远程仓库 de 第一次配置

    GitHub远程仓库, Git是分布式版本控制系统,同一个Git仓库,可以分布到不同的机器上.首先找一台电脑充当服务器的角色, 每天24小时开机,其他每个人都从这个“服务器”仓库克隆一份到自己的电脑上 ...

  2. 微信小程序之如何定义页面标题

    效果图: 这个标题是在哪里定义的呢?type.js核心代码如下(通常这段代码放在onLoad函数体内): wx.setNavigationBarTitle({ title: "支出类型列表& ...

  3. 正向代理 & 反向代理 & 透明代理

    正向代理(Forward Proxy) 概述 一般情况下,如果没有特别说明,代理技术默认说的是正向代理技术.关于正向代理的概念如下: 正 向代理(forward)是一个位于客户端[用户A]和原始服务器 ...

  4. 第05组Alpha冲刺(1/4)

    队名:天码行空 组长博客连接 作业博客连接 团队燃尽图(共享): GitHub当日代码/文档签入记录展示(共享): 组员情况: 组员1:卢欢(组长) 过去两天完成了哪些任务:SVN管理工具搭建 展示G ...

  5. mysql 面试题 查询出表中某字段的重复值

    users 表中有 两个字段  id 和 name 表数据大概如下: id       name 1       AAA 2       BBB 3       CCC 4       AAA 请写查 ...

  6. Error:(23, 0) Could not find method implementation() for arguments [directory 'libs'] on object of t

    Error:(28, 0) Could not find method implementation() for arguments [com.android.support:appcompat-v7 ...

  7. 使用create-react-app遇到问题解决方案汇总

    使用create-react-app时遇到Module not found问题 转 https://blog.csdn.net/wkq_1212/article/details/90291558 本来 ...

  8. index row size 2720 exceeds maximum 2712 for index "xxx" ,Values larger than 1/3 of a buffer page cannot be indexed.

    记录一个bug情况: 我有个表NewTable,复合主键(slaveid,resid,owner) CREATE TABLE "public"."NewTable&quo ...

  9. git pull push 所有分支

    因为远端 git 服务器上有很多分支,一个个分支pull太麻烦,所以找了 pull 所有分支的方法,如下: git branch -r | grep -v '\->' | while read ...

  10. Python3基础 tuple(list) 改变list元素的内容时,元组的id值不变

             Python : 3.7.3          OS : Ubuntu 18.04.2 LTS         IDE : pycharm-community-2019.1.3    ...