前端:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<link href="easyui/themes/default/easyui.css" rel="stylesheet" />
<link href="easyui/themes/icon.css" rel="stylesheet" />
<script src="easyui/js/jquery.min.js"></script>
<script src="easyui/js/jquery.easyui.min.js"></script>
<script src="easyui/js/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
var datagrid = {
init: function () {
$('#userGrid').datagrid({
toolbar: '',
title: "用户信息",
iconCls: 'icon icon-list',
nowrap: false, //折行
rownumbers: true, //行号
striped: true, //隔行变色
remoteSort: false,//定义从服务器对数据进行排序
idField: 'Id', //主键
//singleSelect: true, //单选
columns: [[
{ field: 'ck', checkbox: true },
{ title: 'Id', field: 'Id', width: 130 },
{ title: 'Name', field: 'Name', width: 80 },
{ title: 'Sex', field: 'Sex', width: 100 },
{
title: 'Email', field: 'Email', width: 100, formatter: function (value) {
return "<a href='www.baidu.com'>"+value+"</a>";
}
},
{ title: 'Remark', field: 'Remark', width: 100 }
]],
onLoadSuccess: function () {
},
pagination: true,
pageNumber: 1,
pageSize: 2,
pageList: [2, 3, 10, 50]
});
},
databind: function () {
$('#userGrid').datagrid({ url: "Handler/UserInfoHandler.ashx?Action=getList" });
}
} $(document).ready(function () {
datagrid.init();
datagrid.databind();
$("#Report1").click(ExportResumeList1)
$("#Report2").click(ExportResumeList2)
$("#Report3").click(ExportResumeList3)
})
function ExportResumeList1() {
$.ajax({
url: "Handler/ReportHelperHandler.ashx?action=export1",
type: "get",
cache: false,
success: function (data) {
alert(data);
window.location.href = "Handler/ReportHelperHandler.ashx?action=ResponseFile&filePath=" + escape(data);
},
error: function (e) {
alert(e);
}
});
}
//导出文件
function ExportResumeList2() {
$("#Export").attr("action", "Handler/ReportHelperHandler.ashx?action=export2");
$("#Export").submit();
}
function ExportResumeList3() {
$("#Export").attr("action", "Handler/ReportHelperHandler.ashx?action=export3");
$("#Export").submit();
}
</script>
</head>
<body>
<button id="Report1">Excle导出1</button>
<button id="Report2">Excle导出2</button>
<button id="Report3">Excle导出3</button>
<table id="userGrid" style="width:400px; height:200px;"></table>
<form style="display: none; width: 0px; height: 0px;" id="Export" method="post" action=""></form>
</body>
</html>

  后端:

