需求說明
點擊按鈕,獲取頁面form表單的數(shù)據(jù)预伺,發(fā)送到服務(wù)器生成Excel文檔并下載到客戶端。
如果參數(shù)比較簡單,我們可以直接通過GET請求訪問生成Excel文檔的Action佩迟。如:
location.href = abp.appPath + 'Service/Export?input=' + result;
但是,如果參數(shù)比較復(fù)雜竿屹,且數(shù)量較多报强,繼續(xù)使用這種方式則顯得比較繁瑣,并且容易報錯拱燃。
此時秉溉,我們可以迂回一下,先把請求參數(shù)緩存到服務(wù)器碗誉,然后在生成Excel時從緩存獲取參數(shù)召嘶。
以下是具體的實現(xiàn):
前臺頁面中導(dǎo)出按鈕的點擊事件代碼如下:
//先請求SaveData接口來緩存參數(shù),然后用返回的result作為參數(shù)訪問Export來導(dǎo)出Excel文檔
_this.genDatas(function (result) {
//result 生成的表單數(shù)據(jù)
axios.post(abp.appPath + 'Service/SaveData', result).then(function (result) {
_this.matloading = false;
location.href = abp.appPath + 'Service/Export?input=' + result;
});
});
Controller 代碼:
public class ServiceController : ControllerBase
{
protected readonly IServiceAppService _serviceAppService;
private readonly ICacheManager _cacheManager;
public SendServiceController(IServiceAppService serviceAppService, ICacheManager cacheManager)
{
_cacheManager = cacheManager;
_serviceAppService = serviceAppService;
}
/// <summary>
/// 緩存參數(shù)哮缺,并返回No
/// </summary>
[System.Web.Http.HttpPost]
public JsonResult SaveData(InputDto input)
{
AsyncHelper.RunSync(()=>_cacheManager.GetCache("Export").SetAsync(input.No, input, TimeSpan.FromMinutes(10)));
return Json(input.No, JsonRequestBehavior.AllowGet);
}
/// <summary>
/// 導(dǎo)出Excel
/// </summary>
public FileResult Export(string input)
{
try
{
var items = _cacheManager.GetCache("Export").GetOrDefault<string, InputDto>(input);
var model = _serviceAppService.GetExportInfo(items);
HSSFWorkbook workbook = new HSSFWorkbook();
BuildExcel(workbook.CreateSheet("物品匯總列表"), model.Details.ToArray());
Stream ms = new MemoryStream();
workbook.Write(ms);
ms.Seek(0, SeekOrigin.Begin);
return File(ms, "application/ms-excel", "物品列表.xls");
}
catch (Exception ex)
{
throw new Exception("生成Excel出錯", ex);
}
}
/// <summary>
/// 生成Excel 只生成帶有[DisplayName]特性的字段
/// </summary>
public void BuildExcel<T>(ISheet sheet,T[] list) where T : new()
{
var properties = typeof(T).GetProperties();
for (int num = 0; num <= list.Length; num++)
{
var model = num == 0 ? new T() : list[num - 1];
IRow row = sheet.CreateRow(num);
var cellCol = 0;
for (int index = 0; index < properties.Length; index++)
{
var property = properties[index];
var attr = property.GetCustomAttribute<DisplayNameAttribute>();
if (attr == null)
continue;
if (num == 0)
{
row.CreateCell(cellCol).SetCellValue(attr.DisplayName);
cellCol++;
continue;
}
var value = property.GetValue(model, null) ?? "";
switch (property.PropertyType.ToString())
{
case "System.Boolean":
row.CreateCell(cellCol).SetCellValue(Convert.ToBoolean(value));
break;
case "System.DateTime":
row.CreateCell(cellCol).SetCellValue(Convert.ToDateTime(value).ToString("yyyy-MM-dd hh:mm:ss"));
break;
case "System.Double":
case "System.Int32":
case "System.Decimal":
row.CreateCell(cellCol).SetCellValue(Convert.ToDouble(value));
break;
default:
row.CreateCell(cellCol).SetCellValue(value.ToString());
break;
}
cellCol++;
}
}
}
}