导出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; ...
随机推荐
- 错误: 找不到或无法加载主类 Welcome.java
问题原因: 不需要带.java
- python 获取 一个正整数的二进制
#coding=utf- def getbin(a): out = "" # 辗转相除法 ): div = a mod = a % out += str(mod) ): break ...
- 把pdf的内容转化为txt文件
import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.util.PDFTextStripper; import j ...
- CTF SSRF(服务器端伪造请求)
目录 CTF SSRF(服务器端伪造请求) 一.概念 二.危害 三.漏洞挖掘与判断 四.相关函数 五.IP绕过 六.Gopher协议 1.使用限制 2.构造payload CTF SSRF(服务器端伪 ...
- 关于证书如何完成身份验证(SSL证书)
一.写在前面 SSL和IPsec是现在VPN技术中最为常见的,在云计算的应用环境中,SSL更受企业青睐,至于原因的话简单的说就是SSL更为简洁,不需要像IPsec那样需要额外安装客户端,这会带来软件维 ...
- @Conditional 和 @ConditionalOnProperty
@ConditionalOnProperty https://blog.csdn.net/dalangzhonghangxing/article/details/78420057 @Condition ...
- Service Fabric独立集群搭建
开篇声明:巨坑,慎入.若实则无奈,建议直接上azure... 1. 开启服务器自动更新,安装最新的补丁. 2. 下载用于 Windows Server 的 Service Fabric 包(htt ...
- Delphi内存专题
第一课: Windows 是多任务的操作系统, 一个任务就是一个应用(应用程序).一个应用占一个进程; 在一个进程里面, 又可以运行多个线程(所以就有了很多"多线程编程"的话题). ...
- mysql用户添加执行存储过程权限
- 使用nodejs+http(s)+events+cheerio+iconv-lite爬取2717网站图片数据到本地文件夹
源代码如下: //(node:9240) Warning: Setting the NODE_TLS_REJECT_UNAUTHORIZED environment variable to '0' ...