using Common;
using DBUtility;
using Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web; namespace ReportTool
{
/// <summary>
/// ReportHelperHandler 的摘要说明
/// </summary>
public class ReportHelperHandler : IHttpHandler
{ public DataProvider dataprovider = new DataProvider();
public ReportHelperHandler()
{
dataprovider.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
} public void ProcessRequest(HttpContext context)
{
try
{
context.Response.ContentType = "text/plain";
string action = context.Request["Action"];
switch (action)
{ case "export1":
export1(context);
break;
case "ResponseFile":
//ResponseFile(context.Request["filePath"]);
ResponseFile1(context);
break;
case "export2":
export2(context);
//responeResult(filepath,context);
break;
case "export3":
export3(context);
//responeResult(filepath,context);
break;
} }
catch (Exception e)
{ throw e;
}
} private void export1(HttpContext context)
{
try
{
var result = configEnum.mergeRow.ToString();
//string BaseTemplateFolder = HttpContext.Current.Server.MapPath("~/Template");
string BaseTemplateFolder = AppDomain.CurrentDomain.BaseDirectory+ "Template";
string templateFile = Path.Combine(BaseTemplateFolder, "端午假期网络和信息系统运行值班表(汇总).xlsx");
ExcelHelper excelHelper = new ExcelHelper(templateFile);
DataTable configDt = excelHelper.ExcelToDataTable(templateFile, true);
var list = DataTableHelper.ConvertTo<ConfigModel>(configDt);
DataTable dt = new DataTable();
string strSql = string.Empty;
foreach (var item in list)
{
if (item.key == "cols" && item.type == "sql")
{
strSql = item.value;
}
}
dt = dataprovider.FillDataTable(strSql, CommandType.Text);
string sDirFileName = setDataToTemplate(dt, (List<ConfigModel>)list, context);
System.IO.File.WriteAllText(HttpContext.Current.Server.MapPath("~/") + "log.txt", "export1"+sDirFileName);
//返回导出文件的路径
//ResponseFile(sDirFileName);
context.Response.Write(sDirFileName);
}
catch (Exception e)
{
throw e;
} }
private void ResponseFile1(HttpContext context)
{
try
{ FileStream fs = new FileStream(context.Request["filePath"], FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(context.Request["filePath"]), System.Text.Encoding.UTF8));
context.Response.BinaryWrite(bytes);
context.Response.Flush();
//context.Response.End();
context.ApplicationInstance.CompleteRequest();
}
catch (Exception e)
{ throw e;
}
} private void export2(HttpContext context)
{
try
{
var result = configEnum.mergeRow.ToString();
//string BaseTemplateFolder = context.Server.MapPath("~/Template");
string BaseTemplateFolder = AppDomain.CurrentDomain.BaseDirectory + "Template";
string templateFile = Path.Combine(BaseTemplateFolder, "端午假期网络和信息系统运行值班表(汇总).xlsx");
ExcelHelper excelHelper = new ExcelHelper(templateFile);
DataTable configDt = excelHelper.ExcelToDataTable(templateFile, true);
var list = DataTableHelper.ConvertTo<ConfigModel>(configDt);
DataTable dt = new DataTable();
string strSql = string.Empty;
foreach (var item in list)
{
if (item.key == "cols" && item.type == "sql")
{
strSql = item.value;
}
}
dt = dataprovider.FillDataTable(strSql, CommandType.Text);
string sDirFileName = setDataToTemplate(dt, (List<ConfigModel>)list, context);
System.IO.File.WriteAllText(context.Server.MapPath("~/") + "log.txt", "export2"+sDirFileName);
//返回导出文件的路径
//ResponseFile(sDirFileName,context);
//return sDirFileName;
responeResult2(sDirFileName, context);
}
catch (Exception e)
{
throw e;
} }
private void responeResult2(string filepath, HttpContext context)
{
FileStream fs1 = new FileStream(filepath, FileMode.Open);
byte[] bytes1 = new byte[(int)fs1.Length];
fs1.Read(bytes1, 0, bytes1.Length);
fs1.Close();
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Path.GetFileName(filepath), System.Text.Encoding.UTF8));
context.Response.BinaryWrite(bytes1);
context.Response.Flush();
//context.Response.End();
context.ApplicationInstance.CompleteRequest();
} private void export3(HttpContext context)
{
try
{
var result = configEnum.mergeRow.ToString();
string BaseTemplateFolder = context.Server.MapPath("~/Template");
string templateFile = Path.Combine(BaseTemplateFolder, "端午假期网络和信息系统运行值班表(汇总).xlsx");
ExcelHelper excelHelper = new ExcelHelper(templateFile);
DataTable configDt = excelHelper.ExcelToDataTable(templateFile, true);
var list = DataTableHelper.ConvertTo<ConfigModel>(configDt);
DataTable dt = new DataTable();
string strSql = string.Empty;
foreach (var item in list)
{
if (item.key == "cols" && item.type == "sql")
{
strSql = item.value;
}
}
dt = dataprovider.FillDataTable(strSql, CommandType.Text);
string sDirFileName = setDataToTemplate(dt, (List<ConfigModel>)list, context);
System.IO.File.WriteAllText(context.Server.MapPath("~/") + "log.txt", "export13"+sDirFileName);
//返回导出文件的路径
//ResponseFile(sDirFileName,context);
//return sDirFileName;
responeResult3(sDirFileName, context);
}
catch (Exception e)
{
throw e;
} }
private void responeResult3(string filepath, HttpContext context)
{
FileInfo file = new FileInfo(filepath);//创建一个文件对象
context.Response.Clear();//清除所有缓存区的内容
context.Response.Charset = "GB2312";//定义输出字符集
context.Response.ContentEncoding = Encoding.Default;//输出内容的编码为默认编码
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + file.Name);
//添加头信息。为“文件下载/另存为”指定默认文件名称
context.Response.AddHeader("Content-Length", file.Length.ToString());
//添加头文件,指定文件的大小,让浏览器显示文件下载的速度
context.Response.WriteFile(file.FullName);// 把文件流发送到客户端
context.Response.End();
//context.ApplicationInstance.CompleteRequest();
}
/// <summary>
/// 将数据设置到模板中
/// </summary>
public string setDataToTemplate(DataTable dt)
{
string tmpFilePath = string.Empty;
string BaseTmpFolder = AppDomain.CurrentDomain.BaseDirectory + "Export\\";
string BaseTemplateFolder = AppDomain.CurrentDomain.BaseDirectory + "Template\\"; foreach (string fileInfo in Directory.GetFiles(BaseTmpFolder))
{
File.Delete(fileInfo);
}
string templateFile = BaseTemplateFolder + "端午假期网络和信息系统运行值班表(汇总).xlsx";
string tmpFile = string.Format("{0}{1}年{2}", BaseTmpFolder, DateTime.Now.ToString("yyyy"), "端午假期网络和信息系统运行值班表(汇总).xlsx");
File.Copy(templateFile, tmpFile);
ExcelHelper excelHelper = new ExcelHelper(tmpFile);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
excelHelper.DataSetToExcel(ds, 3, 0, 0); return tmpFile; }
public string setDataToTemplate(DataTable dt, List<ConfigModel> Listconfig, HttpContext context)
{
string tmpFilePath = string.Empty;
string BaseTmpFolder = context.Server.MapPath("~/Export");
string BaseTemplateFolder = context.Server.MapPath("~/Template"); foreach (string fileInfo in Directory.GetFiles(BaseTmpFolder))
{
File.Delete(fileInfo);
}
string templateFile = Path.Combine(BaseTemplateFolder, "端午假期网络和信息系统运行值班表(汇总).xlsx");
string tmpFile = string.Format("{0}\\{1}年{2}", BaseTmpFolder, DateTime.Now.ToString("yyyy"), "端午假期网络和信息系统运行值班表(汇总).xlsx");
File.Copy(templateFile, tmpFile);
ExcelHelper excelHelper = new ExcelHelper(tmpFile);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
excelHelper.DataSetToExcel(ds, 3, 0, 0, Listconfig); return tmpFile; }
public bool IsReusable
{
get
{
return false;
}
}
}
}

  注意:

