ASP.NET mvc導出Excel文件


首先要下載 NPOI.dll 引用到項目中

 

 

第一步。

 

 

第二步控制台(業務邏輯層)

public ActionResult Export(string CustomerName="",int SumbitUser=0,string Level="",DateTime? StartDate=null, DateTime? EndDate =null,int Industry=0,string CustomerCode="",int PageIndex=0,int PageSize=0)

{

try

{

///下面是添加表的標題

DataTable dtSouce = new DataTable();

//客戶基本信息

dtSouce.Columns.Add("客戶名稱");

dtSouce.Columns.Add("客戶代碼");

dtSouce.Columns.Add("客戶等級");

dtSouce.Columns.Add("所屬行業");

dtSouce.Columns.Add("上一年產值");

dtSouce.Columns.Add("主要產品類型");

dtSouce.Columns.Add("終端客戶");

dtSouce.Columns.Add("上一年PCB采購額度");

dtSouce.Columns.Add("主要層數分布");

dtSouce.Columns.Add("建議采取措施");

//合作信息

dtSouce.Columns.Add("合作年份");

dtSouce.Columns.Add("采購額度");

dtSouce.Columns.Add("預計采購額度");

dtSouce.Columns.Add("我司報價情況");

dtSouce.Columns.Add("客戶投訴情況");

dtSouce.Columns.Add("目前進展");

dtSouce.Columns.Add("合作風險");

dtSouce.Columns.Add("付款方式");

dtSouce.Columns.Add("回款期");

//競爭對手信息

dtSouce.Columns.Add("競爭對手名稱");

dtSouce.Columns.Add("供貨層數");

dtSouce.Columns.Add("供貨類型");

dtSouce.Columns.Add("采購比例");

dtSouce.Columns.Add("價格信息");

dtSouce.Columns.Add("質量情況");

dtSouce.Columns.Add("服務(關系)情況");

dtSouce.Columns.Add("交貨期情況");

var user = (AuthProvider.CurrentUserInfo)Thread.CurrentPrincipal;

var userModel = BusinessService.SystemManage.UserInfoService.GetSingleUserInfo(user.Identity.Name);//獲取當前用戶信息

var records = BusinessService.CustomerManage.LCustomerService.GetListPage(CustomerName, CustomerCode, Level, Industry, SumbitUser, 0, 0, StartDate, EndDate, PageIndex, PageSize,0, userModel.ID);//得到部分數據

var lPayType = BusinessService.SystemManage.PayTypeService.GetList("");//得到部分數據

if (records != null && records.Count > 0)//下面是表里面的數據賦值

{

foreach (var item in records)

{

var row = dtSouce.NewRow();

//客戶基本信息

row[0] = item.CustomerName;

row[1] = item.CustomerCode;

row[2] = item.Level;

row[3] = "";

var recordModel = new Models.LCustomerRecordsViewModel();

var industry = BusinessService.SystemManage.IndustryInfoService.GetSingle(item.Industry);

if (industry != null)

{

row[3] = industry.Name;

}

row[4] = item.PreYearPValue.ToString();

row[5] = item.MainProductTypes;

row[6] = item.TerminalCustomers;

row[7] = item.PreYearPCBTradeCredit;

row[8] = item.MainLayersDistribution;

row[9] = item.SuggestUseMeasures;

//合作信息

var cooperatorInfo = BusinessService.CustomerManage.LCustomerService.GetLCooperation(item.ID);

if (cooperatorInfo!=null&&cooperatorInfo.Count>0)

{

row[10] = cooperatorInfo.First().CooperationYear;

row[11] = cooperatorInfo.First().TradeCredit.ToString();

row[12] = cooperatorInfo.First().ExpectMyTradeCredit.ToString();

row[13] = cooperatorInfo.First().MyQuotationInfo;

row[14] = cooperatorInfo.First().CustomerComplaintsInfo;

row[15] = cooperatorInfo.First().CurrentProgressInfo;

row[16] = cooperatorInfo.First().CooperationRisk;

if (cooperatorInfo.First().PayType>0)

{

var payType = lPayType.Where(m => m.ID.Equals(cooperatorInfo.First().PayType)).ToList();

if (payType!=null&&payType.Count>0)

{

row[17] = payType.First().Name;

}

}

row[18] = cooperatorInfo.First().PaybackPeriod;

}

//競爭對手信息

var competitorInfo = BusinessService.CustomerManage.LCustomerService.GetLCompetitors(item.ID);

if (competitorInfo!=null&&competitorInfo.Count>0)

{

row[19] = competitorInfo.First().Name;

row[20] = competitorInfo.First().GoodsLayers;

row[21] = competitorInfo.First().GoodsTypes;

row[22] = competitorInfo.First().ProcurementPercent;

row[23] = competitorInfo.First().PriceInfo;

row[24] = competitorInfo.First().QualityInfo;

row[25] = competitorInfo.First().ServiceInfo;

row[26] = competitorInfo.First().DeliveryDateInfo;

}

dtSouce.Rows.Add(row);

 

//var subitUser = BusinessService.SystemManage.UserInfoService.GetSingleUserInfo(item.SumbitUser);

//recordModel.SumbitUser = subitUser.ChinessName;

//if (item.FollowUser != null)

//{

// var followUser = BusinessService.SystemManage.UserInfoService.GetSingleUserInfo((int)item.FollowUser);

// recordModel.FollowUser = followUser.ChinessName;

//}

//else

//{

// recordModel.FollowUser = "暫未指定";

//}

}

}

var wookbook = Helper.ExcelHelper.DataTable2Excel(dtSouce,2, "", Server.MapPath("~/ExcelTemp/潛力客戶信息導入模板.xlsx"));//地址 (引用幫助類)

//ms.Seek(0, SeekOrigin.Begin);

Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", "潛力客戶信息列表" + DateTime.Now.ToString("yyyyMMddHHmmssfff")));//表名

//Response.BinaryWrite(byteData);

wookbook.SaveAs(Response.OutputStream);

//ms.Close();

//ms.Dispose();

 

return Content("");

}

catch (Exception ex)

{

throw ex;

}

}

 

