首先需要引用NPOI的dll文件。
下载地址:https://me.csdn.net/download/laizhixue
HTML代码:
<a id='ExportMyExcel_a' class='k-button' href='' style='display:none;'>图标1</a>
<br/>
<a class='k-button' title='导出相应的Excel' onclick='ExportMyExcel()'>图标2</a>
前台方法:
//laizhixue 2019.06.18
//导出自定义数据的Excel数据
function ExportMyExcel() {
$.ajax({
url: "/Report/CommonReport/ExportMyExcel",
data: {
ProcSetName: $("#sltProcess").data("kendoDropDownList").text(),
StartDate:$("#ProcStartDate").val(),
EndDate: $("#ProcEndDate").val()
},
dataType: "text",
async: false,
success: function (data) {
if (data.indexOf("导出成功!\n若已打开文件,数据则不会覆盖之前已存在的文件!") >= 0) {
var url = data.substring(data.indexOf(":") + 1);
$("#ExportMyExcel_a").attr("href", url);
document.getElementById("ExportMyExcel_a").click();//需JS触发click,JQ触发失败
DeleteFile( $("#ExportMyExcel_a").attr("href"));
} else {
alert(data);
}
}
});
}
//删除文件
function DeleteFile(url) {
$.ajax({
url: "/Report/CommonReport/DeleteFile",
data: {
Url:url
},
dataType: "text",
async: false,
success: function (data) {
if (data == "error") {
alert(data);
}
}
});
}
后台方法:
//laizhixue 2019-06-18
//导出自定义数据的Excel数据
public string ExportMyExcel(string ProcSetName, string StartDate, string EndDate)
{
string conStr = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["aZaaSFramework"].ToString();
var list = new List<List<string>>();
//调用存储过程拉取相应的数据
try
{
//NPOI
string bookpath = Server.MapPath("~\\Content\\");
string bookName = ProcSetName + '-' + StartDate + '-' + EndDate + ".xls";
string filepath = bookpath + bookName;
string str = "";
//SQL
DataSet ds = new DataSet();
SqlConnection con = new SqlConnection(conStr);
con.Open();
SqlCommand command = new SqlCommand("ExportMyExcel", con);
command.CommandType = CommandType.StoredProcedure;//采用存储过程
command.Parameters.Add("@ProcSetName", SqlDbType.NVarChar, 100);//流程名字
command.Parameters["@ProcSetName"].Value = ProcSetName;
command.Parameters.Add("@StartDate", SqlDbType.NVarChar, 100);//开始日期
command.Parameters["@StartDate"].Value = StartDate + " 00:00:00";
command.Parameters.Add("@EndDate", SqlDbType.NVarChar, 100);//结束日期
command.Parameters["@EndDate"].Value = EndDate + " 23:59:59";
command.Parameters.Add("@Status", SqlDbType.TinyInt);//状态
command.Parameters["@Status"].Value = 3;//完成
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
//获取数据条数
if (ds != null && ds.Tables.Count > 0)
{
//创建workbook
HSSFWorkbook book = new HSSFWorkbook();
//创建Sheet1
ISheet sheet = book.CreateSheet("Sheet1");
//表头
IRow headrow = sheet.CreateRow(0);
//添加表头数据
for (var i = 0; i < ds.Tables[0].Columns.Count; i++)
{
ICell headcell = headrow.CreateCell(i);
headcell.SetCellValue(ds.Tables[0].Columns[i].ToString());
sheet.AutoSizeColumn(i);
}
//添加主数据 i行j列
for (var i = 0; i < ds.Tables[0].Rows.Count; i++)
{
//数据
IRow row = sheet.CreateRow(i + 1);
for (var j = 0; j < ds.Tables[0].Columns.Count; j++)
{
ICell cell = row.CreateCell(j);
//状态转中文
if (j == 0)
{
switch (ds.Tables[0].Rows[i][j].ToString())
{
case "3":
cell.SetCellValue("完成");
break;
}
}
else
{
cell.SetCellValue(ds.Tables[0].Rows[i][j].ToString());
}
}
}
//获取当前列的宽度,然后对比本列的长度,取最大值
//自适应宽度
for (int columnNum = 0; columnNum < ds.Tables[0].Columns.Count; columnNum++)
{
int columnWidth = sheet.GetColumnWidth(columnNum) / 256;
for (int rowNum = 0; rowNum < sheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (sheet.GetRow(rowNum) == null)
{
currentRow = sheet.CreateRow(rowNum);
}
else
{
currentRow = sheet.GetRow(rowNum);
}
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
sheet.SetColumnWidth(columnNum, columnWidth * 256);
}
// 写入到服务器,需要下载到本地需要通过前台的超链接
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
book.Write(ms);
using (FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite))
{
byte[] d = ms.ToArray();
fs.Write(d, 0, d.Length);
fs.Flush();
}
book = null;
ds.Dispose();
}
str = "导出成功!\n若已打开文件,数据则不会覆盖之前已存在的文件!路径:/Content/" + bookName;
return str;
}
else
{
return "请检查ExportMyExcel存储过程是否已完善代码!";
}
}
catch
{
return "调用ExportMyExcel存储过程异常!";
}
}
//删除服务器生成的文件
public string DeleteFile(string Url)
{
try
{
FileInfo resFile = new FileInfo(Server.MapPath("~\\" + Url));//服务器的资源文件
if (resFile.Exists)
{
resFile.Delete();
}
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("删除文件异常!");
return "error";
}
return "success";
}
SQL存储过程:
USE [aZaaS.Framework]
GO
/****** Object: StoredProcedure [dbo].[ExportMyExcel] Script Date: 07/02/2019 09:06:39 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
--获取需要导出的相应流程的表格数据
ALTER procedure [dbo].[ExportMyExcel]
@ProcSetName nvarchar(100),--流程名
@StartDate nvarchar(100),--开始日期
@EndDate nvarchar(100),--结束日期
@Status nvarchar(100)--状态
AS
DECLARE @sql NVARCHAR(max)
BEGIN
IF @ProcSetName=N'供应商主档流程'
BEGIN
--自定义导出字段
SELECT
[Before_SupplierNo] as N'供应商编号'
,[NewOrOldSel] as N'SAP系统'
,[Before_SupplierName] as N'供应商名称'
,[Before_VendorClass1] as N'类别代码1'
,[Before_VendorClass2] as N'类别代码2'
,[Before_SearchCondition] as N'搜索条件'
,[Before_Country] as N'国家'
,[Before_Address_1] as N'街道1'
,[Before_Address_2] as N'街道2'
,[Before_Address_3] as N'街道3'
,[Before_PhoneNo_1] as N'电话'
,[Before_FaxNo] as N'传真'
,[Before_E_email] as N'电子信箱'
,[Before_HeadOffice] as N'总部'
,[Before_Currency] as N'订单货币'
,[Before_PaymentRule] as N'前付款条件'
,[Before_Trade1] as N'国贸条件1'
,[Before_Trade2] as N'国贸条件2'
,[Before_Seller] as N'销售员'
,[Before_SellTel] as N'销售电话'
,[Before_Remarks] as N'备注'
FROM 表名
END