临时文件夹读写权限设置:1.自己设置

2.通过代码控制

//给Excel文件添加"Everyone,Users"用户组的完全控制权限
FileInfo fi = new FileInfo(excelPath);
System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
fi.SetAccessControl(fileSecurity); //给Excel文件所在目录添加"Everyone,Users"用户组的完全控制权限
DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(excelPath));
System.Security.AccessControl.DirectorySecurity dirSecurity = di.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
dirSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
di.SetAccessControl(dirSecurity);

  

NPOI导出Excle的更多相关文章

  1. NPOI导出Excel (C#) 踩坑 之--The maximum column width for an individual cell is 255 charaters

    /******************************************************************* * 版权所有: * 类 名 称:ExcelHelper * 作 ...

  2. 基于NPOI导出和导入Excel

    概述 NPOI,顾名思义,就是POI的.NET版本.NPOI就是用.NET语言编写的一套数据导出Excel的开源项目,支持XML.xls.xlsx.ppt等格式..NET不仅实现Excel导出还可以实 ...

  3. (C#)使用NPOI导出Excel

    在做业务型的软件时,经常需要将某些数据导出,本文介绍了在Winform或Asp.net中使用NPOI(POI 项目的 .NET 版本)来操作Excel文件,而无需安装Office. 首先,需要获取NP ...

  4. Asp.Net 使用Npoi导出Excel

    引言 使用Npoi导出Excel 服务器可以不装任何office组件,昨天在做一个导出时用到Npoi导出Excel,而且所导Excel也符合规范,打开时不会有任何文件损坏之类的提示.但是在做导入时还是 ...

  5. C# NPOI导出Excel和EPPlus导出Excel比较

    系统中经常会使用导出Excel的功能. 之前使用的是NPOI,但是导出数据行数多就报内存溢出. 最近看到EPPlus可以用来导出Excel,就自己测了下两者导出上的差异. NPIO官网地址:http: ...

  6. NPOI导出EXCEL 打印设置分页及打印标题

    在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方法,但一直都没有起到作用.经过研究是要设置  sheet1.FitToPage = false; 而 ...

  7. .NET NPOI导出Excel详解

    NPOI,顾名思义,就是POI的.NET版本.那POI又是什么呢?POI是一套用Java写成的库,能够帮助开发者在没有安装微软Office的情况下读写Office的文件. 支持的文件格式包括xls, ...

  8. NPOI导出Excel(含有超过65335的处理情况)

    NPOI导出Excel的网上有很多,正好自己遇到就学习并总结了一下: 首先说明几点: 1.Excel2003及一下:后缀xls,单个sheet最大行数为65335 Excel2007 单个sheet ...

  9. [转]NPOI导出EXCEL 打印设置分页及打印标题

    本文转自:http://www.cnblogs.com/Gyoung/p/4483475.html 在用NPOI导出EXCEL的时候设置分页,在网上有查到用sheet1.SetRowBreak(i)方 ...

随机推荐

  1. Apache Directory Studio

    Apache Directory Studio 是一个 LDAP 的工具平台,用来连接到任何 LDAP 服务器并进行管理和开发工作.主要功能:LDAP浏览器.LDIF编辑器.嵌入式 ApacheDS. ...

  2. 串口通讯编程一日通2(Overlapped IO模型)

    第一篇初步了解串口的大致运作,接下来我们看基本操作 先看串口操作的数据结构: 串口操作有几个比较重要的Struct 1.Overlapped I/O 异步I/O模型 异步I/O和同步I/O不同,同步I ...

  3. 主从复制时报:ERROR 1794 (HY000): Slave is not configured or failed to initialize properly. You must at least set --server-id to enable either a master or a slave. Additional error messages can be found in t

    centos 6.5 mysql5.7 在从库作stop slave时报: error:ERROR 1794 (HY000): Slave is not configured or failed to ...

  4. spring中ApplicationContext

    1 spring 容器应用上下文:ApplicationContext 主要的实现类是 ClassPathXmlApplicationContext 和 FileSystemXmlApplicatio ...

  5. spring概念简介、bean扫描与注册实现方式

    写在前面:本文作为整理,包含很多个人理解,有跳跃成份,初学者如果看晕了,可以先看其它同类文章,或者……多看几遍. 一.概念部分: 1.spring概念:网上有很多 2.spring核心:IOC(DI) ...

  6. Windows下 Qt 资源文件(.qrc)文件 的 编写与应用

    最近遇到一些项目都包含了qrc文件,这个是Qt的资源文件,如果在pro文件中不包含的话,在编译的时候会提示找不到相应资源的错误. 下面说一下手动修改pro和编写qrc文件的方法. 我们直接在命令行下执 ...

  7. Atitit.各种 数据类型 ( 树形结构,表形数据 ) 的结构与存储数据库 attilax 总结

    Atitit.各种  数据类型 ( 树形结构,表形数据  ) 的结构与存储数据库 attilax  总结 1. 数据结构( 树形结构,表形数据,对象结构 ) 1 2. 编程语言中对应的数据结构 jav ...

  8. python 使用urllib.urlopen超时问题的解决方法

    准备写一个python脚本抓取网页数据,前面抓了几个都没有什么问题,但总会抓取不完整,在中间过程中没有反应,发现执行urlopen的地方总是提示超时,百度了一下,因为我使用的是urllib不是urll ...

  9. Codeforces Round #235 (Div. 2) C. Team

    C. Team time limit per test 1 second memory limit per test 256 megabytes input standard input output ...

  10. Spring Oauth2 with JWT Sample

    https://www.javacodegeeks.com/2016/04/spring-oauth2-jwt-sample.html ******************************** ...