导出到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. win10 无法使用内置管理员账户打开应用

    运行gpedit.msc 启用两项 如何登陆 win 10 账户? 进入 win 10 应用商店,下载一个软件,然后登陆即可

  2. Don't always upset yourself !

  3. idea docker docker-compose发布springboot站点到tomcat

    允许docker被远程访问 见:https://www.cnblogs.com/wintersoft/p/10921396.html 教程:https://spring.io/guides/gs/sp ...

  4. free中buffer 与 cache 的区别

    通常人们所说的Cache就是指缓存SRAM. SRAM叫静态内存,“静态”指的是当我们将一笔数据写入SRAM后,除非重新写入新数据或关闭电源,否则写入的数据保持不变. 由于CPU的速度比内存和硬盘的速 ...

  5. Android adb临时关闭Selinux

    在eng/userdebug版本中 使用getenforce 命令查询当前权限状态,如:adb shell getenforce 使用setenforce 命令进行设置:adb shell seten ...

  6. C# Newtonsoft.Json解析json字符串处理(最清晰易懂的方法)

    需求: 假设有如下json字符串: { ", "employees": [ { "firstName": "Bill", &quo ...

  7. 几种常见的java网页静态化技术对比

    名称 优点 缺点 使用场景 jsp 1.功能强大,可以写java代码 2.支持jsp标签(jsp tag) 3.支持表达式语言(el) 4.官方标准,用户群广,丰富的第三方jsp标签库 5.性能良好. ...

  8. oracle plsql 异常

      set serveroutput on DECLARE pename emp.ename%type; begin '; exception when no_data_found then dbms ...

  9. Idea控制台中文乱码

    在菜单栏找到”run->editconfigration” 找到”server”选项卡 设置 vm option为 -Dfile.encoding=utf-8

  10. plsql 32位,Oracle Client 64位 无法读取tnsnames.ora文件

    ORACLE_HOME=C:\app\fjz\product\11.2.0\client_1 1)设置windows系统环境变量: TNS_ADMIN=C:\app\fjz\product\11.2. ...