Commit 97826a2a authored by liudong1993's avatar liudong1993

1

parent ada84f88
using EduSpider.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Config;
using VTX.FW.DB;
namespace EduSpider.Repository
{
/// <summary>
/// 考试仓储接口
/// </summary>
public interface IExamRepository : IDBRepository<RB_Exam>, IDependency
{
}
}
using EduSpider.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Config;
using VTX.FW.DB;
namespace EduSpider.Repository
{
/// <summary>
/// 考试题目仓储接口
/// </summary>
public interface IExam_QuestionsRepository : IDBRepository<RB_Exam_Questions>, IDependency
{
}
}
using EduSpider.Model.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Config;
using VTX.FW.DB;
namespace EduSpider.Repository
{
/// <summary>
/// 考试得分仓储接口
/// </summary>
public interface IExam_ScoreRepository : IDBRepository<RB_Exam_Score>, IDependency
{
}
}
......@@ -14,5 +14,6 @@ namespace EduSpider.IRepository
/// <param name="students"></param>
/// <returns></returns>
public bool BatchSetStudent(List<RB_Student> students);
List<RB_Student> GetListForStuName(string stuNames);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Config;
namespace EduSpider.IServices
{
/// <summary>
/// 考试服务层接口
/// </summary>
public interface IExamService : IDependency
{
string ImportExcelForStuExamScore(string path_server,int courseId, string examName, int userId);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Attr;
namespace EduSpider.Model.Entity
{
/// <summary>
/// 考试
/// </summary>
[Serializable]
[DB(ConnectionName = "DefaultConnection")]
public class RB_Exam
{
/// <summary>
/// ExamId
/// </summary>
public int ExamId { get; set; }
/// <summary>
/// 考试名称
/// </summary>
public string ExamName { get; set; }
/// <summary>
/// 关联课程
/// </summary>
public int CourseId { get; set; }
/// <summary>
/// 删除状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 创建人
/// </summary>
public int CreateBy { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Attr;
namespace EduSpider.Model.Entity
{
/// <summary>
/// 考试题目
/// </summary>
[Serializable]
[DB(ConnectionName = "DefaultConnection")]
public class RB_Exam_Questions
{
/// <summary>
/// Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 考试ID
/// </summary>
public int ExamId { get; set; }
/// <summary>
/// 题号
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 难度
/// </summary>
public string Difficulty { get; set; }
/// <summary>
/// 知识点
/// </summary>
public string KnowledgePoint { get; set; }
/// <summary>
/// 归属模块
/// </summary>
public string Module { get; set; }
/// <summary>
/// 分数
/// </summary>
public decimal Score { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Attr;
namespace EduSpider.Model.Entity
{
/// <summary>
/// 考试分数
/// </summary>
[Serializable]
[DB(ConnectionName = "DefaultConnection")]
public class RB_Exam_Score
{
/// <summary>
/// Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 考试ID
/// </summary>
public int ExamId { get; set; }
/// <summary>
/// 学生ID
/// </summary>
public int StuId { get; set; }
/// <summary>
/// 导入的姓名
/// </summary>
public string StuName { get; set; }
/// <summary>
/// 得分明细 json格式
/// </summary>
public string Content { get; set; }
/// <summary>
/// 总分
/// </summary>
public decimal TScore { get; set; }
/// <summary>
/// 排名
/// </summary>
public int Rank { get; set; }
/// <summary>
/// 百分比排名
/// </summary>
public decimal RankRate { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Attr;
namespace EduSpider.Model.Entity
{
/// <summary>
/// 考试分数
/// </summary>
[Serializable]
[DB(ConnectionName = "DefaultConnection")]
public class RB_Exam_Score2
{
/// <summary>
/// Id
/// </summary>
public int Id { get; set; }
/// <summary>
/// 考试ID
/// </summary>
public int ExamId { get; set; }
/// <summary>
/// 学生ID
/// </summary>
public int StuId { get; set; }
/// <summary>
/// 题号
/// </summary>
public int Sort { get; set; }
/// <summary>
/// 分数
/// </summary>
public decimal Score { get; set; }
/// <summary>
/// 导入的姓名
/// </summary>
public string StuName { get; set; }
}
}
using EduSpider.Model.Entity;
using System;
using VTX.FW.Attr;
namespace EduSpider.Model.Extend
{
/// <summary>
/// 考试扩展
/// </summary>
public class RB_Exam_Extend : RB_Exam
{
}
}
using EduSpider.Model.Entity;
using System;
using VTX.FW.Attr;
namespace EduSpider.Model.Extend
{
/// <summary>
/// 考试题目扩展
/// </summary>
public class RB_Exam_Questions_Extend : RB_Exam_Questions
{
}
}
using EduSpider.Model.Entity;
using System;
using VTX.FW.Attr;
namespace EduSpider.Model.Extend
{
/// <summary>
/// 考试分数扩展
/// </summary>
public class RB_Exam_Score_Extend : RB_Exam_Score
{
}
}
using EduSpider.Model.Entity;
using EduSpider.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EduSpider.Repository
{
/// <summary>
/// 考试仓储层
/// </summary>
public class ExamRepository : BaseRepository<RB_Exam>, IExamRepository
{
}
}
using EduSpider.Model.Entity;
using EduSpider.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EduSpider.Repository
{
/// <summary>
/// 考试题目仓储层
/// </summary>
public class Exam_QuestionsRepository : BaseRepository<RB_Exam_Questions>, IExam_QuestionsRepository
{
}
}
using EduSpider.Model.Entity;
using EduSpider.Repository.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EduSpider.Repository
{
/// <summary>
/// 考试得分仓储层
/// </summary>
public class Exam_ScoreRepository : BaseRepository<RB_Exam_Score>, IExam_ScoreRepository
{
}
}
......@@ -2,6 +2,7 @@
using EduSpider.Model.Entity;
using EduSpider.Repository.Base;
using System.Collections.Generic;
using System.Linq;
namespace EduSpider.Repository
{
......@@ -13,5 +14,16 @@ namespace EduSpider.Repository
flag = base.BatchInsert(students, isReplace: true);
return flag;
}
/// <summary>
/// 获取学生列表 根据学生姓名
/// </summary>
/// <param name="stuNames"></param>
/// <returns></returns>
public List<RB_Student> GetListForStuName(string stuNames)
{
string sql = $"select StudId,StudentName from RB_Student where StudentName in({stuNames}) order by StudId desc";
return Get<RB_Student>(sql).ToList();
}
}
}

using EduSpider.IRepository;
using EduSpider.IServices;
using EduSpider.Repository;
using EduSpider.Utility.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VTX.FW.Attr;
using VTX.FW.Helper;
namespace EduSpider.Services
{
/// <summary>
/// 考试服务实现
/// </summary>
public class ExamService : IExamService
{
/// <summary>
/// 帐号仓储接口
/// </summary>
[Autowired]
private IAccountRepository accountRepository { get; set; }
/// <summary>
/// 考试
/// </summary>
[Autowired]
private IExamRepository examRepository { get; set; }
/// <summary>
/// 考试题目
/// </summary>
[Autowired]
private IExam_QuestionsRepository exam_QuestionsRepository { get; set; }
/// <summary>
/// 考试得分
/// </summary>
[Autowired]
private IExam_ScoreRepository exam_ScoreRepository { get; set; }
/// <summary>
/// 学生
/// </summary>
[Autowired]
private IStudentRepository studentRepository { get; set; }
/// <summary>
/// 导入考试成绩
/// </summary>
/// <param name="path_server"></param>
/// <param name="userId"></param>
/// <returns></returns>
public string ImportExcelForStuExamScore(string path_server,int courseId, string examName, int userId)
{
var umodel = accountRepository.GetAccountList(new Model.Extend.RB_Account_Extend() { Id = userId }).FirstOrDefault();
if (umodel == null || umodel.Status == Utility.Enum.DateStateEnum.Delete || umodel.AccountType != Utility.Enum.AccountTypeEnum.Teacher) { return "没有权限操作"; }
var EQlist = StuExamScoreHelper.GetStuExamScoreData(path_server, out List<StuScoreModel> StuList);
if (EQlist.Any())
{
var AvgList = StuList.Where(x => x.Name == "平均分").ToList();
StuList = StuList.Where(x => x.Name != "平均分" && !string.IsNullOrWhiteSpace(x.Name)).ToList();
//根据学生姓名 查询所有的学生账号
string StuNames = "'" + string.Join("','", StuList.Select(x => x.Name).Distinct()) + "'";
var sList = studentRepository.GetListForStuName(StuNames);
//插入考试
int ExamId = examRepository.Insert(new Model.Entity.RB_Exam()
{
ExamId = 0,
CourseId = courseId,
ExamName = examName,
CreateBy = userId,
CreateTime = DateTime.Now,
Status = 0
});
if (ExamId > 0) {
List<Model.Entity.RB_Exam_Questions> InsertEQ = new();
//开始插入题目
foreach (var item in EQlist)
{
InsertEQ.Add(new Model.Entity.RB_Exam_Questions()
{
Id = 0,
ExamId = ExamId,
Difficulty = item.Difficulty,
KnowledgePoint = item.KnowledgePoint,
Module = item.Module,
Score = item.Score,
Sort = item.Id
});
}
exam_QuestionsRepository.BatchInsert(InsertEQ);
List<Model.Entity.RB_Exam_Score> InsertScore = new();
foreach (var Name in StuList.Select(x => x.Name).Distinct()) {
var clist = StuList.Where(x => x.Name == Name).ToList();
var stuModel = sList.Where(x => x.StudentName == Name).FirstOrDefault();
InsertScore.Add(new Model.Entity.RB_Exam_Score()
{
Id = 0,
ExamId = ExamId,
StuId = stuModel?.StudId ?? 0,//匹配学生失败 可能要在后台给与提示, 重新导入
StuName = Name,
Content = JsonHelper.Serialize(clist.Where(x => x.Id > 0).Select(x => new
{
Sort = x.Id,
x.Score,
AvgScore = AvgList.Where(y => y.Id == x.Id).FirstOrDefault()?.Score ?? 0
})),
TScore = clist.Where(x => x.Id == -1).FirstOrDefault()?.Score ?? 0,
Rank = Convert.ToInt32(clist.Where(x => x.Id == -2).FirstOrDefault()?.Score ?? 0),
RankRate = clist.Where(x => x.Id == -3).FirstOrDefault()?.Score ?? 0,
});
}
//InsertScore = InsertScore.Where(x => x.StuId > 0).ToList();//暂时只插入匹配到学生的
exam_ScoreRepository.BatchInsert(InsertScore);
}
return "";
}
else
{
return "模板匹配失败";
}
}
/// <summary>
/// 取消备份
/// </summary>
/// <param name="path_server"></param>
/// <param name="courseId"></param>
/// <param name="examName"></param>
/// <param name="userId"></param>
/// <returns></returns>
public string ImportExcelForStuExamScore_V2(string path_server, int courseId, string examName, int userId)
{
var umodel = accountRepository.GetAccountList(new Model.Extend.RB_Account_Extend() { Id = userId }).FirstOrDefault();
if (umodel == null || umodel.Status == Utility.Enum.DateStateEnum.Delete || umodel.AccountType != Utility.Enum.AccountTypeEnum.Teacher) { return "没有权限操作"; }
var EQlist = StuExamScoreHelper.GetStuExamScoreData(path_server, out List<StuScoreModel> StuList);
if (EQlist.Any())
{
var AvgList = StuList.Where(x => x.Name == "平均分").ToList();
StuList = StuList.Where(x => x.Name != "平均分" && !string.IsNullOrWhiteSpace(x.Name)).ToList();
//根据学生姓名 查询所有的学生账号
string StuNames = "'" + string.Join("','", StuList.Select(x => x.Name).Distinct()) + "'";
var sList = studentRepository.GetListForStuName(StuNames);
//插入考试
int ExamId = examRepository.Insert(new Model.Entity.RB_Exam()
{
ExamId = 0,
CourseId = courseId,
ExamName = examName,
CreateBy = userId,
CreateTime = DateTime.Now,
Status = 0
});
if (ExamId > 0)
{
List<Model.Entity.RB_Exam_Questions> InsertEQ = new();
//开始插入题目
foreach (var item in EQlist)
{
InsertEQ.Add(new Model.Entity.RB_Exam_Questions()
{
Id = 0,
ExamId = ExamId,
Difficulty = item.Difficulty,
KnowledgePoint = item.KnowledgePoint,
Module = item.Module,
Score = item.Score,
Sort = item.Id
});
}
exam_QuestionsRepository.BatchInsert(InsertEQ);
List<Model.Entity.RB_Exam_Score> InsertScore = new();
//开始插入得分
foreach (var item in StuList)
{
var stuModel = sList.Where(x => x.StudentName == item.Name).FirstOrDefault();
InsertScore.Add(new Model.Entity.RB_Exam_Score()
{
Id = 0,
ExamId = ExamId,
//Sort = item.Id,
StuId = stuModel?.StudId ?? 0,//=0表示未匹配上 暂时=0处理
//Score = item.Score,
StuName = item.Name
});
}
exam_ScoreRepository.BatchInsert(InsertScore);
}
return "";
}
else
{
return "模板匹配失败";
}
}
}
}

using EduSpider.IServices;
using EduSpider.Utility.Data;
using System;
using System.Collections.Generic;
using System.Linq;
......
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
namespace EduSpider.Utility.Data
{
/// <summary>
/// 学生成绩导入帮助类
/// </summary>
public class StuExamScoreHelper
{
/// <summary>
/// 根据Excel文件获取列表
/// </summary>
/// <param name="filePath"></param>
/// <returns></returns>
public static List<ExamQuestionModel> GetStuExamScoreData(string filePath, out List<StuScoreModel> StuList)
{
StuList = new List<StuScoreModel>();
var dt = NPOIHelper.ImportExcelToDatatable(filePath, 0, 0, true);
List<ExamQuestionModel> EQList = new List<ExamQuestionModel>();
if (dt != null && dt.Rows.Count > 0)
{
//先抓取 题目列表
for (var i = 1; i < 1000; i++)
{
if (dt.Columns.Contains(i.ToString()))
{
EQList.Add(new ExamQuestionModel()
{
Id = i,
Difficulty = dt.Rows[0][i.ToString()].ToString(),
KnowledgePoint = dt.Rows[1][i.ToString()].ToString(),
Module = dt.Rows[2][i.ToString()].ToString(),
Score = Convert.ToDecimal(dt.Rows[3][i.ToString()].ToString())
});
}
else
{
break;
}
}
if (EQList.Any())
{
int totalCount = dt.Rows.Count;
//从第5行 开始 是学生
for (var i = 4; i < totalCount; i++)
{
foreach (var item in EQList)
{
//先装姓名
StuList.Add(new StuScoreModel()
{
Name = dt.Rows[i]["题号"].ToString().Trim(),
Id = item.Id,
Score = Convert.ToDecimal(dt.Rows[i][item.Id.ToString()].ToString())
});
}
if (i < totalCount - 1)
{
//总分 排名 百分比排名
StuList.Add(new StuScoreModel()
{
Name = dt.Rows[i]["题号"].ToString().Trim(),
Id = -1,
Score = Convert.ToDecimal(dt.Rows[i]["总分"].ToString())
});
StuList.Add(new StuScoreModel()
{
Name = dt.Rows[i]["题号"].ToString().Trim(),
Id = -2,
Score = Convert.ToDecimal(dt.Rows[i]["排名"].ToString())
});
StuList.Add(new StuScoreModel()
{
Name = dt.Rows[i]["题号"].ToString().Trim(),
Id = -3,
Score = Convert.ToDecimal(dt.Rows[i]["百分比排名"].ToString())
});
}
}
}
}
return EQList;
}
}
/// <summary>
/// 考题
/// </summary>
public class ExamQuestionModel {
/// <summary>
/// 题目编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 难度
/// </summary>
public string Difficulty { get; set; }
/// <summary>
/// 知识点
/// </summary>
public string KnowledgePoint{ get; set; }
/// <summary>
/// 归属模块
/// </summary>
public string Module { get; set; }
/// <summary>
/// 分数
/// </summary>
public decimal Score { get; set; }
}
/// <summary>
/// 学生成绩
/// </summary>
public class StuScoreModel {
/// <summary>
/// 学生姓名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 考题编号
/// </summary>
public int Id { get; set; }
/// <summary>
/// 得分
/// </summary>
public decimal Score { get; set; }
}
}
......@@ -8,6 +8,7 @@
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.1" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="NPOI" Version="2.5.6" />
<PackageReference Include="VTX.FW" Version="1.1.0" />
</ItemGroup>
......
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula.Eval;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using VTX.FW.Helper;
namespace EduSpider.Utility
{
/// <summary>
/// npoi帮助类
/// </summary>
public class NPOIHelper
{
#region datatable中将数据导出到excel
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
[Obsolete]
static MemoryStream ExportDataTable(DataTable dtSource, String strHeaderText)
{
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.CreateSheet() as HSSFSheet;
HSSFCellStyle dateStyle = workbook.CreateCellStyle() as HSSFCellStyle;
HSSFDataFormat format = workbook.CreateDataFormat() as HSSFDataFormat;
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).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(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet() as HSSFSheet;
}
#region 表头及样式
{
HSSFRow headerRow = sheet.CreateRow(0) as HSSFRow;
headerRow.HeightInPoints = 25;
headerRow.CreateCell(0).SetCellValue(strHeaderText);
HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = workbook.CreateFont() as HSSFFont;
font.FontHeightInPoints = 20;
font.Boldweight = 700;
headStyle.SetFont(font);
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));
}
#endregion
#region 列头及样式
{
HSSFRow headerRow = sheet.CreateRow(1) as HSSFRow;
HSSFCellStyle headStyle = workbook.CreateCellStyle() as HSSFCellStyle;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
HSSFFont font = workbook.CreateFont() as HSSFFont;
font.FontHeightInPoints = 10;
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);
}
//headerRow.Dispose();
}
#endregion
rowIndex = 2;
}
#endregion
#region 填充内容
HSSFRow dataRow = sheet.CreateRow(rowIndex) as HSSFRow;
foreach (DataColumn column in dtSource.Columns)
{
HSSFCell newCell = dataRow.CreateCell(column.Ordinal) as HSSFCell;
String drValue = row[column].ToString();
switch (column.DataType.ToString())
{
case "System.String": //字符串类型
double result;
if (IsNumeric(drValue, out result))
{
double.TryParse(drValue, out result);
newCell.SetCellValue(result);
break;
}
else
{
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++;
}
using MemoryStream ms = new MemoryStream();
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
return ms;
}
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="fs">文件流</param>
[Obsolete]
static void ExportDataTableI(DataTable dtSource, String strHeaderText, FileStream fs)
{
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.CreateSheet() as XSSFSheet;
#region 右击文件 属性信息
//{
// DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
// dsi.Company = "http://www.yongfa365.com/";
// workbook.DocumentSummaryInformation = dsi;
// SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
// si.Author = "柳永法"; //填加xls文件作者信息
// si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
// si.LastAuthor = "柳永法2"; //填加xls文件最后保存者信息
// si.Comments = "说明信息"; //填加xls文件作者信息
// si.Title = "NPOI测试"; //填加xls文件标题信息
// si.Subject = "NPOI测试Demo"; //填加文件主题信息
// si.CreateDateTime = DateTime.Now;
// workbook.SummaryInformation = si;
//}
#endregion
XSSFCellStyle dateStyle = workbook.CreateCellStyle() as XSSFCellStyle;
XSSFDataFormat format = workbook.CreateDataFormat() as XSSFDataFormat;
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");
//取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).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(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 0)
{
#region 表头及样式
//{
// XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow;
// headerRow.HeightInPoints = 25;
// headerRow.CreateCell(0).SetCellValue(strHeaderText);
// XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle;
// headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
// XSSFFont font = workbook.CreateFont() as XSSFFont;
// font.FontHeightInPoints = 20;
// font.Boldweight = 700;
// headStyle.SetFont(font);
// headerRow.GetCell(0).CellStyle = headStyle;
// //sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));
// //headerRow.Dispose();
//}
#endregion
#region 列头及样式
{
XSSFRow headerRow = sheet.CreateRow(0) as XSSFRow;
XSSFCellStyle headStyle = workbook.CreateCellStyle() as XSSFCellStyle;
headStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
XSSFFont font = workbook.CreateFont() as XSSFFont;
font.FontHeightInPoints = 10;
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);
}
//headerRow.Dispose();
}
#endregion
rowIndex = 1;
}
#endregion
#region 填充内容
XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow;
foreach (DataColumn column in dtSource.Columns)
{
XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell;
String drValue = row[column].ToString();
switch (column.DataType.ToString())
{
case "System.String": //字符串类型
double result;
if (IsNumeric(drValue, out result))
{
double.TryParse(drValue, out result);
newCell.SetCellValue(result);
break;
}
else
{
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++;
}
workbook.Write(fs);
fs.Close();
}
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置(路径+文件名)</param>
[Obsolete]
public static void ExportDataTableToExcel(DataTable dtSource, String strHeaderText, String strFileName)
{
String[] temp = strFileName.Split('.');
if (temp[^1] == "xls" && dtSource.Columns.Count < 256 && dtSource.Rows.Count < 65536)
{
using MemoryStream ms = ExportDataTable(dtSource, strHeaderText);
using FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write);
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
else
{
if (temp[^1] == "xls")
strFileName += "x";
using FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write);
ExportDataTableI(dtSource, strHeaderText, fs);
}
}
#endregion
#region excel文件中将数据导出到datatable
/// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="SheetIndex">需要导出的sheet序号</param>
/// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
/// <param name="needHeader">列头</param>
/// <returns></returns>
public static DataTable ImportExcelToDatatable(String strFileName, int SheetIndex, int HeaderRowIndex, bool needHeader)
{
IWorkbook wb;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
wb = WorkbookFactory.Create(file);
}
ISheet sheet = wb.GetSheetAt(SheetIndex);
DataTable table = ImportDataTable(sheet, HeaderRowIndex, needHeader);
return table;
}
/// <summary>
/// 将制定sheet中的数据导出到datatable中
/// </summary>
/// <param name="sheet">需要导出的sheet</param>
/// <param name="HeaderRowIndex">列头所在行号,-1表示没有列头</param>
/// <param name="needHeader">是否导出表头</param>
/// <returns></returns>
static DataTable ImportDataTable(ISheet sheet, int HeaderRowIndex, bool needHeader)
{
DataTable table = new DataTable();
IRow headerRow;
int cellCount;
try
{
if (HeaderRowIndex < 0 || !needHeader)
{
headerRow = sheet.GetRow(0);
cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
}
}
else
{
headerRow = sheet.GetRow(HeaderRowIndex);
cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
if (headerRow.GetCell(i) == null)
{
if (table.Columns.IndexOf(Convert.ToString(i)) > 0)
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
}
}
else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > 0)
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
table.Columns.Add(column);
}
}
}
int rowCount = sheet.LastRowNum;
for (int i = (HeaderRowIndex + 1); i <= sheet.LastRowNum; i++)
{
try
{
IRow row;
if (sheet.GetRow(i) == null)
{
row = sheet.CreateRow(i);
}
else
{
row = sheet.GetRow(i);
}
DataRow dataRow = table.NewRow();
for (int j = row.FirstCellNum; j <= cellCount; j++)
{
try
{
if (row.GetCell(j) != null)
{
switch (row.GetCell(j).CellType)
{
case CellType.String:
String str = row.GetCell(j).StringCellValue;
if (str != null && str.Length > 0)
{
dataRow[j] = str.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
{
dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
}
else
{
dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
}
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
case CellType.Formula:
switch (row.GetCell(j).CachedFormulaResultType)
{
case CellType.String:
String strFORMULA = row.GetCell(j).StringCellValue;
if (strFORMULA != null && strFORMULA.Length > 0)
{
dataRow[j] = strFORMULA.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
default:
dataRow[j] = "";
break;
}
break;
default:
dataRow[j] = "";
break;
}
}
}
catch (Exception exception)
{
LogHelper.WriteError("ImportDataTable", "ImportDataTable_1", exception);
}
}
table.Rows.Add(dataRow);
}
catch (Exception exception)
{
LogHelper.WriteError("ImportDataTable", "ImportDataTable_2", exception);
}
}
}
catch (Exception exception)
{
LogHelper.WriteError("ImportDataTable", "ImportDataTable_3", exception);
}
return table;
}
/// <summary>
/// Excel转DataSet
/// </summary>
/// <param name="excelPath"></param>
/// <returns></returns>
public static DataSet ExcelToDataSet(string excelPath)
{
return ExcelToDataSet(excelPath, true, out int sheetCount);
}
/// <summary>
/// Excel转DataSet
/// </summary>
/// <param name="excelPath"></param>
/// <param name="firstRowAsHeader"></param>
/// <param name="sheetCount"></param>
/// <returns></returns>
static DataSet ExcelToDataSet(string excelPath, bool firstRowAsHeader, out int sheetCount)
{
using DataSet ds = new DataSet();
using FileStream fileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read);
string extFile = Path.GetExtension(excelPath).ToLower();
IWorkbook workbook;
if (extFile.Equals(".xls"))
{
workbook = new HSSFWorkbook(fileStream);
HSSFFormulaEvaluator evaluator = new HSSFFormulaEvaluator(workbook);
sheetCount = workbook.NumberOfSheets;
for (int i = 0; i < sheetCount; ++i)
{
HSSFSheet sheet = workbook.GetSheetAt(i) as HSSFSheet;
DataTable dt = ImportDataTable(sheet, 0, firstRowAsHeader);
dt.TableName = workbook.GetSheetName(i);
ds.Tables.Add(dt);
}
return ds;
}
else
{
workbook = new XSSFWorkbook(fileStream);
XSSFFormulaEvaluator evaluator = new XSSFFormulaEvaluator(workbook);
sheetCount = workbook.NumberOfSheets;
for (int i = 0; i < sheetCount; ++i)
{
XSSFSheet sheet = workbook.GetSheetAt(i) as XSSFSheet;
DataTable dt = ImportDataTable(sheet, 0, firstRowAsHeader);
dt.TableName = workbook.GetSheetName(i);
ds.Tables.Add(dt);
}
return ds;
}
}
#endregion
/// <summary>
/// 判断是否为数字
/// </summary>
/// <param name="message"></param>
/// <param name="result"></param>
/// <returns></returns>
public static bool IsNumeric(String message, out double result)
{
Regex rex = new Regex(@"^[-]?\d+[.]?\d*$");
result = -1;
if (rex.IsMatch(message))
{
result = double.Parse(message);
return true;
}
else
return false;
}
/// <summary>
/// excel 指定行插入数据
/// </summary>
/// <param name="dtSource"></param>
/// <param name="SheetName"></param>
/// <param name="Path"></param>
/// <param name="NewPath"></param>
/// <param name="rowIndex"></param>
/// <param name="FontName"></param>
/// <param name="FontHeight"></param>
/// <param name="height"></param>
public static void ExportInsert(DataTable dtSource, string SheetName, string Path, string NewPath, int rowIndex = 0, string FontName = "宋体", double FontHeight = 0, short height = 0)
{
FileStream file = new FileStream(Path, FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.GetSheet(SheetName) as XSSFSheet;
foreach (DataRow row in dtSource.Rows)
{
#region 填充内容
XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow;
if (height > 0)
{
dataRow.Height = height;
}
foreach (DataColumn column in dtSource.Columns)
{
XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell;
ICellStyle style = workbook.CreateCellStyle();
style.WrapText = true;//自动换行
IFont font = workbook.CreateFont();
font.FontName = FontName;
if (FontHeight > 0)
{
font.FontHeight = FontHeight;
}
style.SetFont(font);
style.Alignment = HorizontalAlignment.Center;
newCell.CellStyle = style;
String drValue = row[column].ToString();
newCell.SetCellValue(drValue);
}
#endregion
rowIndex++;
}
FileStream out1 = new FileStream(NewPath, FileMode.Create);
workbook.Write(out1);
workbook.Close();
out1.Close();
}
/// <summary>
/// 测试插入数据 月度考勤专用
/// </summary>
/// <param name="dtSource"></param>
/// <param name="SheetName"></param>
/// <param name="Path"></param>
/// <param name="NewPath"></param>
/// <param name="rowIndex"></param>
/// <param name="FontName"></param>
/// <param name="FontHeight"></param>
/// <param name="height"></param>
public static void ExportInsertAndMergeCells(DataTable dtSource, string SheetName, string Path, string NewPath, int rowIndex = 0, string FontName = "宋体", double FontHeight = 0, short height = 0)
{
FileStream file = new FileStream(Path, FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.GetSheet(SheetName) as XSSFSheet;
string OldDepStr = "";
int startNum = rowIndex;
int EndNum = dtSource.Rows.Count + rowIndex;
foreach (DataRow row in dtSource.Rows)
{
#region 填充内容
XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow;
if (height > 0)
{
dataRow.Height = height;
}
foreach (DataColumn column in dtSource.Columns)
{
XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell;
ICellStyle style = workbook.CreateCellStyle();
style.WrapText = true;//自动换行
IFont font = workbook.CreateFont();
font.FontName = FontName;
if (FontHeight > 0)
{
font.FontHeight = FontHeight;
}
style.SetFont(font);
style.Alignment = HorizontalAlignment.Center;
style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center;
newCell.CellStyle = style;
String drValue = row[column].ToString();
newCell.SetCellValue(drValue);
}
#endregion
//合并单元格
if (row["部门"].ToString() != OldDepStr)
{
OldDepStr = row["部门"].ToString();
if (OldDepStr == "")
{
var region = new CellRangeAddress(startNum, rowIndex - 1, 2, 2);
sheet.AddMergedRegion(region);
startNum = rowIndex;
}
else
{
if (startNum != rowIndex)
{
if (OldDepStr != "")
{
var region = new CellRangeAddress(startNum, rowIndex - 1, 2, 2);
sheet.AddMergedRegion(region);
}
else
{
startNum = rowIndex + 1;
}
startNum = rowIndex;
}
}
}
else
{
if (OldDepStr == "")
{
startNum = rowIndex + 1;
}
}
rowIndex++;
//最后一条数据
if (EndNum == rowIndex && startNum != rowIndex)
{
var region = new CellRangeAddress(startNum, rowIndex - 1, 2, 2);
sheet.AddMergedRegion(region);
}
}
FileStream out1 = new FileStream(NewPath, FileMode.Create);
workbook.Write(out1);
workbook.Close();
out1.Close();
}
/// <summary>
/// excel 指定行插入数据(客户线索专用)
/// </summary>
/// <param name="dtSource"></param>
/// <param name="SheetName"></param>
/// <param name="Path"></param>
/// <param name="NewPath"></param>
/// <param name="rowIndex"></param>
public static void CustomerExportInsert(DataTable dtSource, string SheetName, string Path, string NewPath, int rowIndex = 0)
{
FileStream file = new FileStream(Path, FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.GetSheet(SheetName) as XSSFSheet;
foreach (DataRow row in dtSource.Rows)
{
#region 填充内容
var rowSource = sheet.GetRow(rowIndex);
var cellSource = rowSource.GetCell(0);//都以第一列的样式复制
XSSFRow dataRow = sheet.CreateRow(rowIndex) as XSSFRow;
dataRow.Height = 500;
foreach (DataColumn column in dtSource.Columns)
{
XSSFCell newCell = dataRow.CreateCell(column.Ordinal) as XSSFCell;
newCell.CellStyle = cellSource.CellStyle;
String drValue = row[column].ToString();
newCell.SetCellValue(drValue);
}
#endregion
rowIndex++;
}
FileStream out1 = new FileStream(NewPath, FileMode.Create);
workbook.Write(out1);
workbook.Close();
out1.Close();
}
}
}
\ No newline at end of file
using EduSpider.IServices;
using EduSpider.WebApi.Controllers.Base;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using VTX.FW.Api;
using VTX.FW.Attr;
using VTX.FW.Helper;
using EduSpider.Utility;
using System.Threading;
using EduSpider.Model.Extend;
using System.Linq;
using JWT;
using System;
using System.Collections.Generic;
using JWT.Algorithms;
using JWT.Serializers;
using System.IO;
using Microsoft.AspNetCore.Cors;
namespace EduSpider.WebApi.Controllers
{
/// <summary>
/// 上传文件
/// </summary>
[EnableCors("AllowCors")]
[Route("api/[controller]/[action]")]
[ApiController]
public class UploadController : ControllerBase
{
/// <summary>
/// 考试
/// </summary>
[Autowired]
public IExamService examService { get; set; }
/// <summary>
/// 导入考试成绩
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public ApiResult UploadStuExamScore()
{
try
{
var files = Request.Form.Files;
if (files.Count == 0)
{
return new ApiResult { Code = (int)ResultCode.Fail, Message = "未选择文件", Data = "" };
}
var json = !string.IsNullOrEmpty(Request.Form["params"]) ? JObject.Parse(Request.Form["params"].ToString()) : null;
int UserId = Convert.ToInt32(json["Uid"] != null ? json["Uid"].ToString() : "0");
int CourseId = Convert.ToInt32(json["CourseId"] != null ? json["CourseId"].ToString() : "0");
string ExamName = json["ExamName"] != null ? json["ExamName"].ToString() : "";
string filename = files[0].FileName;
string fileExtention = System.IO.Path.GetExtension(files[0].FileName);
//验证文件格式
List<string> ExtList = new() {
".xls",
".xlsx"
};
if (!ExtList.Contains(fileExtention))
{
return new ApiResult { Code = (int)ResultCode.Fail, Message = "文件格式有误", Data = "" };
}
if (files[0].Length <= 0)
{
return new ApiResult { Code = (int)ResultCode.Fail, Message = "文件大小有误", Data = "" };
}
decimal fileMNum = files[0].Length / (1024 * 1024);
if (fileMNum > 10) { return ApiResult.Failed("文件不能超过10M"); }
string path = Guid.NewGuid().ToString() + fileExtention;
string basepath = AppContext.BaseDirectory;
string dateStr = DateTime.Now.ToString("yyyyMMdd");
string tempPath = basepath + "upfile\\temporary\\" + dateStr + "\\";
string path_server = tempPath + path;
string httpPath = "/upfile/temporary/" + dateStr + "/" + path;
if (!Directory.Exists(tempPath))
{
Directory.CreateDirectory(tempPath);
}
using (FileStream fstream = new(path_server, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
files[0].CopyTo(fstream);
}
#region 解析文档数据并保存
string rmsg = examService.ImportExcelForStuExamScore(path_server, CourseId, ExamName, UserId);
if (rmsg == "")
{
return ApiResult.Success();
}
else
{
return ApiResult.Failed(rmsg);
}
#endregion
}
catch (Exception ex)
{
LogHelper.WriteError("UploadStuExamScore", "", ex);
return ApiResult.Failed();
}
}
/// <summary>
/// 导入考试成绩
/// </summary>
/// <returns></returns>
[HttpPost]
[AllowAnonymous]
public ApiResult UploadStuExamScore_Test()
{
try
{
string path_server = "C:/Users/Administrator/Desktop/TempFile/化学成绩查询表.xlsx";
#region 解析文档数据并保存
string rmsg = examService.ImportExcelForStuExamScore(path_server, 44977497, "测试一下化学", 11759328);
if (rmsg == "")
{
return ApiResult.Success();
}
else
{
return ApiResult.Failed(rmsg);
}
#endregion
}
catch (Exception ex)
{
LogHelper.WriteError("UploadStuExamScore", "", ex);
return ApiResult.Failed();
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment