From d5631012a5867947d51d6e6916791bf6773b2079 Mon Sep 17 00:00:00 2001 From: xiaochanghai Date: Tue, 18 Jun 2024 19:55:33 +0800 Subject: [PATCH] =?UTF-8?q?=E9=A2=98=E5=BA=93=E5=AE=9A=E5=88=B6=E5=8C=96?= =?UTF-8?q?=E5=AF=BC=E5=85=A5Excwl=E5=BC=80=E5=8F=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Ghre/Ghre_QuestionController.cs | 9 + Tiobon.Core.Common/Helper/DateTimeHelper.cs | 375 ++++++++++ Tiobon.Core.Common/Helper/NPOIHelper.cs | 661 ++++++++++++++++++ Tiobon.Core.Common/Tiobon.Core.Common.csproj | 1 + .../Ghre/IGhre_QuestionServices.cs | 5 +- Tiobon.Core.Services/BASE/BaseServices.cs | 36 +- .../Ghre/Ghre_CourseServices.cs | 4 +- .../Ghre/Ghre_ExamServices.cs | 4 +- .../Ghre/Ghre_QuestionServices.cs | 139 +++- .../Ghre/Ghre_RequiredCourseServices.cs | 2 +- 10 files changed, 1215 insertions(+), 21 deletions(-) create mode 100644 Tiobon.Core.Common/Helper/DateTimeHelper.cs create mode 100644 Tiobon.Core.Common/Helper/NPOIHelper.cs diff --git a/Tiobon.Core.Api/Controllers/Ghre/Ghre_QuestionController.cs b/Tiobon.Core.Api/Controllers/Ghre/Ghre_QuestionController.cs index 3e29d183..0f976602 100644 --- a/Tiobon.Core.Api/Controllers/Ghre/Ghre_QuestionController.cs +++ b/Tiobon.Core.Api/Controllers/Ghre/Ghre_QuestionController.cs @@ -58,5 +58,14 @@ public class Ghre_QuestionController : BaseController ImportExcelAsync(IFormFile file) + { + return await _service.ImportExcelAsync(file); + } #endregion + } \ No newline at end of file diff --git a/Tiobon.Core.Common/Helper/DateTimeHelper.cs b/Tiobon.Core.Common/Helper/DateTimeHelper.cs new file mode 100644 index 00000000..d9208dca --- /dev/null +++ b/Tiobon.Core.Common/Helper/DateTimeHelper.cs @@ -0,0 +1,375 @@ +namespace Tiobon.Core.Common.Helper; + +public class DateTimeHelper +{ + public static string FriendlyDate(DateTime? date) + { + if (!date.HasValue) return string.Empty; + + string strDate = date.Value.ToString("yyyy-MM-dd"); + string vDate = string.Empty; + if (DateTime.Now.ToString("yyyy-MM-dd") == strDate) + { + vDate = "今天"; + } + else if (DateTime.Now.AddDays(1).ToString("yyyy-MM-dd") == strDate) + { + vDate = "明天"; + } + else if (DateTime.Now.AddDays(2).ToString("yyyy-MM-dd") == strDate) + { + vDate = "后天"; + } + else if (DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd") == strDate) + { + vDate = "昨天"; + } + else if (DateTime.Now.AddDays(2).ToString("yyyy-MM-dd") == strDate) + { + vDate = "前天"; + } + else + { + vDate = strDate; + } + + return vDate; + } + /// + /// 格式化DateTime类型为字符串类型,精确到年,如:2008 + /// + /// + /// + public static string ConvertToYearString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy"); + } + /// + /// 格式化DateTime类型为字符串类型,精确到年,如:2008 + /// + /// + /// + public static string ConvertToYearString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToYearString((DateTime)dateTime); + } + /// + /// 格式化DateTime类型为字符串类型,精确到月,如:2008/01 + /// + /// + /// + public static string ConvertToMonthString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM"); + } + /// + /// 格式化object类型为字符串类型,精确到月,如:2008/01 + /// + /// + /// + public static string ConvertToMonthString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToMonthString((DateTime)dateTime); + } + /// + /// 格式化DateTime类型为字符串类型,精确到天,如:2008/01/01 + /// + /// + /// + public static string ConvertToDayString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM\/dd"); + } + + public static DateTime ConvertToDay(DateTime dateTime) + { + string result = ConvertToDayString(dateTime); + if (string.IsNullOrEmpty(result)) + { + return DateTime.MinValue; + } + else + { + return Convert.ToDateTime(result); + } + } + + /// + /// 格式化DateTime类型为字符串类型,精确到小时,如:2008/01/01 18 + /// + /// + /// + public static string ConvertToHourString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM\/dd HH"); + } + /// + /// 格式化object类型为字符串类型,精确到小时,如:2008/01/01 18 + /// + /// + /// + public static string ConvertToHourString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToHourString((DateTime)dateTime); + } + + /// + /// 格式化object类型为字符串类型,精确到天,如:2008/01/01 + /// + /// + /// + public static string ConvertToDayString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToDayString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,精确到分钟,如:2008/01/01 18:09 + /// + /// + /// + public static string ConvertToMiniuteString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM\/dd HH:mm"); + } + + /// + /// 格式化object类型为字符串类型,精确到分钟,如:2008/01/01 18:09 + /// + /// + /// + public static string ConvertToMiniuteString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToMiniuteString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,精确到秒,如:2008/01/01 18:09:20 + /// + /// + /// + public static string ConvertToSecondString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM\/dd HH:mm:ss"); + } + /// + /// 格式化object类型为字符串类型,精确到秒,如:2008/01/01 18:09:20 + /// + /// + /// + public static string ConvertToSecondString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToSecondString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,如:01/01 + /// + /// + /// + public static string ConvertToOnlyMonthDayString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"MM\/dd"); + } + /// + /// 格式化object类型为字符串类型,如:01/01 + /// + /// + /// + public static string ConvertToOnlyMonthDayString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToOnlyMonthDayString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,如:12:12 + /// + /// + /// + public static string ConvertToOnlyHourMinuteString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"HH:mm"); + } + /// + /// 格式化object类型为字符串类型,如:12:12 + /// + /// + /// + public static string ConvertToOnlyHourMinuteString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToOnlyHourMinuteString(Convert.ToDateTime(dateTime)); + } + /// + /// 格式化DateTime类型为字符串类型,如:12:12:12 + /// + /// + /// + public static string ConvertToOnlySecondString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"HH:mm:ss"); + } + /// + /// 格式化object类型为字符串类型,如:12:12:12 + /// + /// + /// + public static string ConvertToOnlySecondString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToOnlySecondString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,如:2020/05 + /// + /// + /// + public static string ConvertToYearMonthString(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy\/MM"); + } + /// + /// 格式化object类型为字符串类型,如:2020/05 + /// + /// + /// + public static string ConvertToYearMonthString(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToYearMonthString(Convert.ToDateTime(dateTime)); + } + + /// + /// 格式化DateTime类型为字符串类型,如:2020-05 + /// + /// + /// + public static string ConvertToYearMonthString1(DateTime dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return dateTime.ToString(@"yyyy-MM"); + } + /// + /// 格式化object类型为字符串类型,如:2020-05 + /// + /// + /// + public static string ConvertToYearMonthString1(object dateTime) + { + if (string.IsNullOrEmpty(Convert.ToString(dateTime))) + { + return ""; + } + return ConvertToYearMonthString1(Convert.ToDateTime(dateTime)); + } + + /// + /// 毫秒转天时分秒 + /// + /// + /// + public static string FormatTime(long ms) + { + int ss = 1000; + int mi = ss * 60; + int hh = mi * 60; + int dd = hh * 24; + + long day = ms / dd; + long hour = (ms - day * dd) / hh; + long minute = (ms - day * dd - hour * hh) / mi; + long second = (ms - day * dd - hour * hh - minute * mi) / ss; + long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss; + + string sDay = day < 10 ? "0" + day : "" + day; //天 + string sHour = hour < 10 ? "0" + hour : "" + hour;//小时 + string sMinute = minute < 10 ? "0" + minute : "" + minute;//分钟 + string sSecond = second < 10 ? "0" + second : "" + second;//秒 + string sMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;//毫秒 + sMilliSecond = milliSecond < 100 ? "0" + sMilliSecond : "" + sMilliSecond; + + return string.Format("{0} 天 {1} 小时 {2} 分 {3} 秒", sDay, sHour, sMinute, sSecond); + } + +} \ No newline at end of file diff --git a/Tiobon.Core.Common/Helper/NPOIHelper.cs b/Tiobon.Core.Common/Helper/NPOIHelper.cs new file mode 100644 index 00000000..44a60c4f --- /dev/null +++ b/Tiobon.Core.Common/Helper/NPOIHelper.cs @@ -0,0 +1,661 @@ +using System.Data; +using System.Text; +using NPOI.HPSF; +using NPOI.HSSF.UserModel; +using NPOI.SS.UserModel; +using NPOI.XSSF.UserModel; + +namespace Tiobon.Core.Common.Helper; + +public class NPOIHelper +{ + #region DataTable 导出到 Excel 的 MemoryStream + /// + /// DataTable 导出到 Excel 的 MemoryStream + /// + /// 源 DataTable + /// 表头文本 空值未不要表头标题 + /// + public static MemoryStream ExportExcel(DataTable dtSource, string strHeaderText) + { + //HSSFWorkbook workbook = new HSSFWorkbook(); + XSSFWorkbook workbook = new XSSFWorkbook(); + ISheet sheet = workbook.CreateSheet(); + #region 文件属性 + DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); + dsi.Company = "EUCloud"; + //workbook.DocumentSummaryInformation = dsi; + SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); + si.Author = "EUCloud"; + si.ApplicationName = "EUCloud"; + si.LastAuthor = "EUCloud"; + si.Comments = ""; + si.Title = ""; + si.Subject = ""; + si.CreateDateTime = DateTime.Now; + //workbook.SummaryInformation = si; + #endregion + ICellStyle dateStyle = workbook.CreateCellStyle(); + IDataFormat format = workbook.CreateDataFormat(); + dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); + ICellStyle datetimeStyle = workbook.CreateCellStyle(); + datetimeStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm"); + ICellStyle datetimesStyle = workbook.CreateCellStyle(); + datetimesStyle.DataFormat = format.GetFormat("yyyy-mm-dd hh:mm:ss"); + int[] arrColWidth = new int[dtSource.Columns.Count]; + foreach (DataColumn item in dtSource.Columns) + { + arrColWidth[item.Ordinal] = Encoding.GetEncoding("utf-8").GetBytes(item.ColumnName.ToString()).Length; + } + for (int i = 0; i < dtSource.Rows.Count; i++) + { + for (int j = 0; j < dtSource.Columns.Count; j++) + { + int intTemp = Encoding.GetEncoding("utf-8").GetBytes(dtSource.Rows[i][j].ToString()).Length; + if (intTemp > arrColWidth[j]) + { + arrColWidth[j] = intTemp; + } + } + } + int rowIndex = 0; + int intTop = 0; + foreach (DataRow row in dtSource.Rows) + { + #region 新建表、填充表头、填充列头,样式 + if (rowIndex == 655350 || rowIndex == 0) + { + if (rowIndex != 0) + { + sheet = workbook.CreateSheet(); + } + intTop = 0; + #region 表头及样式 + { + if (strHeaderText.Length > 0) + { + IRow headerRow = sheet.CreateRow(intTop); + intTop += 1; + headerRow.HeightInPoints = 25; + headerRow.CreateCell(0).SetCellValue(strHeaderText); + ICellStyle headStyle = workbook.CreateCellStyle(); + headStyle.Alignment = HorizontalAlignment.Center; + IFont font = workbook.CreateFont(); + font.FontHeightInPoints = 20; + font.Boldweight = 700; + headStyle.SetFont(font); + headerRow.GetCell(0).CellStyle = headStyle; + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); + + } + } + #endregion + #region 列头及样式 + { + IRow headerRow = sheet.CreateRow(intTop); + intTop += 1; + ICellStyle headStyle = workbook.CreateCellStyle(); + headStyle.Alignment = HorizontalAlignment.Center; + headStyle.BorderBottom = BorderStyle.Medium; + headStyle.FillBackgroundColor = NPOI.HSSF.Util.HSSFColor.LightGreen.Index; + headStyle.FillPattern = FillPattern.NoFill; + IFont font = workbook.CreateFont(); + font.Boldweight = 700; + headStyle.SetFont(font); + foreach (DataColumn column in dtSource.Columns) + { + headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); + headerRow.GetCell(column.Ordinal).CellStyle = headStyle; + //设置列宽 + //sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); + if (arrColWidth[column.Ordinal] > 255) + { + arrColWidth[column.Ordinal] = 254; + } + else + { + sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); + } + } + + + } + #endregion + rowIndex = intTop; + } + #endregion + #region 填充内容 + IRow dataRow = sheet.CreateRow(rowIndex); + foreach (DataColumn column in dtSource.Columns) + { + ICell newCell = dataRow.CreateCell(column.Ordinal); + string drValue = row[column].ToString(); + switch (column.DataType.ToString()) + { + case "System.String"://字符串类型 + newCell.SetCellValue(drValue); + break; + case "System.DateTime"://日期类型 + DateTime dateV; + if (!string.IsNullOrEmpty(drValue)) + { + DateTime.TryParse(drValue, out dateV); + //dateV = DateTimeHelper.ConvertToSecondString(dateV); + newCell.SetCellValue(dateV); + if (column.Caption == "renderDateTime") + { + newCell.CellStyle = datetimeStyle;//格式化显示到分钟 + } + else if (column.Caption == "renderDate") + { + newCell.CellStyle = dateStyle;//格式化显示到天 + } + else + { + newCell.CellStyle = datetimesStyle;//格式化显示到秒 + } + } + break; + case "System.Boolean"://布尔型 + bool boolV = false; + bool.TryParse(drValue, out boolV); + newCell.SetCellValue(boolV); + break; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.Byte": + int intV = 0; + int.TryParse(drValue, out intV); + newCell.SetCellValue(intV); + break; + case "System.Decimal": + case "System.Double": + double doubV = 0; + double.TryParse(drValue, out doubV); + newCell.SetCellValue(doubV); + break; + case "System.DBNull"://空值处理 + newCell.SetCellValue(""); + break; + default: + newCell.SetCellValue(""); + break; + } + } + #endregion + rowIndex++; + } + using (MemoryStream ms = new MemoryStream()) + { + workbook.Write(ms); + ms.Flush(); + //ms.Position = 0; + return ms; + } + } + #endregion + + #region DaataTable 导出到 Excel 文件 + /// + /// DaataTable 导出到 Excel 文件 + /// + /// 源 DataaTable + /// 表头文本 + /// 保存位置(文件名及路径) + public static void ExportExcel(DataTable dtSource, string strHeaderText, string strFileName) + { + using (MemoryStream ms = ExportExcel(dtSource, strHeaderText)) + { + using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)) + { + byte[] data = ms.ToArray(); + fs.Write(data, 0, data.Length); + fs.Flush(); + } + } + } + #endregion + + #region 读取 excel,默认第一行为标头 + /// + /// 读取 excel,默认第一行为标头 + /// + /// excel 文档路径 + /// + public static DataTable ImportExcel(string strFileName, string sheetName = "") + { + DataTable dt = new DataTable(); + //HSSFWorkbook hssfworkbook; + IWorkbook hssfworkbook; + ISheet sheet; + using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) + { + //hssfworkbook = new HSSFWorkbook(file); + //hssfworkbook = new XSSFWorkbook(file); + hssfworkbook = NPOI.SS.UserModel.WorkbookFactory.Create(file); + } + if (hssfworkbook == null) throw new Exception("未能加载excel"); + int sheetCount = hssfworkbook.NumberOfSheets; + if (sheetCount == 0) throw new Exception("未能加载excel"); + if (string.IsNullOrEmpty(sheetName)) + { + sheet = hssfworkbook.GetSheetAt(0); + } + else + { + int sheetIndex = hssfworkbook.GetSheetIndex(sheetName); + if (sheetIndex >= 0) + { + sheet = hssfworkbook.GetSheetAt(sheetIndex); + } + else + { + throw new Exception($"未能找到{sheetName}这个sheet页"); + } + } + System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); + IRow headerRow = sheet.GetRow(0); + int cellCount = headerRow.LastCellNum; + for (int j = 0; j < cellCount; j++) + { + ICell cell = headerRow.GetCell(j); + dt.Columns.Add(cell.ToString()); + } + for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) + { + IRow row = sheet.GetRow(i); + if (row.GetCell(row.FirstCellNum) != null && row.GetCell(row.FirstCellNum).ToString().Length > 0) + //if (row.GetCell(row.FirstCellNum) != null) + { + DataRow dataRow = dt.NewRow(); + for (int j = row.FirstCellNum; j < cellCount; j++) + { + if (row.GetCell(j) != null) + { + DateTime dateV = DateTime.MinValue; + try + { + dataRow[j] = GetCellValue(row.GetCell(j)); + //if (row.GetCell(j).IsDate()) + //{ + // dateV = row.GetCell(j).DateCellValue; + // dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV); + //} + //else + //{ + // dataRow[j] = row.GetCell(j).ToString(); + //} + } + catch { } + //if (dateV == DateTime.MinValue) + //{ + // dataRow[j] = row.GetCell(j).ToString(); + //} + //else + //{ + // dataRow[j] = DateTimeHelper.ConvertToSecondString(dateV); + //} + + } + } + dt.Rows.Add(dataRow); + } + } + return dt; + + } + #endregion + + /// + /// 获取单元格类型 + /// + /// + /// + private static string GetCellValue(ICell cell) + { + if (cell == null) + return null; + switch (cell.CellType) + { + case CellType.Blank: //BLANK: + return null; + case CellType.Boolean: //BOOLEAN: + return Convert.ToString(cell.BooleanCellValue); + case CellType.Numeric: //NUMERIC: + if (DateUtil.IsCellDateFormatted(cell)) + { + return DateTimeHelper.ConvertToSecondString(cell.DateCellValue); + } + else + { + return Convert.ToString(cell); + } + case CellType.String: //STRING: + return cell.StringCellValue; + case CellType.Error: //ERROR: + return Convert.ToString(cell.ErrorCellValue); + case CellType.Formula: //FORMULA: + default: + return "=" + cell.CellFormula; + } + } + + /// + /// DataSet 导出到 Excel 的 MemoryStream + /// + /// 源 DataSet + /// 表头文本 空值未不要表头标题(多个表对应多个表头以英文逗号(,)分开,个数应与表相同) + /// + public static MemoryStream ExportExcel(DataSet dsSource, string strHeaderText) + { + + HSSFWorkbook workbook = new HSSFWorkbook(); + + #region 文件属性 + DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); + dsi.Company = "517best.com"; + workbook.DocumentSummaryInformation = dsi; + SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); + si.Author = "517best.com"; + si.ApplicationName = "517best.com"; + si.LastAuthor = "517best.com"; + si.Comments = ""; + si.Title = ""; + si.Subject = ""; + si.CreateDateTime = DateTime.Now; + workbook.SummaryInformation = si; + #endregion + + #region 注释 + + + //ICellStyle dateStyle = workbook.CreateCellStyle(); + //IDataFormat format = workbook.CreateDataFormat(); + //dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); + + //ISheet sheet = workbook.CreateSheet(); + //int[] arrColWidth = new int[dtSource.Columns.Count]; + //foreach (DataColumn item in dtSource.Columns) + //{ + // arrColWidth[item.Ordinal] = Encoding.GetEncoding("gb2312").GetBytes(item.ColumnName.ToString()).Length; + //} + //for (int i = 0; i < dtSource.Rows.Count; i++) + //{ + // for (int j = 0; j < dtSource.Columns.Count; j++) + // { + // int intTemp = Encoding.GetEncoding("gb2312").GetBytes(dtSource.Rows[i][j].ToString()).Length; + // if (intTemp > arrColWidth[j]) + // { + // arrColWidth[j] = intTemp; + // } + // } + //} + //int rowIndex = 0; + //int intTop = 0; + //foreach (DataRow row in dtSource.Rows) + //{ + // #region 新建表、填充表头、填充列头,样式 + // if (rowIndex == 65535 || rowIndex == 0) + // { + // if (rowIndex != 0) + // { + // sheet = workbook.CreateSheet(); + // } + // intTop = 0; + // #region 表头及样式 + // { + // if (strHeaderText.Length > 0) + // { + // IRow headerRow = sheet.CreateRow(intTop); + // intTop += 1; + // headerRow.HeightInPoints = 25; + // headerRow.CreateCell(0).SetCellValue(strHeaderText); + // ICellStyle headStyle = workbook.CreateCellStyle(); + // headStyle.Alignment = HorizontalAlignment.CENTER; + // IFont font = workbook.CreateFont(); + // font.FontHeightInPoints = 20; + // font.Boldweight = 700; + // headStyle.SetFont(font); + // headerRow.GetCell(0).CellStyle = headStyle; + // sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); + + // } + // } + // #endregion + // #region 列头及样式 + // { + // IRow headerRow = sheet.CreateRow(intTop); + // intTop += 1; + // ICellStyle headStyle = workbook.CreateCellStyle(); + // headStyle.Alignment = HorizontalAlignment.CENTER; + // IFont font = workbook.CreateFont(); + // font.Boldweight = 700; + // headStyle.SetFont(font); + // foreach (DataColumn column in dtSource.Columns) + // { + // headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); + // headerRow.GetCell(column.Ordinal).CellStyle = headStyle; + // //设置列宽 + // sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); + // } + + + // } + // #endregion + // rowIndex = intTop; + // } + // #endregion + // #region 填充内容 + // IRow dataRow = sheet.CreateRow(rowIndex); + // foreach (DataColumn column in dtSource.Columns) + // { + // ICell newCell = dataRow.CreateCell(column.Ordinal); + // string drValue = row[column].ToString(); + // switch (column.DataType.ToString()) + // { + // case "System.String"://字符串类型 + // newCell.SetCellValue(drValue); + // break; + // case "System.DateTime"://日期类型 + // DateTime dateV; + // DateTime.TryParse(drValue, out dateV); + // newCell.SetCellValue(dateV); + // newCell.CellStyle = dateStyle;//格式化显示 + // break; + // case "System.Boolean"://布尔型 + // bool boolV = false; + // bool.TryParse(drValue, out boolV); + // newCell.SetCellValue(boolV); + // break; + // case "System.Int16": + // case "System.Int32": + // case "System.Int64": + // case "System.Byte": + // int intV = 0; + // int.TryParse(drValue, out intV); + // newCell.SetCellValue(intV); + // break; + // case "System.Decimal": + // case "System.Double": + // double doubV = 0; + // double.TryParse(drValue, out doubV); + // newCell.SetCellValue(doubV); + // break; + // case "System.DBNull"://空值处理 + // newCell.SetCellValue(""); + // break; + // default: + // newCell.SetCellValue(""); + // break; + // } + // } + // #endregion + // rowIndex++; + //} + #endregion + + string[] strNewText = strHeaderText.Split(Convert.ToChar(",")); + if (dsSource.Tables.Count == strNewText.Length) + { + for (int i = 0; i < dsSource.Tables.Count; i++) + { + ExportFromDSExcel(workbook, dsSource.Tables[i], strNewText[i]); + } + } + + using (MemoryStream ms = new MemoryStream()) + { + workbook.Write(ms); + ms.Flush(); + ms.Position = 0; + return ms; + } + } + /// + /// DataTable 导出到 Excel 的 MemoryStream + /// + /// 源 workbook + /// 源 DataTable + /// 表头文本 空值未不要表头标题(多个表对应多个表头以英文逗号(,)分开,个数应与表相同) + /// + public static void ExportFromDSExcel(HSSFWorkbook workbook, DataTable dtSource, string strHeaderText) + { + ICellStyle dateStyle = workbook.CreateCellStyle(); + IDataFormat format = workbook.CreateDataFormat(); + dateStyle.DataFormat = format.GetFormat("yyyy-MM-dd HH:mm:ss"); + ISheet sheet = workbook.CreateSheet(strHeaderText); + + int[] arrColWidth = new int[dtSource.Columns.Count]; + foreach (DataColumn item in dtSource.Columns) + { + arrColWidth[item.Ordinal] = Encoding.GetEncoding("utf-8").GetBytes(item.ColumnName.ToString()).Length; + } + for (int i = 0; i < dtSource.Rows.Count; i++) + { + for (int j = 0; j < dtSource.Columns.Count; j++) + { + int intTemp = Encoding.GetEncoding("utf-8").GetBytes(dtSource.Rows[i][j].ToString()).Length; + if (intTemp > arrColWidth[j]) + { + arrColWidth[j] = intTemp; + } + } + } + int rowIndex = 0; + int intTop = 0; + foreach (DataRow row in dtSource.Rows) + { + #region 新建表、填充表头、填充列头,样式 + if (rowIndex == 65535 || rowIndex == 0) + { + if (rowIndex != 0) + { + sheet = workbook.CreateSheet(); + } + intTop = 0; + #region 表头及样式 + { + if (strHeaderText.Length > 0) + { + IRow headerRow = sheet.CreateRow(intTop); + intTop += 1; + headerRow.HeightInPoints = 25; + headerRow.CreateCell(0).SetCellValue(strHeaderText); + ICellStyle headStyle = workbook.CreateCellStyle(); + headStyle.Alignment = HorizontalAlignment.Center; + IFont font = workbook.CreateFont(); + font.FontHeightInPoints = 20; + font.Boldweight = 700; + headStyle.SetFont(font); + headerRow.GetCell(0).CellStyle = headStyle; + sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1)); + + } + } + #endregion + #region 列头及样式 + { + IRow headerRow = sheet.CreateRow(intTop); + intTop += 1; + ICellStyle headStyle = workbook.CreateCellStyle(); + headStyle.Alignment = HorizontalAlignment.Center; + IFont font = workbook.CreateFont(); + font.Boldweight = 700; + headStyle.SetFont(font); + foreach (DataColumn column in dtSource.Columns) + { + headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); + headerRow.GetCell(column.Ordinal).CellStyle = headStyle; + //设置列宽 + // sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256); // 设置设置列宽 太长会报错 修改2014 年9月22日 + int dd = (arrColWidth[column.Ordinal] + 1) * 256; + + if (dd > 200 * 256) + { + dd = 100 * 256; + } + + + sheet.SetColumnWidth(column.Ordinal, dd); + } + + + } + #endregion + rowIndex = intTop; + } + #endregion + #region 填充内容 + IRow dataRow = sheet.CreateRow(rowIndex); + foreach (DataColumn column in dtSource.Columns) + { + ICell newCell = dataRow.CreateCell(column.Ordinal); + string drValue = row[column].ToString(); + switch (column.DataType.ToString()) + { + case "System.String"://字符串类型 + newCell.SetCellValue(drValue); + break; + case "System.DateTime"://日期类型 + if (drValue.Length > 0) + { + DateTime dateV; + DateTime.TryParse(drValue, out dateV); + newCell.SetCellValue(dateV); + newCell.CellStyle = dateStyle;//格式化显示 + } + else { newCell.SetCellValue(drValue); } + break; + case "System.Boolean"://布尔型 + bool boolV = false; + bool.TryParse(drValue, out boolV); + newCell.SetCellValue(boolV); + break; + case "System.Int16": + case "System.Int32": + case "System.Int64": + case "System.Byte": + int intV = 0; + int.TryParse(drValue, out intV); + newCell.SetCellValue(intV); + break; + case "System.Decimal": + case "System.Double": + double doubV = 0; + double.TryParse(drValue, out doubV); + newCell.SetCellValue(doubV); + break; + case "System.DBNull"://空值处理 + newCell.SetCellValue(""); + break; + default: + newCell.SetCellValue(""); + break; + } + } + #endregion + rowIndex++; + } + } +} diff --git a/Tiobon.Core.Common/Tiobon.Core.Common.csproj b/Tiobon.Core.Common/Tiobon.Core.Common.csproj index a8dfb746..0237c40b 100644 --- a/Tiobon.Core.Common/Tiobon.Core.Common.csproj +++ b/Tiobon.Core.Common/Tiobon.Core.Common.csproj @@ -27,6 +27,7 @@ + diff --git a/Tiobon.Core.IServices/Ghre/IGhre_QuestionServices.cs b/Tiobon.Core.IServices/Ghre/IGhre_QuestionServices.cs index ba63101e..05a4e692 100644 --- a/Tiobon.Core.IServices/Ghre/IGhre_QuestionServices.cs +++ b/Tiobon.Core.IServices/Ghre/IGhre_QuestionServices.cs @@ -1,4 +1,5 @@ -using Tiobon.Core.IServices.BASE; +using Microsoft.AspNetCore.Http; +using Tiobon.Core.IServices.BASE; using Tiobon.Core.Model; using Tiobon.Core.Model.Models; @@ -13,5 +14,7 @@ namespace Tiobon.Core.IServices Task InsertFrom(FromGhre_QuestionPageData insertModel); Task UpdareFrom(long Id, FromGhre_QuestionPageData insertModel); + + Task ImportExcelAsync(IFormFile file); } } \ No newline at end of file diff --git a/Tiobon.Core.Services/BASE/BaseServices.cs b/Tiobon.Core.Services/BASE/BaseServices.cs index ef487a69..d320c2a9 100644 --- a/Tiobon.Core.Services/BASE/BaseServices.cs +++ b/Tiobon.Core.Services/BASE/BaseServices.cs @@ -309,15 +309,19 @@ public class BaseServices : IBaseServ /// public virtual async Task Add(TInsertDto entity) { - HttpRequest request = UserContext.Context.Request; - var api = request.Path.ObjToString().TrimEnd('/').ToLower(); - var ip = GetUserIp(UserContext.Context); - var entity1 = Mapper.Map(entity).ToANew(); - BasePoco ent = entity1 as BasePoco; + if (UserContext.Context != null) + { + HttpRequest request = UserContext.Context.Request; + var api = request.Path.ObjToString().TrimEnd('/').ToLower(); + var ip = GetUserIp(UserContext.Context); + + BasePoco ent = entity1 as BasePoco; + + ent.CreateIP = ip; + ent.CreateProg = api; + } - ent.CreateIP = ip; - ent.CreateProg = api; #region 检查是否存在相同值 CheckOnly(entity1); @@ -335,10 +339,16 @@ public class BaseServices : IBaseServ { if (listEntity != null && listEntity.Any()) { - var userId = UserContext.Current.User_Id; - HttpRequest request = UserContext.Context.Request; - var api = request.Path.ObjToString().TrimEnd('/').ToLower(); - var ip = GetUserIp(UserContext.Context); + var userId = App.User.ID; + var api = string.Empty; + var ip = string.Empty; + if (UserContext.Context != null) + { + HttpRequest request = UserContext.Context.Request; + api = request.Path.ObjToString().TrimEnd('/').ToLower(); + ip = GetUserIp(UserContext.Context); + } + var list = Mapper.Map(listEntity).ToANew>(); list.ForEach(entity => { @@ -704,7 +714,7 @@ public class BaseServices : IBaseServ public virtual async Task> QueryFilterPage(QueryBody filter, string condition) { if (string.IsNullOrWhiteSpace(filter.orderBy)) - filter.orderBy = "UpdateTime DESC,CreateTime DESC"; + filter.orderBy = "CreateTime1 DESC"; if (filter.pageSize == 0) filter.pageSize = 10000; @@ -721,7 +731,7 @@ public class BaseServices : IBaseServ ISNULL ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END FROM Ghrs_User B WHERE B.UserId = A.UpdateBy), - '') UpdateDataInfo + '') UpdateDataInfo, ISNULL(A.UpdateTime, A.CreateTime) CreateTime1 FROM {entityType.GetEntityTableName()} A"; string conditions = " WHERE IsEnable = 1"; diff --git a/Tiobon.Core.Services/Ghre/Ghre_CourseServices.cs b/Tiobon.Core.Services/Ghre/Ghre_CourseServices.cs index 6bedee7d..0bafbd65 100644 --- a/Tiobon.Core.Services/Ghre/Ghre_CourseServices.cs +++ b/Tiobon.Core.Services/Ghre/Ghre_CourseServices.cs @@ -52,7 +52,7 @@ public class Ghre_CourseServices : BaseServices ImportExcelAsync(IFormFile file) + { + long id = SnowFlakeSingle.instance.getID(); + var path = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}"; + if (!Directory.Exists(path)) + Directory.CreateDirectory(path); + + var filepath = path + file.FileName; + using (var stream = File.Create(filepath)) + { + await file.CopyToAsync(stream); + } + + var types = new List + { + "单选题", + //"多选题", + //"判断题", + //"填空题", + //"简答题", + }; + var answers = new List + { + "A", + "B", + "C", + "D", + "E", + "F", + "G", + "H", + }; + + + types.ForEach(async x => + { + + string questionType = ConvertQuestionType1(x); + DataTable dt = NPOIHelper.ImportExcel(filepath, "单选题"); + for (int i = 0; i < dt.Rows.Count; i++) + { + var course = await _ghre_CourseServices.Query(x => x.CourseName == dt.Rows[i]["课程(必填)"].ToString()); + + var questionContent = dt.Rows[i]["题干(必填)"].ToString(); + var correctAnswer = dt.Rows[i]["正确答案(必填)"].ToString(); + var questionAnalysis = dt.Rows[i]["解析"].ToString(); + var difficultyLevel = dt.Rows[i]["难度"].ToString(); + + var question = await base.Query(x => x.QuestionContent == questionContent); + if (!question.Any()) + { + var insert = new InsertGhre_QuestionInput() + { + CourseId = course.FirstOrDefault().Id, + QuestionNo = await GenerateContinuousSequence(questionType.Substring(0, 1)), + DifficultyLevel = ConvertDifficultyLevel1(difficultyLevel), + QuestionType = questionType, + QuestionContent = questionContent, + QuestionAnalysis = questionAnalysis + }; + var id = await base.Add(insert); + var insertAnswers = new List(); + int j = 100; + answers.ForEach(a => + { + var answer = dt.Rows[i]["选项" + a].ToString(); + if (!string.IsNullOrWhiteSpace(answer)) + { + var isCorrect = false; + + if (x == "单选题" && correctAnswer == a) + isCorrect = true; + + insertAnswers.Add(new InsertGhre_QuestionAnswerInput() + { + TaxisNo = j, + QuestionNo = a, + QuestionId = id, + AnswerContent = answer, + IsCorrect = isCorrect + }); + } + + j = j + 100; + }); + + await _ghre_QuestionAnswerServices.Add(insertAnswers); + + } + else + { + + } + + } + }); + + return ServiceResult.OprateSuccess("新增成功!"); + + } + #endregion } \ No newline at end of file diff --git a/Tiobon.Core.Services/Ghre/Ghre_RequiredCourseServices.cs b/Tiobon.Core.Services/Ghre/Ghre_RequiredCourseServices.cs index 72cbbd62..bfdde7e6 100644 --- a/Tiobon.Core.Services/Ghre/Ghre_RequiredCourseServices.cs +++ b/Tiobon.Core.Services/Ghre/Ghre_RequiredCourseServices.cs @@ -28,7 +28,7 @@ public class Ghre_RequiredCourseServices : BaseServices> QueryFilterPage(QueryBody filter) { if (string.IsNullOrWhiteSpace(filter.orderBy)) - filter.orderBy = "UpdateTime DESC,CreateTime DESC"; + filter.orderBy = "CreateTime1 DESC"; if (filter.pageSize == 0) filter.pageSize = 10000;