当前位置:网站首页>C import Xls data method summary V (complete code)
C import Xls data method summary V (complete code)
2022-07-04 01:11:00 【Xiao Zhong wants to learn!!!】
C# Import .xls Data method summary V ( Complete code )
explain :
This code is only for my personal review and release for easy viewing
I won't elaborate on the last save below , Because back to the metropolis , No, I won't even speak
The saving of uploaded data is mainly related to the database fields you set , It's OK to see whether the data matches
public ActionResult ImportExcel(HttpPostedFileBase excelFile)
{
ReturnJson returnJson = new ReturnJson();
int saveCount = 0;
// Idea of batch import data
// 1、 Get the read file -> Determine if the data type is correct ;
// 2、 Convert files to binary arrays ;
// 3、 Convert binary array into memory stream ;
// 4、 utilize NPOI Read the data in the memory stream into Excel
try
{
// Get file suffix
string fileExtension = Path.GetExtension(excelFile.FileName);
// Judge whether the document is excel form
if (".xls".Equals(fileExtension.ToLower()) || ".xlsx".Equals(fileExtension.ToLower()))
{
// Declare the binary array to store the file
byte[] fileBytes = new byte[excelFile.ContentLength];
// Convert the file into binary data group and store it in fileBytes
excelFile.InputStream.Read(fileBytes, 0, excelFile.ContentLength);
// Convert binary array into memory stream
MemoryStream excelFileStream = new MemoryStream(fileBytes);
// Convert memory stream to workbooks
IWorkbook workbook = new HSSFWorkbook(excelFileStream);
// Determine if there are worksheets in the workbook
if (workbook.NumberOfSheets > 0)
{
// Query out college , major , grade , class Information about : It is used to get the corresponding ID
List<SYS_Academe> dbAcademe = myModel.SYS_Academe.ToList();
List<SYS_Specialty> dbSpecialty = myModel.SYS_Specialty.ToList();
List<SYS_Grade> dbGrade = myModel.SYS_Grade.ToList();
List<SYS_Class> dbClass = myModel.SYS_Class.ToList();
// establish studentVo The object list -》 Used to store imported students / User data
List<studentVo> listStudentVo = new List<studentVo>();
// Get the first sheet
ISheet sheet = workbook.GetSheetAt(0);
// Determine whether there is data in the worksheet
//PhysicalNumberOfRows Number of physical rows obtained , Not including those empty lines ( Interlace ) The situation of
if (sheet.PhysicalNumberOfRows > 0)
{
#region take Excel Table data into DataTable in
// Load data into datatable in
// Definition datatable
DataTable dtExcel = new DataTable();
// Gets the second row in the worksheet ( The first line is the description , The index for 0)
IRow rowHeader = sheet.GetRow(1);
/* FirstCellNum: Gets the subscript of the first cell in a row LastCellNum: Get the number of columns in a row FirstRowNum: Get the subscript of the first actual row LastRowNum: Get the subscript of the last actual line */
// Get the number of table columns
int cellCount = rowHeader.LastCellNum;
// Get the number of table rows
int rowCount = sheet.LastRowNum + 1;
// Cycle through the values of each cell in the header row -- It is equivalent to defining the fields of the database table
for (var i = rowHeader.FirstCellNum; i < cellCount; i++)
{
// establish dataTable Column in
// By traversing each cell in the row , Get the data of each cell in the header row
DataColumn dtColumn = new DataColumn(rowHeader.GetCell(i).StringCellValue);
// Put the data of the obtained Title row into datatable in ;
dtExcel.Columns.Add(dtColumn);
}
// obtain Excel Data rows in the table
//(sheet.FirstRowNum) The first line is the description ; The second line is the title ; The third line starts with the data information
for (var j = sheet.FirstRowNum + 2; j < rowCount; j++)
{
// Get data row (3,4,5,6,......) data
IRow row = sheet.GetRow(j);
// establish DataTable That's ok
DataRow dtRow = dtExcel.NewRow();
if (row != null)
{
// De blank line variable
bool isNull = true;
// Traverse all cells in a row , fill dtRow in
for (var n = row.FirstCellNum; n < cellCount; n++)
{
if (row.GetCell(n) != null)
{
string cellVal = row.GetCell(n).ToString();
dtRow[n] = cellVal;
// Go to the airport , If there are non empty cells in the row , Variable isNull by false, Otherwise true
if (!string.IsNullOrEmpty(cellVal))
{
isNull = false;
}
}
}
if (!isNull)
{
// take b Non empty data row dtRow fill dtExcel in
dtExcel.Rows.Add(dtRow);
}
}
}
#endregion
#region Handle DataTable Data in
// above , take Excel All the data in the table is written in dtExcel in
// The next step is before adding to the database , Processing of data in each column of the table
// Traverse dtExcel Every row of data in , According to the college name filled in 、 Grade name 、 The specialty name matches the corresponding ID
for (int i = 0; i < dtExcel.Rows.Count; i++)
{
DataRow row = dtExcel.Rows[i];
// establish studentVo object , Save the data of each student traversed
studentVo studentVo = new studentVo();
// Query the college according to its name ID
string academeName = row[" college "].ToString().Trim();
try
{
studentVo.AcademeID = dbAcademe.Single(m => m.AcademeName == academeName).AcademeID;
}
catch (Exception e)
{
returnJson.Text = string.Format(" The first {0} Of a student college Information matching error , Please check ", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
// Query the major according to the major name ID
string specialtyName = row[" major "].ToString().Trim();
try
{
studentVo.SpecialtyID = dbSpecialty.Single(m => m.AcademeID == studentVo.AcademeID &&
m.SpecialtyName == specialtyName).SpecialtyID;
}
catch (Exception e)
{
returnJson.Text = string.Format(" The first {0} Of a student major Information matching error , Please check ", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
// Query major according to grade name ID
string gradeName = row[" grade "].ToString().Trim();
try
{
studentVo.GradeID = dbGrade.Single(m => m.AcademeID == studentVo.AcademeID &&
m.GradeName == gradeName).GradeID;
}
catch (Exception e)
{
returnJson.Text = string.Format(" The first {0} Of a student grade Information matching error , Please check ", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
// Query the major according to the class name ID
string className = row[" class "].ToString().Trim();
try
{
studentVo.ClassID = dbClass.Single(m => m.AcademeID == studentVo.AcademeID &&
m.SpecialtyID == studentVo.SpecialtyID &&
m.GradeID == studentVo.GradeID &&
m.ClassName == className).ClassID;
}
catch (Exception e)
{
returnJson.Text = string.Format(" The first {0} Of a student class Information matching error , Please check ", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
// Authentication ID No
if (!IdCardHelper.CheckIdCard(row[" ID number "].ToString().Trim()))
{
returnJson.Text = string.Format(" The first {0} The ID card information of students is wrong , Please check ", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
// Student ID , full name , ID number & Gender information filling object student
studentVo.StudentNumber = row[" Student number "].ToString().Trim();
studentVo.StudentName = row[" full name "].ToString().Trim();
studentVo.StudentIDNum = row[" ID number "].ToString().Trim();
studentVo.StudentSex = row[" Gender "].ToString().Trim();
studentVo.UniformAuthenticationCode = row[" Unified authentication code "].ToString().Trim();
// Add each piece of student information to studentVo Object list
listStudentVo.Add(studentVo);
}
#endregion
#region To repeat
#region Compare between imported data , To judge whether or not to repeat
// Place data in myListStudentVo China and listStudentVo Compare the data in
List<studentVo> myListStudentVo = new List<studentVo>();
// Judge whether there are duplicates in the information imported into students
for (int i = 0; i < listStudentVo.Count; i++)
{
if (i != 0)
{
for (int j = 0; j < myListStudentVo.Count; j++)
{
if (listStudentVo[i].StudentIDNum.Trim() == myListStudentVo[j].StudentIDNum.Trim() ||
listStudentVo[i].StudentNumber.Trim() == myListStudentVo[j].StudentNumber.Trim() ||
listStudentVo[i].UniformAuthenticationCode.Trim() == myListStudentVo[j].UniformAuthenticationCode.Trim())
{
returnJson.Text = string.Format("Excel Page in the table {0} Duplicate data with other data ,<br> Please check the ID number. 、 Student number and unified authentication code !", i + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
myListStudentVo.Add(listStudentVo[i]);
}
else
{
// The first data is directly put into myListStudentVo in
myListStudentVo.Add(listStudentVo[0]);
}
}
#endregion
#region Comparison of imported data with database , To judge whether or not to repeat
// Query student table & Data from user tables
List<PW_Student> dbListStudent = myModel.PW_Student.ToList();
List<PW_User> dbListUser = myModel.PW_User.ToList();
// Judge whether the imported data is duplicate with the data in the database
// Traverse imported data
for (int n = 0; n < listStudentVo.Count; n++)
{
// Traverse database student data
for (int m = 0; m < dbListStudent.Count; m++)
{
if (listStudentVo[n].StudentIDNum == dbListStudent[m].StudentIDNum ||
listStudentVo[n].StudentNumber == dbListStudent[m].StudentNumber)
{
returnJson.Text = string.Format("Excel Page in the table {0} Duplicate student data and database data ,<br> Please check the ID card number and student ID number. !", n + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
// Traverse database user data
for (int k = 0; k < dbListUser.Count; k++)
{
if (listStudentVo[n].UniformAuthenticationCode == dbListUser[k].UniformAuthenticationCode)
{
returnJson.Text = string.Format("Excel Page in the table {0} Student authentication codes already exist , Please check !", n + 1);
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
}
#endregion
#endregion
#region preservation
// Adding multiple pieces of data , Open transaction , Only when all data is successfully added can the transaction be committed , Otherwise, roll back
// Ensure data integrity
using (TransactionScope scope = new TransactionScope())
{
// Data table addition order : User table => Student list => Role schedule
// Traverse listStudentVo list
foreach (studentVo student in listStudentVo)
{
// Create a user table object
PW_User dbUser = new PW_User();
dbUser.UniformAuthenticationCode = student.UniformAuthenticationCode;
dbUser.UserNuber = student.StudentNumber;
dbUser.Password = Common.AESEncryptHelper.Encrypt(student.StudentNumber);
dbUser.ToVoidNo = true;
// newly added , preservation
myModel.PW_User.Add(dbUser);
if (myModel.SaveChanges() > 0)
{
// Get users ID
var userId = dbUser.UserID;
// Create a student table object
PW_Student dbStudent = new PW_Student();
dbStudent.UserID = userId;
dbStudent.ClassID = student.ClassID;
dbStudent.GradeID = student.GradeID;
dbStudent.SpecialtyID = student.SpecialtyID;
dbStudent.AcademeID = student.AcademeID;
dbStudent.StudentName = student.StudentName;
dbStudent.StudentSex = student.StudentSex;
dbStudent.StudentIDNum = student.StudentIDNum;
dbStudent.StudentNumber = student.StudentNumber;
dbStudent.StudentState = " This year's session ";
// Save new
myModel.PW_Student.Add(dbStudent);
if (myModel.SaveChanges() > 0)
{
// Create user role schedule objects
PW_UserRoleDetail dbUserRoleDetail = new PW_UserRoleDetail();
dbUserRoleDetail.UserID = userId;
dbUserRoleDetail.UserTypeID = 6;//1- Super administrator ;4- Teachers' ;6- Student ;7- College Counselor
// newly added , preservation
myModel.PW_UserRoleDetail.Add(dbUserRoleDetail);
if (myModel.SaveChanges() > 0)
{
saveCount++;
}
else
{
returnJson.Text = " Failed to add user role , Please check !";
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
else
{
returnJson.Text = " Student addition failed , Please check !";
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
else
{
returnJson.Text = " Failed to add user , Please check !";
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
// Judge saveCount Is the value of listStudentVo Number of data
if (saveCount == listStudentVo.Count)
{
// Commit transaction
scope.Complete();
// Successful import
returnJson.State = true;
returnJson.Text = " Successful import !";
}
else
{
returnJson.Text = " Import failed , Please check !";
}
}
#endregion
}
else {
returnJson.Text = " The worksheet is empty , Please check !";
}
}
else {
returnJson.Text = " There are no worksheets in the workbook , Please check !";
}
}
else {
returnJson.Text = " Wrong file type Uploaded , Please check !";
}
}
catch (Exception e)
{
Console.WriteLine(e);
returnJson.Text = " Data exception :"+e;
}
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
There are many ways to import data , This is just one of them , When the data is repeated, the data will not be imported , It is also a major drawback .
Another import is , The non duplicate data is still saved into your database , If it is repeated, it will reply uniformly again. Where do you have data duplication , Therefore, there is no one size fits all for non duplicate data
边栏推荐
- Understanding of Radix
- 基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
- MySQL uses the view to report an error, explain/show can not be issued; lacking privileges for underlying table
- 功能:编写函数fun求s=1^k+2^k +3^k + ......+N^k的值, (1的K次方到N的K次方的累加和)。
- It is worthy of "Alibaba internal software test interview notes" from beginning to end, all of which are essence
- 不得不会的Oracle数据库知识点(二)
- Characteristics of ginger
- Analysis and solution of lazyinitializationexception
- 我管你什么okr还是kpi,PPT轻松交给你
- Mobile asynchronous sending SMS verification code solution -efficiency+redis
猜你喜欢
In the process of seeking human intelligent AI, meta bet on self supervised learning
How to use AHAS to ensure the stability of Web services?
Pytest unit test framework: simple and easy to use parameterization and multiple operation modes
Audio resource settings for U3D resource management
CLP information - how does the digital transformation of credit business change from star to finger?
String hash, find the string hash value after deleting any character, double hash
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
打印菱形图案
2-Redis架构设计到使用场景-四种部署运行模式(下)
机器学习基础:用 Lasso 做特征选择
随机推荐
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
Ka! Why does the seat belt suddenly fail to pull? After reading these pictures, I can't stop wearing them
Print diamond pattern
be based on. NETCORE development blog project starblog - (14) realize theme switching function
Swagger2 quick start and use
Msp32c3 board connection MSSQL method
[dynamic programming] leetcode 53: maximum subarray sum
长文综述:大脑中的熵、自由能、对称性和动力学
Unity Shader入门精要读书笔记 第三章 Unity Shader基础
AI helps make new breakthroughs in art design plagiarism retrieval! Professor Liu Fang's team paper was employed by ACM mm, a multimedia top-level conference
A little understanding of GSLB (global server load balance) technology
PMP 考试常见工具与技术点总结
Delete all elements with a value of Y. The values of array elements and y are entered by the main function through the keyboard.
不得不会的Oracle数据库知识点(三)
The super fully automated test learning materials sorted out after a long talk with a Tencent eight year old test all night! (full of dry goods
Some other configurations on Huawei's spanning tree
[software testing] you haven't mastered these real interview questions of big companies?
Summary of JWT related knowledge
The first training of wechat applet
不得不会的Oracle数据库知识点(四)