標籤:for try document 服務 pre error mod append request
using MongoDB.Bson;using Newtonsoft.Json.Linq;using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using System;using System.Collections;using System.Collections.Generic;using System.Data;using System.IO;using System.Linq;using System.Web;using System.Web.Http;using System.Web.Mvc;using Zluo.CMember.Entity;using Zluo.CMember.Interface;using Zluo.CMember.Service;using Zluo.CMember.Web.RequestParam;using Zluo.CMember.Web.RequestParam.Account;using Zluo.CMember.Web.RequestParam.Order;using Zluo.Common;using Zluo.Common.CMember;using Zluo.SessionCached;public void CreateExport() { try { string fileName = "ErrorSongIds.xls"; // 檔案名稱 string filePath = Path.Combine(HttpRuntime.AppDomainAppPath, "Upload") + "/" + fileName; // 1.檢測是否存在檔案夾,若不存在就建立個檔案夾 string directoryName = Path.GetDirectoryName(filePath); if (!Directory.Exists(directoryName)) { Directory.CreateDirectory(directoryName); } // 2.解析儲存格頭部,設定單元頭的中文名稱 HSSFWorkbook workbook = new HSSFWorkbook(); // 活頁簿 ISheet sheet = workbook.CreateSheet("失敗歌曲"); // 工作表 IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue("原始ID"); row.CreateCell(1).SetCellValue("歌曲名稱"); row.CreateCell(2).SetCellValue("歌手名"); row.CreateCell(3).SetCellValue("失敗原因"); //_songListService.getErrorExcel(uid); BsonArray array = null; int rowIndex = 1; BsonDocument bd = null; if (array != null && array.Count > 0) { for (int i = 0; i < array.Count; i++) { IRow rowTmp = sheet.CreateRow(rowIndex); bd = (BsonDocument)array[i]; if (bd != null) { rowTmp.CreateCell(0).SetCellValue(bd.GetValue("sourceId").ToString()); rowTmp.CreateCell(1).SetCellValue(bd.GetValue("songName").ToString()); rowTmp.CreateCell(2).SetCellValue(bd.GetValue("singerName").ToString()); rowTmp.CreateCell(3).SetCellValue(string.IsNullOrEmpty(bd.GetValue("errorReason").ToString()) ? "" : bd.GetValue("errorReason").ToString()); rowIndex++; } } } // 4.組建檔案 FileStream file = new FileStream(filePath, FileMode.Create); workbook.Write(file); file.Close(); Response.AppendHeader("Content-Disposition", "attachment;filename=ErrorSongIds.xls"); Response.ContentType = "application/ms-excel"; Response.WriteFile(filePath); Response.Flush(); Response.End(); } catch (Exception ex) { throw ex; } }
C#產生Excel儲存到伺服器端並下載