第三步(幫助類)

/// <summary>

/// 將Excel內容轉換為DataTable

/// </summary>

/// <param name="fs">文件流</param>

/// <param name="isFirstRowColumn">標題列</param>

/// <param name="sheetName">工作表名稱,若為空則取第一個工作表</param>

/// <returns></returns>

public static DataTable GetDataFromExcel(Stream fs, int titleIndex, string sheetName)

{

DataTable data = new DataTable();

try

{

ISheet sheet = null;

IWorkbook workbook = null;

int startRow = 0;

workbook = new XSSFWorkbook(fs);

if (workbook == null)

{

workbook = new HSSFWorkbook(fs);

}

if (!string.IsNullOrEmpty(sheetName))

{

sheet = workbook.GetSheet(sheetName);

if (sheet == null) //如果沒有找到指定的sheetName對應的sheet,則嘗試獲取第一個sheet

{

sheet = workbook.GetSheetAt(0);

}

}

else

{

sheet = workbook.GetSheetAt(0);

}

if (sheet != null)

{

IRow firstRow = sheet.GetRow(titleIndex);

int cellCount = firstRow.LastCellNum; //一行最后一個cell的編號 即總的列數

 

for (int i = firstRow.FirstCellNum; i < cellCount; ++i)

{

ICell cell = firstRow.GetCell(i);

if (cell != null)

{

string cellValue = cell.StringCellValue;

if (cellValue != null)

{

DataColumn column = new DataColumn(cellValue);

data.Columns.Add(column);

}

}

}

startRow = titleIndex + 1;

 

//最后一列的標號

int rowCount = sheet.LastRowNum;

for (int i = startRow; i <= rowCount; ++i)

{

IRow row = sheet.GetRow(i);

if (row == null) continue; //沒有數據的行默認是null       

 

DataRow dataRow = data.NewRow();

for (int j = row.FirstCellNum; j < cellCount; ++j)

{

if (row.GetCell(j) != null) //同理,沒有數據的單元格都默認是null

dataRow[j] = row.GetCell(j).ToString();

}

data.Rows.Add(dataRow);

}

}

}

catch (Exception ex)

{

ExceptionHelper.ThrowReferensNullException("Excel文件轉換錯誤,請確認填寫的數據格式是否跟模板一致。");

}

finally

{

fs.Close();

fs.Dispose();

}

return data;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM