/// <summary> /// 企業信息Excel批量導入 需要先引入NPOI /// </summary> /// <returns></returns> public ActionResult ImportEnterpriseInfomation() { var success = false; var message = string.Empty; var excelUrl = string.Empty; int totalCoun = 0; int successCount = 0; if (Request.Files == null || Request.Files.Count <= 0) { return Content("未獲取到文件"); } var file1 = Request.Files[0]; int ImgSize = file1.ContentLength; if (ImgSize > (5 * 1024 * 1024)) { return Content("文件過大"); } string fileName = file1.FileName.Substring(0, file1.FileName.LastIndexOf('.')) + "-" + DateTime.Now.ToString("yyyyMMddhhmmss") + file1.FileName.Substring(file1.FileName.LastIndexOf('.')); //生成將要保存的隨機文件名 // = GetFileName() + ".jpg"; //要上傳的文件 var fs = file1.InputStream; BinaryReader r = new BinaryReader(fs); //使用UploadFile方法可以用下面的格式 byte[] postArray = r.ReadBytes((int)fs.Length); string fileSave = Server.MapPath("~/TemplateExcel/QuestionBank"); //獲取文件的擴展名 file1.SaveAs(Path.Combine(fileSave, fileName)); TrainingFacade facade = new TrainingFacade(); var storePath = System.AppDomain.CurrentDomain.BaseDirectory + "\\TemplateExcel\\QuestionBank\\" + fileName; //從EXCEL讀取數據 var qbdto = EnterpriseInformationExcel(storePath, storePath, out message); var excelModels = new List<EnterpriseExcelModel>(); if (qbdto != null) { totalCoun = qbdto.Count; qbdto.ForEach(item => { var result = facade.InsertEnterpriseInformation(item); if (result.IsSuccess) { successCount++; } else { excelModels.Add(item); } }); success = successCount > 0 ? true : false; if (excelModels.Count > 0) { excelUrl = ExportEnterpriseInformation(excelModels); } } message += "<font style=\"color:green\">共" + totalCoun + "條,成功導入" + successCount + "條</font>"; return Json(new { success, msg = message, totalCoun, successCount, excelUrl }); } private List<EnterpriseExcelModel> EnterpriseInformationExcel(string filePath, string storePath, out string message) { var excelHelper = new ExcelHelper<EnterpriseExcelModel>(); var titleList = new List<string>(); titleList.Add("單位名稱*"); titleList.Add("許可證編號*"); titleList.Add("許可證有效期"); titleList.Add("注冊地址*"); titleList.Add("法定代表人"); titleList.Add("法人聯系電話"); titleList.Add("聯系人"); titleList.Add("聯系電話"); var contentItem = new Hashtable(); contentItem.Add("Name", "單位名稱*"); contentItem.Add("LicenseNum", "許可證編號*"); contentItem.Add("LicenceValidityPeriod", "許可證有效期"); contentItem.Add("Address", "注冊地址*"); contentItem.Add("LegalPerson", "法定代表人"); contentItem.Add("LegalPhone", "法人聯系電話"); contentItem.Add("Contacts", "聯系人"); contentItem.Add("Phone", "聯系電話"); var renewalItemViewModels = excelHelper.InformationExcel(filePath, storePath, titleList, contentItem, out message, 0); return renewalItemViewModels; } /// <summary> /// 企業信息錯誤信息導出 /// </summary> /// <returns></returns> private string ExportEnterpriseInformation(List<EnterpriseExcelModel> model) {
string filename = "";
string fullurl = "";
try
{
TrendArg arg = new TrendArg();
arg.appIds = AppId;
arg.Area = Area;
arg.timeOpt = StartTime;
arg.VersionTime = EndTime;
var EPFancade = new CockpitFacade();
var result = EPFancade.GetSunProduct_DifficultyStatistics(arg);
//創建Excel文件的對象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一個sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
ICellStyle style = book.CreateCellStyle();
IFont dataFont = book.CreateFont();
dataFont.FontHeightInPoints = 11;//設置字體大小
style.SetFont(dataFont);
style.Alignment = HorizontalAlignment.Center;//居中
style.VerticalAlignment = VerticalAlignment.Center;
style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
//給sheet1添加第一行的頭部標題
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
row1.Height = 30 * 20;
row1.CreateCell(0).SetCellValue("序號");
row1.CreateCell(1).SetCellValue("困難和訴求");
row1.CreateCell(2).SetCellValue("數量(個)");
for (int i = 0; i <= 2; i++)
{
try
{
//style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.PaleBlue.Index;
//sheet1.SetColumnWidth(i, 25 * 256);
ICell cell1 = sheet1.GetRow(0).GetCell(i);
cell1.CellStyle = style;
}
catch { }
}
sheet1.SetColumnWidth(0, 20 * 256);
sheet1.SetColumnWidth(1, 60 * 256);
sheet1.SetColumnWidth(2, 20 * 256);
if (result.Data != null && result.Data.Count > 0)
{
#region 聲明Excel文件對象
//將數據逐步寫入sheet1各個行
for (int i = 0; i < result.Data.Count; i++)
{
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
rowtemp.CreateCell(0).SetCellValue(result.Data[i].Num);
rowtemp.CreateCell(1).SetCellValue(result.Data[i].Difficulty ?? "");
rowtemp.CreateCell(2).SetCellValue(result.Data[i].DifficultyNum ?? "");
for (int j = 0; j <= 2; j++)
{
try
{
ICell cell1 = sheet1.GetRow(i + 1).GetCell(j);
cell1.CellStyle = style;
}
catch (Exception ex)
{
}
}
}
#endregion
}
string importPath = AppDomain.CurrentDomain.BaseDirectory + "ExcelExport\\";
filename = StartTime + "__" + EndTime + "_Sheet2_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";
string produceCardPath = string.Format("{0}{1}", importPath, filename);
FileStream fileHSSF = new FileStream(produceCardPath, FileMode.Create);
book.Write(fileHSSF);
byte[] byteArry = new byte[fileHSSF.Length];
fileHSSF.Close();
System.IO.MemoryStream ms = new System.IO.MemoryStream(byteArry);
book.Write(ms);
//寫入文件服務器
var pcmFilePath = Server.MapPath("~/ExcelExport/" + filename);
if (System.IO.File.Exists(pcmFilePath))
{
FileStream serverFs = new FileStream(pcmFilePath, FileMode.OpenOrCreate);
FileInfo fileInfo = new FileInfo(pcmFilePath);
BinaryReader serverBr = new BinaryReader(serverFs);
//使用UploadFile方法可以用下面的格式
byte[] postArray = serverBr.ReadBytes((int)serverFs.Length);
Jinher.JAP.BaseApp.FileServer.Deploy.CustomDTO.FileDTO fileDTO = new Jinher.JAP.BaseApp.FileServer.Deploy.CustomDTO.FileDTO();
fileDTO.UploadFileName = fileInfo.Name;
fileDTO.FileData = postArray;
fileDTO.FileSize = fileInfo.Length;
Jinher.JAP.BaseApp.FileServer.ISV.Facade.FileFacade fileFacade = new Jinher.JAP.BaseApp.FileServer.ISV.Facade.FileFacade();
string serverFilePath = fileFacade.UploadFile(fileDTO);
fullurl = System.Configuration.ConfigurationManager.AppSettings["FileServerUrl"] + serverFilePath;
}
}
catch (Exception ex)
{
SystemLog.LogWrite(
new LogEntity
{
CodeAuthor = "mazg",
ClassName = this.GetType().ToString(),
FunctionName = MethodBase.GetCurrentMethod().Name,
Error = ex
});
return Json(new { code = "0", Success = true, FileName = ex.Message }, JsonRequestBehavior.AllowGet);
}
return Json(new { uploaded = 1, fileName = "", url = fullurl, mes = "上傳成功" }, JsonRequestBehavior.AllowGet);
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Net; using System.Configuration; using Jinher.JAP.Common.Loging; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using NPOI.HSSF.UserModel; namespace Jinher.AMP.TPP.Common { public class ExcelHelper<T> { //private readonly ILog _logInfo = LogManager.GetLogger("INFO"); static int _startIndex = 1; readonly Hashtable _fromEnglishToChineseForBatchRenewalItem = new Hashtable() { { "QuestionType", "題型必填*" }, { "QuestionTitle", "題干內容必填*" }, { "QuestionExplain", "題目解析" }, { "IsRight", "正確答案必填*" }, { "QuestionAnswerA", "選項A必填*" }, { "QuestionAnswerB", "選項B必填*" }, { "QuestionAnswerC", "選項C" }, { "QuestionAnswerD", "選項D" } }; readonly List<string> CommonheaderRowNameList = new List<string>() { "題型必填*", "題干內容必填*", "題目解析", "正確答案必填*", "選項A必填*", "選項B必填*", "選項C", "選項D" }; readonly Hashtable _PersonItem = new Hashtable() { { "ID_Card", "ID_Card" }, { "Pro", "Pro" }, { "City", "City" }, { "Area", "Area" }, { "Town", "Town" }, { "Street", "Street" }, { "CompanyName", "CompanyName" }, { "Phone", "Phone" } }; readonly List<string> PersonNameList = new List<string>() { "ID_Card", "Pro", "City", "Area", "Town", "Street", "CompanyName", "Phone" }; private readonly string _fileServerURL = ConfigurationManager.AppSettings["FileServerURL"].ToString(); /// <summary> /// 導入Excel /// </summary> /// <param name="workbookFile">Excel所在路徑</param> /// <param name="storePath">文件存放地址,包含文件名(最好加上時間戳避免文件名重復)</param> /// <param name="categories">客戶類集合</param> /// <param name="agentInfos">傳入代理人的集合</param> /// <param name="excelErrorDataList">輸出的錯誤數據集合</param> /// <param name="message">返回的錯誤信息</param> /// <returns></returns> public List<T> FromExcel(string workbookFile, string storePath, string ExcelType, out string message) { IWorkbook iWorkBook = null; message = ""; if (HttpDownload(workbookFile, storePath)) { using (var file = new FileStream(storePath, FileMode.Open, FileAccess.Read)) { if (workbookFile.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本 iWorkBook = new XSSFWorkbook(file); else if (workbookFile.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本 iWorkBook = new HSSFWorkbook(file); } var sheet = iWorkBook.GetSheetAt(0); var headerRow = sheet.GetRow(_startIndex); //EXCEL表頭第一個單元格位置 var headerRowFirstCellNum = headerRow.FirstCellNum; var headerRowNameList = new List<string>(); if (ExcelType == "1") { headerRowNameList.AddRange(CommonheaderRowNameList); } else { headerRowNameList.AddRange(PersonNameList); } if (ExcelType == "1") { if (headerRow.GetCell(headerRowFirstCellNum) == null || headerRow.GetCell(headerRowFirstCellNum).ToString() != "題型必填*") { message = "<font style=\"color:red\">上傳失敗:</font>您上傳的模板不正確"; return null; } } else { if (headerRow.GetCell(headerRowFirstCellNum) == null || headerRow.GetCell(headerRowFirstCellNum).ToString() != "ID_Card") { message = "<font style=\"color:red\">上傳失敗:</font>您上傳的模板不正確"; return null; } } var bag = new List<T>(); var totalCount = sheet.LastRowNum - sheet.FirstRowNum - _startIndex; if (totalCount <= 0) { message = "<font style=\"color:red\">上傳失敗:</font>無任何數據"; return null; } GetListData(sheet, headerRow, sheet.FirstRowNum + _startIndex + 1, sheet.LastRowNum, bag, ExcelType); if (bag.Count <= 0) { message = "<font style=\"color:red\">上傳失敗:</font>請在模板中查看上傳規則,並檢查數據正確性"; } return bag.ToList(); } else { message = "<font style=\"color:red\">讀取出錯</font>無任何數據"; return null; } } object valueType(Type t, ICell value) { object o = null; string strt = t.ToString(); if (t.Name == "Nullable`1") { strt = t.GetGenericArguments()[0].Name; } var valStr = string.Empty; if (value != null) valStr = GetNoTNullValue(GetCellValue(value)); if (string.IsNullOrWhiteSpace(valStr)) return o; switch (strt) { case "System.Decimal": o = decimal.Parse(valStr.Trim('\0')); break; case "System.Int32": o = int.Parse(valStr.Trim('\0')); break; case "System.Float": o = float.Parse(valStr.Trim('\0')); break; case "System.DateTime": if (HSSFDateUtil.IsCellDateFormatted(value)) { o = Convert.ToDateTime(valStr); } break; case "System.Int64": o = Int64.Parse(valStr.Trim('\0')); break; case "Int64": o = value == null ? null : (Int64.Parse(valStr.Trim('\0'))) as long?; break; case "DateTime": if (string.IsNullOrWhiteSpace(value.ToString())) o = null; else if (value.CellType == CellType.Numeric && HSSFDateUtil.IsCellDateFormatted(value)) o = (DateTime?)value.DateCellValue; else o = Convert.ToDateTime(valStr); break; default: o = valStr.Trim('\0'); break; } return o; } #region 優化方法GetListData int type = 0;//這個全局變量在下面用到 public List<T> GetListData(ISheet sheet, IRow headerRow, int startIndex, int endIndex, List<T> lists, string ExcelType) { var htLicenseNos = new List<string>(); for (var i = startIndex; i <= endIndex; i++) { //1 去掉空行 如果返回false從新循環 int out_i; int out_endIndex; if (RemoveEmptyRow(sheet, endIndex, i, out out_i, out out_endIndex)) { Dictionary<string, string> excelDictionary = null; if (CellValuation(sheet, i, out excelDictionary))//2 給每個單元格判斷空 不為空 賦值.ToString().Trim() 如果返回false從新循環 { if (ExcelType == "1") { if (SpecificCheckCell(excelDictionary, i, sheet))//3 執行具體的校驗 這一步下面還要細分8 { ConversionCell(excelDictionary, i, sheet, headerRow, lists); } } else { ConversionAttachCell(excelDictionary, i, sheet, headerRow, lists); } } } i = out_i; endIndex = out_endIndex; } return lists; } #region //轉化 public bool ConversionCell(Dictionary<string, string> excelDictionary, int i, ISheet sheet, IRow headerRow, List<T> lists) { //int type = 0;//有車架號和發動機號 IRow row = sheet.GetRow(i); var t = Activator.CreateInstance<T>(); var properties = t.GetType().GetProperties(); // int j = 0; foreach (var column in properties) { int j = headerRow.Cells.FindIndex( c => c.StringCellValue == (_fromEnglishToChineseForBatchRenewalItem[column.Name] == null ? column.Name : _fromEnglishToChineseForBatchRenewalItem[column.Name].ToString())); if (j >= 0 && row.GetCell(j) != null) { object value = valueType(column.PropertyType, row.GetCell(j)); if (value != null) { switch (column.Name) { case "QuestionType": value = value.ToString().ToUpper(); break; case "QuestionTitle": value = value.ToString().ToUpper(); break; case "QuestionExplain": value = value.ToString().ToUpper(); break; case "IsRight": value = value.ToString().ToUpper(); break; case "QuestionAnswerA": value = value.ToString().ToUpper(); break; case "QuestionAnswerB": value = value.ToString().ToUpper(); break; case "QuestionAnswerC": value = value.ToString().ToUpper(); break; case "QuestionAnswerD": value = value.ToString().ToUpper(); break; } } column.SetValue(t, value, null); } //j++; //if (j >= properties.Count()) //{ // break; //} } lists.Add(t); return true; } //轉化 public bool ConversionAttachCell(Dictionary<string, string> excelDictionary, int i, ISheet sheet, IRow headerRow, List<T> lists) { //int type = 0;//有車架號和發動機號 IRow row = sheet.GetRow(i); var t = Activator.CreateInstance<T>(); var properties = t.GetType().GetProperties(); // int j = 0; foreach (var column in properties) { int j = headerRow.Cells.FindIndex( c => c.StringCellValue == (_PersonItem[column.Name] == null ? column.Name : _PersonItem[column.Name].ToString())); if (j >= 0 && row.GetCell(j) != null) { object value = valueType(column.PropertyType, row.GetCell(j)); if (value != null) { switch (column.Name) { case "ID_Card": value = value.ToString().ToUpper(); break; case "Pro": value = value.ToString().ToUpper(); break; case "City": value = value.ToString().ToUpper(); break; case "Area": value = value.ToString().ToUpper(); break; case "Town": value = value.ToString().ToUpper(); break; case "Street": value = value.ToString().ToUpper(); break; case "CompanyName": value = value.ToString().ToUpper(); break; case "Phone": value = value.ToString().ToUpper(); break; } } column.SetValue(t, value, null); } //j++; //if (j >= properties.Count()) //{ // break; //} } lists.Add(t); return true; } //去掉空行 public bool RemoveEmptyRow(ISheet sheet, int endIndex, int i, out int out_i, out int out_endIndex) { if (sheet.GetRow(endIndex) == null) { out_i = --i; out_endIndex = --endIndex; return false; } for (int j = 0; j < sheet.GetRow(_startIndex).LastCellNum; j++) { bool c0_c14 = sheet.GetRow(endIndex).GetCell(j) == null || string.IsNullOrWhiteSpace(sheet.GetRow(endIndex).GetCell(j).ToString()); if (!c0_c14) { out_i = i; out_endIndex = endIndex; return true; } } out_i = --i; out_endIndex = --endIndex; return false; } public static string GetNoTNullValue(string values) { if (string.IsNullOrWhiteSpace(values)) return string.Empty; var stringItem = ""; foreach (var item in values.ToArray()) { if (char.IsNumber(item) || char.IsLetter(item) || char.IsPunctuation(item)) { stringItem = stringItem + item; } } return stringItem; } //取單元格賦值 public bool CellValuation(ISheet sheet, int i, out Dictionary<string, string> excelDictionary) { IRow row = sheet.GetRow(i) ?? sheet.CreateRow(i); IRow headerRow = sheet.GetRow(_startIndex); try { excelDictionary = new Dictionary<string, string>(); for (int j = headerRow.FirstCellNum; j < headerRow.LastCellNum; j++) { var headerName = headerRow.GetCell(j).ToString().Trim(); var cell = row.GetCell(j); var cellValue = GetCellValue(cell); if (!string.IsNullOrWhiteSpace(headerName)) { var value = GetNoTNullValue(cellValue); excelDictionary.Add(headerName, value); } } return true; } catch (Exception ex) { excelDictionary = null; return false; } } /// <summary> /// 獲取Excel對應的內容 為了支持有表達式的cell 取到正確的值 /// </summary> /// <param name="cell"></param> /// <returns></returns> public string GetCellValue(ICell cell) { try { var value = string.Empty; if (cell == null) return value; switch (cell.CellType) { case CellType.Numeric: if (DateUtil.IsCellDateFormatted(cell)) value = cell.DateCellValue.ToString("yyyy-MM-dd"); else value = cell.NumericCellValue.ToString(); break; case CellType.String: value = cell.StringCellValue; break; case CellType.Formula: value = cell.StringCellValue; break; case CellType.Boolean: value = cell.BooleanCellValue.ToString(); break; default: value = cell.ToString().Trim('\0'); break; } return value; } catch (Exception) { return cell.ToString().Trim('\0'); } } public bool SpecificCheckCell(Dictionary<string, string> excelDictionary, int i, ISheet sheet) { var sb = new StringBuilder(); //這里具體校驗分了八個步驟 //1檢查是否為空字典 if (!SpecificCheckCell_ToEmpty(excelDictionary)) { return false; } //驗證是否包含特殊字符 var regex = @"[\'|\\‘’“”]+"; foreach (var item in excelDictionary) { if (Regex.IsMatch(item.Value, regex)) sb.Append(item.Key + "包含有特殊字符"); } //2驗證 車牌 車架 發動機 車主證件號碼 return Specific(excelDictionary, sb); } public bool Specific(Dictionary<string, string> excelDictionary, StringBuilder sb) { List<string> questionBank = new List<string>() { "單選題", "多選題", "判斷題" }; string questionAnswer = "ABCD"; if (excelDictionary["題型必填*"] == null || string.IsNullOrEmpty(excelDictionary["題干內容必填*"]) || string.IsNullOrEmpty(excelDictionary["正確答案必填*"]) || string.IsNullOrEmpty(excelDictionary["選項A必填*"]) || string.IsNullOrEmpty(excelDictionary["選項B必填*"])) { sb.Append("必填項不能為空;"); } if (!questionBank.Exists(x => x.Contains(excelDictionary["題型必填*"].ToString()))) { sb.Append("題型只能選擇單選題,多選題,判斷題;"); } if (excelDictionary["題型必填*"] == "單選題" || excelDictionary["題型必填*"] == "多選題") { if (!questionAnswer.Contains(excelDictionary["正確答案必填*"].ToString())) { sb.Append("正確答案只能為A,B,C,D"); } } if (sb.Length >0) { return false; } else { return true; } } #region 校驗 下面的八個方法 public bool SpecificCheckCell_ToEmpty(Dictionary<string, string> excelDictionary) { var str = new StringBuilder(); foreach (var item in excelDictionary) { str.Append(item.Value); } if (string.IsNullOrWhiteSpace(str.ToString())) return false; else return true; } /// <summary> /// 非法字符轉換 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ReplaceStr(string str) { str = str.Replace("'", ""); str = str.Replace("/", ""); str = str.Replace(@"\", ""); return str; } /// <summary> /// 將字符串從0截取指定長度 /// </summary> /// <param name="oldString"></param> /// <param name="length"></param> /// <returns></returns> private string CutString(string oldString, int length) { return string.Join("", (oldString ?? "").ToList().Take(length)); } #endregion #endregion #endregion private bool CheckExcelRowData(ISheet sheet, int rowIndex, int cellIndex, int dataLength) { bool isPassChecked = true; if (sheet.GetRow(rowIndex).GetCell(cellIndex) != null && !string.IsNullOrEmpty(sheet.GetRow(rowIndex).GetCell(cellIndex).ToString()) && sheet.GetRow(rowIndex).GetCell(cellIndex).ToString().Trim().Length > dataLength) { isPassChecked = false; } return isPassChecked; } /// <summary> /// http下載文件 /// </summary> /// <param name="url">下載文件地址</param> /// <param name="storePath">文件存放地址,包含文件名(最好加上時間戳避免文件名重復)</param> /// <returns></returns> public bool HttpDownload(string url, string storePath) { return true; //try //{ // //_logInfo.Info("讀取文件路徑" + url); // string tempPath = System.IO.Path.GetDirectoryName(storePath); // System.IO.Directory.CreateDirectory(tempPath); //創建臨時文件目錄 // string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(storePath) + ".temp"; //臨時文件 // if (File.Exists(tempFile)) // { // File.Delete(tempFile); //存在則刪除 // } // if (File.Exists(storePath)) // { // File.Delete(storePath); //存在則刪除 // } // //_logInfo.Info("創建臨時文件:" + tempFile); // FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite); // // 設置參數 // HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; // //發送請求並獲取相應回應數據 // HttpWebResponse response = request.GetResponse() as HttpWebResponse; // //直到request.GetResponse()程序才開始向目標網頁發送Post請求 // Stream responseStream = response.GetResponseStream(); // //創建本地文件寫入流 // //Stream stream = new FileStream(tempFile, FileMode.Create); // byte[] bArr = new byte[1024]; // int size = responseStream.Read(bArr, 0, (int)bArr.Length); // while (size > 0) // { // //stream.Write(bArr, 0, size); // fs.Write(bArr, 0, size); // size = responseStream.Read(bArr, 0, (int)bArr.Length); // } // //stream.Close(); // fs.Close(); // responseStream.Close(); // //_logInfo.Info("移動臨時文件到指定位置開始:" + storePath); // System.IO.File.Move(tempFile, storePath); // //_logInfo.Info("移動臨時文件到指定位置完成:" + storePath); // return true; //} //catch (Exception ex) //{ // //_logInfo.Error("讀取批量續保文件路徑" + url + " 錯誤信息:" + ex.Message); // return false; //} } #region 個人信息導入 /// <summary> /// /// </summary> /// <param name="workbookFile">Excel所在路徑</param> /// <param name="storePath">文件存放地址,包含文件名(最好加上時間戳避免文件名重復)</param> /// <param name="headerRowNameList">標題集合</param> /// <param name="contentItem"></param> /// <param name="message">返回的錯誤信息</param> /// <param name="startIndex">標頭索引</param> /// <returns></returns> public List<T> InformationExcel(string workbookFile, string storePath, List<string> headerRowNameList,Hashtable contentItem, out string message,int startIndex=1) { IWorkbook iWorkBook = null; message = ""; _startIndex = startIndex; if (HttpDownload(workbookFile, storePath)) { using (var file = new FileStream(storePath, FileMode.Open, FileAccess.Read)) { if (workbookFile.IndexOf(".xlsx", StringComparison.Ordinal) > 0) // 2007版本 iWorkBook = new XSSFWorkbook(file); else if (workbookFile.IndexOf(".xls", StringComparison.Ordinal) > 0) // 2003版本 iWorkBook = new HSSFWorkbook(file); } var sheet = iWorkBook.GetSheetAt(0); var headerRow = sheet.GetRow(_startIndex); //EXCEL表頭第一個單元格位置 var headerRowFirstCellNum = headerRow.FirstCellNum; if (headerRow.GetCell(headerRowFirstCellNum) == null || headerRow.GetCell(headerRowFirstCellNum).ToString() != headerRowNameList[0]) { message = "<font style=\"color:red\">上傳失敗:</font>您上傳的模板不正確"; return null; } var bag = new List<T>(); var totalCount = sheet.LastRowNum - sheet.FirstRowNum - _startIndex; if (totalCount <= 0) { message = "<font style=\"color:red\">上傳失敗:</font>無任何數據"; return null; } GetListDataInformation(sheet, headerRow, sheet.FirstRowNum + _startIndex + 1, sheet.LastRowNum, bag, contentItem); if (bag.Count <= 0) { message = "<font style=\"color:red\">上傳失敗:</font>請在模板中查看上傳規則,並檢查數據正確性"; } return bag.ToList(); } else { message = "<font style=\"color:red\">讀取出錯</font>無任何數據"; return null; } } public List<T> GetListDataInformation(ISheet sheet, IRow headerRow, int startIndex, int endIndex, List<T> lists,Hashtable contentItem) { var htLicenseNos = new List<string>(); for (var i = startIndex; i <= endIndex; i++) { //1 去掉空行 如果返回false從新循環 int out_i; int out_endIndex; if (RemoveEmptyRow(sheet, endIndex, i, out out_i, out out_endIndex)) { Dictionary<string, string> excelDictionary = null; if (CellValuation(sheet, i, out excelDictionary))//2 給每個單元格判斷空 不為空 賦值.ToString().Trim() 如果返回false從新循環 { ConversionCellInformation(excelDictionary, i, sheet, headerRow, lists, contentItem); } } i = out_i; endIndex = out_endIndex; } return lists; } public bool ConversionCellInformation(Dictionary<string, string> excelDictionary, int i, ISheet sheet, IRow headerRow, List<T> lists,Hashtable contentItem) { IRow row = sheet.GetRow(i); var t = Activator.CreateInstance<T>(); var properties = t.GetType().GetProperties(); // int j = 0; foreach (var column in properties) { int j = headerRow.Cells.FindIndex( c => c.StringCellValue == (contentItem[column.Name] == null ? column.Name : contentItem[column.Name].ToString())); if (j >= 0 && row.GetCell(j) != null) { object value = valueType(column.PropertyType, row.GetCell(j)); column.SetValue(t, value, null); } //j++; //if (j >= properties.Count()) //{ // break; //} } lists.Add(t); return true; } #endregion } }
ICellStyle style = book.CreateCellStyle(); IFont dataFont = book.CreateFont(); dataFont.FontHeightInPoints = 11;//設置字體大小 style.SetFont(dataFont); style.Alignment = HorizontalAlignment.Center;//居中 style.VerticalAlignment = VerticalAlignment.Center; style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;