首先需要引用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