当前位置:网站首页>Cases of addition, deletion, modification and search of C # learning for two years and C # import and export (de duplication)
Cases of addition, deletion, modification and search of C # learning for two years and C # import and export (de duplication)
2022-06-24 22:56:00 【Xiao Zhong wants to learn!!!】
C# Study two years of addition, deletion, modification, inspection and C# Import and export ( duplicate removal ) Case study
Preface :
I haven't written for nearly a week , I must remember the support of all like-minded friends , Thank you for watching.
Technology stack :
development language :C#、.net、C#mvc project
Front end development framework :axios、ElementUI frame
development tool :
Compiler tools :VS2022
database :SQLServer
Case needs analysis :
1、 The front page is simple and objective
2、 Data addition, deletion, modification and query
3、 complete Excel Data import and export function , Importing data requires repeated judgment ( Self judgment of uploaded data 、 Upload data and database judgment )
4、 Export data : You can export all at once , You can query and export the data that displays the current page according to the specified conditions
5、 All requests go through axios Development
Project realization diagram

1、 Data design

The design of the database is simple , It's all a one-to-one relationship , No intermediate table operation , This case does not realize the 4 Add, delete, modify and query the foreign key table , Please write in the database
2、 Add material data

The front-end code for model, saving and verification of newly added material data is as follows :
// Written in data Within the function
// Add form data
formData: {
},
// Form validation rules
rules: {
matter_name: [
{
required: true, message: ' Please fill in the material name ', trigger: 'blur' }
],
matter_code: [
{
required: true, message: ' Please enter the item number ', trigger: 'blur' }
],
product_type_id: [
{
required: true, message: ' Please select product type ', trigger: 'change' }
],
the_winning_type_id: [
{
required: true, message: ' Please select the bid winning type ', trigger: 'change' }
],
purchase_price: [
{
required: true, message: ' Please enter purchase price ', trigger: 'blur' }
],
Selling_price: [
{
required: true, message: ' Please enter the selling price ', trigger: 'blur' }
],
franchiser_id: [
{
required: true, message: ' Please select a dealer ', trigger: 'change' }
],
manufacturer_id: [
{
required: true, message: ' Please select the manufacturer ', trigger: 'change' }
]
}
// Submission method
// Add material preservation event
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
// Asynchronous request to save data
axios.post("/MaterialManagement/add", this.formData).then((res) => {
if (res.data.flag) {
this.$notify({
title: ' Successful hints ',
message: res.data.message,
type: 'success'
});
// Call reset to refresh the page
this.resetForm2('formData');
this.findPage();
} else {
this.$notify.error({
title: ' Error message ',
message: res.data.message
});
}
});
} else {
this.$notify({
title: ' error message ',
type: 'warning',
message: ' Please check whether the correct information is filled in '
});
return false;
}
});
},
// Dialog box reset form
resetForm2(formName) {
this.$refs[formName].resetFields();
this.dialogVisible = false;
this.dialogVisible2 = false;
}
// Backfill drop-down box event encapsulation
selectQuery(url) {
axios.get(url).then((res) => {
// Determine which model data is echoed
switch (url) {
case "/MaterialManagement/productType":
this.ComboBoxData.productType = res.data;
break;
case "/MaterialManagement/TheWinningType":
this.ComboBoxData.TheWinningType = res.data;
break;
case "/MaterialManagement/manufacturer":
this.ComboBoxData.manufacturer = res.data;
break;
case "/MaterialManagement/franchiser":
this.ComboBoxData.franchiser = res.data;
break;
}
});
}
3、 Realize database paging query
The effect is as shown in the first picture , Default display 10 One page , The request parameters are attached with the current page, how many pieces of data are displayed on each page, how many pieces of data in total, and the conditions for fuzzy query , The backend performs paging query processing according to the received conditions
// Written in data Internal initial data
// Paging related properties
pagination: {
currentPage: 1,
pageSize: 10,
total: 1,
name: '',
code: ''
}
// Written in methods In the method
// Paging query
findPage() {
axios.post("/MaterialManagement/qieryList", {
currentPage: this.pagination.currentPage,
pageSize: this.pagination.pageSize,
name: this.pagination.name,// Query criteria
code: this.pagination.code// Query code
}).then((res) => {
// Judge success
if (!res.data.flag && res.data.flag != null) {
this.$notify.error({
title: ' error ',
message: res.data.message
});
}
// Echo data
this.tableData = res.data.rows;
this.pagination.total = res.data.total;
});
}
The backend implements paging data encapsulation , The conditional query method needs to be used in the following places, and all of them are the same code , Refactoring extraction processing can be performed , By method name + You can query data by passing parameters
/// <summary>
/// Methods of encapsulating queries
/// </summary>
public posttingClass ListData(queryData queryData, Boolean flag)
{
posttingClass postting = new posttingClass();
try
{
List<selectData> listFaultInfo = (from tba in myModels.matter_table
// Connect the product type table
join tbb in myModels.product_type on tba.product_type_id equals tbb.product_type_id
// Connect bid type bid
join tbc in myModels.the_winning_type on tba.the_winning_type_id equals tbc.the_winning_type_id
// Connect the dealer table
join tbd in myModels.franchiser_table on tba.franchiser_id equals tbd.franchiser_id
// Connect the manufacturer table
join tbe in myModels.manufacturer_table on tba.manufacturer_id equals tbe.manufacturer_id
// Sort
orderby tba.matterid
select new selectData
{
Id = tba.matterid,
Name = tba.matter_name,
Code = tba.matter_code,
purchasePrice = tba.purchase_price,
SellingPrice = tba.Selling_price,
producer = tbe.manufacturer_name,
franchiser = tbd.franchiser_name,
productType = tbb.product_type_name,
TheWinningType = tbc.the_winning_type_name
}).ToList();
// The total number of queries
var count = myModels.matter_table.Count();
postting.selectDatas = listFaultInfo;
if (flag == false) return postting;
// Fuzzy query
if (queryData.name != null && queryData.name.Length > 0)
{
listFaultInfo = listFaultInfo.Where(o => o.Name.Contains(queryData.name)).ToList();
count = listFaultInfo.Count();
}
if (queryData.code != null && queryData.code.Length > 0)
{
listFaultInfo = listFaultInfo.Where(o => o.Code.Contains(queryData.code)).ToList();
count = listFaultInfo.Count();
}
listFaultInfo = listFaultInfo.Take(queryData.pageSize * queryData.currentPage).Skip(queryData.pageSize * (queryData.currentPage - 1)).ToList();
postting.selectDatas = listFaultInfo;
postting.Count = count;
return postting;
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
// Call the encapsulated query method
#region Two 、 Fuzzy paging query material data
public ActionResult qieryList(queryData queryData)
{
Result result = new Result();
// Paging data
try
{
var list = ListData(queryData, true).selectDatas;
var count = ListData(queryData, true).Count;
// The paging data returned by the assignment
PageResult pageResult = new PageResult();
pageResult.total = count;
// Pagination
// var list_Subject_set = llist.Take(PageSize*PageIndex).Skip(PageSize* (PageIndex- 1)).ToList();
pageResult.rows = list;
return Json(pageResult, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
Console.WriteLine(e);
result.flag = false;
result.message = " Data query failed " + e.Message;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
#endregion
4、 Delete item data
Almost all delete businesses use query , This is unavoidable , Otherwise, once the data is deleted, it will disappear , The deletion condition is based on the currently clicked row id To complete
// Delete event
deltetData(Id) {
// Ask if you want to delete data
this.$confirm(' This operation will permanently delete the file , Whether or not to continue ?', ' Tips ', {
confirmButtonText: ' determine ',
cancelButtonText: ' Cancel ',
type: 'warning'
}).then(() => {
// Asynchronous request to delete data
axios.post("/MaterialManagement/remove?Id=" + Id).then((res) => {
if (res.data.flag) {
this.$notify({
title: ' Successful hints ',
message: res.data.message,
type: 'success'
});
// In order to successfully jump back to the previous page of the last page when deleting the last data of the last page (pageSize=1 It doesn't work )
var totalPage = Math.ceil((this.pagination.total - 1) / this.pagination.pageSize)
var currentPage = this.pagination.currentPage > totalPage ? totalPage : this.pagination.currentPage
this.pagination.currentPage = this.pagination.currentPage < 1 ? 1 : currentPage;
// Query query data
this.findPage();
} else {
this.$notify({
title: ' error message ',
type: 'warning',
message: res.data.message
});
return false;
}
});
}).catch(() => {
this.$message({
type: 'info',
message: ' Delete cancelled '
});
});
}
According to delete the passed id Data query and market data
#region Four 、 Delete item data
public ActionResult remove(int Id)
{
Result result = new Result();
// Exception trapping
try
{
// according to id Query material information
matter_table matter = myModels.matter_table.Where(o => o.matterid == Id).Single();
if (matter != null)
{
// Execute delete
myModels.matter_table.Remove(matter);
if (myModels.SaveChanges() > 0)
{
result.flag = true;
result.message = " Material data deleted successfully ";
}
else
{
result.flag = false;
result.message = " Failed to delete material data ";
}
}
else
{
result.flag = false;
result.message = " according to id Failed to delete data ( There may not be this in the background id data )";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
Console.WriteLine(e);
result.flag = false;
result.message = " according to Id Delete data exception :" + e.Message;
return Json(result, JsonRequestBehavior.AllowGet);
}
}
#endregion
5、 Data import
.net Can be exported with the help of Microsoft
PNOIReference to complete , The version used in this case is :1.2.4.0, There will be differences between different versions
Implementation diagram of uploading data 
Entity tool class for exporting data
Class contains the basic functions of import and export , It can be realized directly by calling
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
namespace LibraryManagementSystem.Entity
{
public class ExcelReader
{
/// <summary>
/// according to Excel The column type gets the value of the column
/// </summary>
/// <param name="cell">Excel Column </param>
/// <returns></returns>
public static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.BLANK:
return string.Empty;
case CellType.BOOLEAN:
return cell.BooleanCellValue.ToString();
case CellType.ERROR:
return cell.ErrorCellValue.ToString();
case CellType.NUMERIC:
case CellType.Unknown:
default:
return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
case CellType.STRING:
return cell.StringCellValue;
case CellType.FORMULA:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
}
/// <summary>
/// Automatic setting Excel Column width
/// </summary>
/// <param name="sheet">Excel surface </param>
private static void AutoSizeColumns(ISheet sheet)
{
if (sheet.PhysicalNumberOfRows > 0)
{
IRow headerRow = sheet.GetRow(0);
for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
{
sheet.AutoSizeColumn(i);
}
}
}
/// <summary>
/// preservation Excel Document flows to file
/// </summary>
/// <param name="ms">Excel The document flow </param>
/// <param name="fileName"> file name </param>
private static void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
data = null;
}
}
/// <summary>
/// Output file to browser
/// </summary>
/// <param name="ms">Excel The document flow </param>
/// <param name="context">HTTP Context </param>
/// <param name="fileName"> file name </param>
private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
{
if (context.Request.Browser.Browser == "IE")
fileName = HttpUtility.UrlEncode(fileName);
context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
context.Response.BinaryWrite(ms.ToArray());
}
/// <summary>
/// DataReader convert to Excel The document flow
/// </summary>
/// <param name="reader"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(IDataReader reader)
{
MemoryStream ms = new MemoryStream();
using (reader)
{
using (IWorkbook workbook = new HSSFWorkbook())
{
using (ISheet sheet = workbook.CreateSheet())
{
IRow headerRow = sheet.CreateRow(0);
int cellCount = reader.FieldCount;
// handling header.
for (int i = 0; i < cellCount; i++)
{
headerRow.CreateCell(i).SetCellValue(reader.GetName(i));
}
// handling value.
int rowIndex = 1;
while (reader.Read())
{
IRow dataRow = sheet.CreateRow(rowIndex);
for (int i = 0; i < cellCount; i++)
{
dataRow.CreateCell(i).SetCellValue(reader[i].ToString());
}
rowIndex++;
}
AutoSizeColumns(sheet);
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}
}
}
return ms;
}
/// <summary>
/// DataReader convert to Excel The document flow , And save to file
/// </summary>
/// <param name="reader"></param>
/// <param name="fileName"> Saved path </param>
public static void RenderToExcel(IDataReader reader, string fileName)
{
using (MemoryStream ms = RenderToExcel(reader))
{
SaveToFile(ms, fileName);
}
}
/// <summary>
/// DataReader convert to Excel The document flow , And output to the client
/// </summary>
/// <param name="reader"></param>
/// <param name="context">HTTP Context </param>
/// <param name="fileName"> Output file name </param>
public static void RenderToExcel(IDataReader reader, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(reader))
{
RenderToBrowser(ms, context, fileName);
}
}
/// <summary>
/// DataTable convert to Excel The document flow
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(DataTable table)
{
MemoryStream ms = new MemoryStream();
using (table)
{
using (IWorkbook workbook = new HSSFWorkbook())
{
using (ISheet sheet = workbook.CreateSheet())
{
IRow headerRow = sheet.CreateRow(0);
// handling header.
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);//If Caption not set, returns the ColumnName value
// handling value.
int rowIndex = 1;
foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
AutoSizeColumns(sheet);
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}
}
}
return ms;
}
/// <summary>
/// DataTable convert to Excel The document flow , And save to file
/// </summary>
/// <param name="table"></param>
/// <param name="fileName"> Saved path </param>
public static void RenderToExcel(DataTable table, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
SaveToFile(ms, fileName);
}
}
/// <summary>
/// DataTable convert to Excel The document flow , And output to the client
/// </summary>
/// <param name="table"></param>
/// <param name="response"></param>
/// <param name="fileName"> Output file name </param>
public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
RenderToBrowser(ms, context, fileName);
}
}
/// <summary>
/// Excel Whether the document stream has data
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream)
{
return HasData(excelFileStream, 0);
}
/// <summary>
/// Excel Whether the document stream has data
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="sheetIndex"> Index number , For example, the first table is 0</param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream, int sheetIndex)
{
using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
//using (IWorkbook workbook = new XSSFWorkbook(excelFileStream))
{
if (workbook.NumberOfSheets > 0)
{
if (sheetIndex < workbook.NumberOfSheets)
{
using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
{
return sheet.PhysicalNumberOfRows > 0;
}
}
}
}
}
return false;
}
/// <summary>
/// Excel The document stream is converted to DataTable
/// The first row must be a header row
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="sheetName"> The name of the table </param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
{
return RenderFromExcel(excelFileStream, sheetName, 0);
}
/// <summary>
/// Excel The document stream is converted to DataTable
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="sheetName"> The name of the table </param>
/// <param name="headerRowIndex"> Title line index number , Such as the first act 0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
{
DataTable table = null;
using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
using (ISheet sheet = workbook.GetSheet(sheetName))
{
table = RenderFromExcel(sheet, headerRowIndex);
}
}
}
return table;
}
/// <summary>
/// Excel The document stream is converted to DataTable
/// Default conversion Excel The first table of
/// The first row must be a header row
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream)
{
return RenderFromExcel(excelFileStream, 0, 0);
}
/// <summary>
/// Excel The document stream is converted to DataTable
/// The first row must be a header row
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="sheetIndex"> Index number , For example, the first table is 0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
{
return RenderFromExcel(excelFileStream, sheetIndex, 0);
}
/// <summary>
/// Excel The document stream is converted to DataTable
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="sheetIndex"> Index number , For example, the first table is 0</param>
/// <param name="headerRowIndex"> Title line index number , Such as the first act 0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
{
DataTable table = null;
using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
{
table = RenderFromExcel(sheet, headerRowIndex);
}
}
}
return table;
}
/// <summary>
/// Excel The table is converted to DataTable
/// </summary>
/// <param name="sheet"> form </param>
/// <param name="headerRowIndex"> Title line index number , Such as the first act 0</param>
/// <returns></returns>
private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
{
DataTable table = new DataTable();
IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
//handling header.
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow();
if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j));
}
}
table.Rows.Add(dataRow);
}
return table;
}
/// <summary>
/// Excel Import documents into the database
/// Default access Excel The first table of
/// The first row must be a header row
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="insertSql"> Insert statement </param>
/// <param name="dbAction"> How to update to the database </param>
/// <returns></returns>
public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction)
{
return RenderToDb(excelFileStream, insertSql, dbAction, 0, 0);
}
public delegate int DBAction(string sql, params IDataParameter[] parameters);
/// <summary>
/// Excel Import documents into the database
/// </summary>
/// <param name="excelFileStream">Excel The document flow </param>
/// <param name="insertSql"> Insert statement </param>
/// <param name="dbAction"> How to update to the database </param>
/// <param name="sheetIndex"> Index number , For example, the first table is 0</param>
/// <param name="headerRowIndex"> Title line index number , Such as the first act 0</param>
/// <returns></returns>
public static int RenderToDb(Stream excelFileStream, string insertSql, DBAction dbAction, int sheetIndex, int headerRowIndex)
{
int rowAffected = 0;
using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
{
StringBuilder builder = new StringBuilder();
IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1
for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
if (row != null)
{
builder.Append(insertSql);
builder.Append(" values (");
for (int j = row.FirstCellNum; j < cellCount; j++)
{
builder.AppendFormat("'{0}',", GetCellValue(row.GetCell(j)).Replace("'", "''"));
}
builder.Length = builder.Length - 1;
builder.Append(");");
}
if ((i % 50 == 0 || i == rowCount) && builder.Length > 0)
{
// Every time 50 Records are inserted into the database in batches at a time
rowAffected += dbAction(builder.ToString());
builder.Length = 0;
}
}
}
}
}
return rowAffected;
}
}
}
Import the front-end page implementation
The uploaded file is based on ElementUI The upload function of
<el-upload class="upload-demo" ref="upload" :file-list="foleList" v-show="!hasFile" action="/MaterialManagement/upload" name="wrapper" :limit="1" :show-file-list="false" accept="application/xls,.xls" :on-success="successFile" :auto-upload="autoUpload" :before-upload="beforeUpload">
<el-button size="small" type="primary"> Click upload </el-button>
</el-upload>
<!-- The above method can be based on the official API To complete -->
js Code writing
// Verify the file format before uploading
beforeUpload(file) {
const isXLS = file.type === 'application/vnd.ms-excel';
if (isXLS) {
return true;
}
const isXLSX = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
if (isXLSX) {
return true;
}
this.$message.error(' Upload files can only be xls perhaps xlsx Format !');
return false;
},
// Upload file successful
successFile(response) {
if (response.flag) {
// Hide injury file button ;
this.hasFile = true;
this.$message({
message: response.message,
type: 'success'
});
this.tableData2 = response.data.Data.rows;
this.pagination2.total = response.data.Data.total;
} else {
this.$message({
message: response.message,
type: 'warning'
});
}
this.$refs.upload.clearFiles();
},
// Upload data paging query
handleCurrentChange2(currentPage) {
this.pagination2.currentPage = currentPage;
axios.post("/MaterialManagement/findByPage", this.pagination2).then((res) => {
this.tableData2 = res.data.rows;
this.pagination2.total = res.data.total;
});
}
Implementation of back-end import data 【 Double to repeat judgment 】
This method is mainly used to filter the uploaded files , You can save the data directly after filtering , At the same time, it also implements a paging query of uploaded data
Pay attention to the nested repetition of self data for loop
#region 6、 ... and 、 File upload event
public ActionResult upload(HttpPostedFileBase wrapper)
{
Result result = new Result();
//using (TransactionScope scope = new TransactionScope())
//{
// scope.Complete();
//}
int ServiceStationCount = 0;// Number of successfully saved entries
int oldCount = 0;// Number of existing data pieces
int renice = 0; // The number of existing data pieces in the uploaded file
try
{
// file type
string fileExtension = Path.GetExtension(wrapper.FileName).ToLower();
if (".xls".Equals(fileExtension) || ".xlsx".Equals(fileExtension))
{
byte[] fileBytes = new byte[wrapper.ContentLength];// Define binary arrays
wrapper.InputStream.Read(fileBytes, 0, wrapper.ContentLength);// Read file contents
if (ExcelReader.HasData(new MemoryStream(fileBytes)))
{
// Judge the uploaded excel Is it empty
// Create a list entity class , Temporarily save the uploaded data for display
List<selectData> selectData = new List<selectData>();
// obtain Excel The data of , In the DataTable in
DataTable dtexcel = ExcelReader.RenderFromExcel(new MemoryStream(fileBytes), 0, 1);
// Delete the second line
dtexcel.Rows.RemoveAt(0);
foreach (DataRow row in dtexcel.Rows)
{
// Create an object to store the uploaded data , And loop to add to a List In combination
selectData selects = new selectData();
try
{
var Code = row.ItemArray[5].ToString().Trim();
// Loop through the uploaded data and compare with the data 【 Add data into the object after data comparison 】
var repetitionCount = myModels.matter_table.Where(o => o.matter_code == Code).Count();
// Query the duplicate quantity
if (repetitionCount > 0)
{
oldCount++;
}
else
{
// The uploaded excel Cell assignment entity class information
selects.producer = row.ItemArray[0].ToString().Trim();
selects.franchiser = row.ItemArray[1].ToString().Trim();
selects.productType = row.ItemArray[2].ToString().Trim();
selects.TheWinningType = row.ItemArray[3].ToString().Trim();
selects.Name = row.ItemArray[4].ToString().Trim();
selects.purchasePrice = Convert.ToDecimal(row.ItemArray[6]);
selects.SellingPrice = Convert.ToDecimal(row.ItemArray[7]);
selects.Code = Code;
// Save data to a collection
selectData.Add(selects);
ServiceStationCount++;
}
}
catch (Exception e)
{
Console.WriteLine(e);
result.flag = false;
result.message = " Failed to upload file to add collection :" + e.Message;
}
}
// Traverse the duplicate data of the uploaded file
List<selectData> selectData2 = new List<selectData>();
for (int i = 0; i < selectData.Count; i++)
{
if (i != 0)
{
// The method of deleting in reverse order , Otherwise, an error will be reported in the deletion
// Each deletion will cause the size of the collection and the value of the element index to change , Which leads to foreach An exception occurs when an element is deleted from the .
for (int j = selectData2.Count - 1; j >= 0; j--)
{
if (selectData[i].Code.Trim() == selectData2[j].Code.Trim())
{
renice++;
selectData2.Remove(selectData2[j]);
}
}
selectData2.Add(selectData[i]);
}
else
{
selectData2.Add(selectData[0]);
}
}
// Session.Abandon();// Clear all Session
// To clear out of Session
Session["ExcelFile"] = null;
Session.Remove("ExcelFile");
#region Return the data
// Judge whether the data read successfully is 0
if (ServiceStationCount == 0 && oldCount > 0)
{
result.flag = false;
result.message = " The comparison of uploaded data is repeated :" + oldCount + " strip , Please upload again ";
}
else
{
// Empty first and then assign a value
result.flag = true;
result.message = " Data read successfully :" + selectData.Count + " strip , Duplicate database comparison :" + oldCount + " strip , The uploaded data is duplicated :" + renice + " strip , Successfully uploaded :" + (ServiceStationCount - renice) + " Data ";
queryData query = new queryData();
query.currentPage = 1;
query.pageSize = 5;
Session["ExcelFile"] = selectData2; // Assign to local save
result.data = findByPage(query); // Return paged data
}
#endregion
}
else
{
result.flag = false;
result.message = " The Excel The file is empty !";
}
}
else
{
result.flag = false;
result.message = " The uploaded file type does not match ";
}
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
result.flag = false;
result.message = " File upload exception :" + e.Message;
Console.WriteLine(e);
return Json(wrapper, JsonRequestBehavior.AllowGet);
}
}
#endregion
Upload data to realize paging query and return to the page
The principle of implementation is the same as that of querying the data display on the first page , It's all about one List The collection data is returned in pages
#region 7、 ... and 、 Page query the uploaded file and return to the page
public ActionResult findByPage(queryData queryData)
{
PageResult pageResult = new PageResult();
try
{
// Create a SeconBook A collection of objects
List<selectData> listSecond = new List<selectData>();
// Judge Session Whether is empty in
if (Session["ExcelFile"] != null)
{
// obtain Session The data saved in is forced to selectData A collection of objects
listSecond = Session["ExcelFile"] as List<selectData>;
}
// Total number of lines
int totalRow = listSecond.Count();
// Pagination
pageResult.total = totalRow;
// var list_Subject_set = llist.Take(PageSize*PageIndex).Skip(PageSize* (PageIndex- 1)).ToList();
pageResult.rows = listSecond.Take(queryData.pageSize * queryData.currentPage).Skip(queryData.pageSize * (queryData.currentPage - 1)).ToList();
}
catch (Exception e)
{
Console.WriteLine(e);
}
return Json(pageResult, JsonRequestBehavior.AllowGet);
}
#endregion
6、 Export data implementation
There are two types of export
1、 Conditional query export
2、 All data export
Export data rendering 
The front page code judges the request
Through a variable
flagTo determine whether to export the current number of pages or all data
// Export Events
derive() {
// Asynchronous request download
this.$confirm(' Do you want to export the contents of the current page or all the contents ', ' Export confirmation prompt ', {
confirmButtonText: ' Export the current page ',
cancelButtonText: ' Export all ',
type: 'warning'
}).then(() => {
window.location.href = "/MaterialManagement/ExportToExcel?currentPage=" + this.pagination.currentPage + "&pageSize=" + this.pagination.pageSize + "&name=" + this.pagination.name + "&code=" + this.pagination.code +"&flag=true";
}).catch(() => {
window.location.href = "/MaterialManagement/ExportToExcel?flag=false";
});
}
The implementation of exporting the current page data
By calling the previously encapsulated
ListDataPass data for query , Return according to the query content , At the same time, the following export style also encapsulates a method at the top of the following code
/// <summary>
/// Unified export format
/// </summary>
/// <param name="style"></param>
public void iCellStyle(ICellStyle style)
{
// Set play
style.Alignment = HorizontalAlignment.CENTER;
style.VerticalAlignment = VerticalAlignment.CENTER;
// Set the border line to solid
style.BorderLeft = CellBorderType.THIN;
style.BorderTop = CellBorderType.THIN;
style.BorderRight = CellBorderType.THIN;
style.BorderBottom = CellBorderType.THIN;
}
#region Nine 、NPOI Export to Excel
//NPOI Export to Excel( Fault code )
public ActionResult ExportToExcel(queryData queryData, Boolean flag)
{
try
{
var listFaultInfo = ListData(queryData, flag).selectDatas;
// Two : Code to create a Excel form ( This is called a workbook )
// establish Excel The object of the document workbook ( call NPOI file )
HSSFWorkbook excelBook = new HSSFWorkbook();
#region Pattern design
ICellStyle style2 = excelBook.CreateCellStyle();
iCellStyle(style2);
ICellStyle style3 = excelBook.CreateCellStyle();
IFont font = excelBook.CreateFont();
font.Color = IndexedColors.RED.Index;// The font is red
style3.SetFont(font);
iCellStyle(style3);
#endregion
// establish Excel Worksheet Sheet= Material information
ISheet sheet1 = excelBook.CreateSheet(" Material information ");
#region Table title merge column style
// The first row of the table is the title
IRow row0 = sheet1.CreateRow(0);
row0.Height = 60 * 15;
row0.CreateCell(0).SetCellValue(" Export material information ");
sheet1.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 7)); // Merge information
// Set header style
ICellStyle style4 = excelBook.CreateCellStyle(); // Header
iCellStyle(style4); // Solid line
style4.FillPattern = FillPatternType.SOLID_FOREGROUND;// Set the background fill effect
style4.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.AQUA.index;// Set the background fill color
IFont font_header = excelBook.CreateFont();// Declaration font
font_header.FontHeightInPoints = 20;// font size
style4.SetFont(font_header);// Add cells
row0.GetCell(0).CellStyle = style4; // The input table has the same style
#endregion
// to Sheet Add the header of the second line
IRow row1 = sheet1.CreateRow(1);
row1.Height = 30 * 15;
string[] strings = new string[] {
" Item name ", " Item no ", " Purchase price ", " Selling price ", " Name of manufacturer ", " Dealer name ", " The product type ", " Type of bid winning " };
int[] widths = new int[] {
40, 40 };
// Traverse to create header row
for (int i = 0; i < strings.Length; i++)
{
row1.CreateCell(i).SetCellValue(strings[i]);// Assign a value to each cell of the title
row1.GetCell(i).CellStyle = style2;// Initialize style settings
sheet1.SetColumnWidth(i, 20 * 256);
if (i == 0 || i == 1)
{
row1.GetCell(i).CellStyle = style3;// Initialize style settings
}
else if (i == 4 || i == 5)
{
sheet1.SetColumnWidth(i, widths[i - 4] * 256);// Initialize setting width
}
}
// Add data row : Write the table data step by step sheet1 In each row ( That is to assign a value to each cell )
for (int i = 0; i < listFaultInfo.Count; i++)
{
//sheet1.CreateRow(i).
// Create lines
IRow rowTemp = sheet1.CreateRow(i + 2);
rowTemp.Height = 30 * 15;
// Item name
rowTemp.CreateCell(0).SetCellValue(listFaultInfo[i].Name);
// Material code
rowTemp.CreateCell(1).SetCellValue(listFaultInfo[i].Code);
// Purchase price
rowTemp.CreateCell(2).SetCellValue((double)listFaultInfo[i].purchasePrice);
// Selling price
rowTemp.CreateCell(3).SetCellValue((double)listFaultInfo[i].SellingPrice);
/// Name of manufacturer
rowTemp.CreateCell(4).SetCellValue(listFaultInfo[i].producer);
// Dealer name
rowTemp.CreateCell(5).SetCellValue(listFaultInfo[i].franchiser);
// The product type
rowTemp.CreateCell(6).SetCellValue(listFaultInfo[i].productType);
// Type of bid winning
rowTemp.CreateCell(7).SetCellValue(listFaultInfo[i].TheWinningType);
// Inner loop creates cell data
for (int j = 0; j < 8; j++)
{
// rowTemp.CreateCell(j).SetCellValue();
if (j == 0 || j == 1)
{
rowTemp.GetCell(j).CellStyle = style3;
}
else
{
rowTemp.GetCell(j).CellStyle = style2;
}
}
}
// The name of the output file
string fileName = " Export material information " + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + ".xls";
// hold Excel Turn to flow , Output
// Create file stream
System.IO.MemoryStream bookStream = new System.IO.MemoryStream();
// Write the workbook to the file stream
excelBook.Write(bookStream);
// The output is called before Seek( Offset , Cursor position ) hold 0 The position is specified as the starting position
bookStream.Seek(0, System.IO.SeekOrigin.Begin);
//Stream object , file type , File name
return File(bookStream, "application/vnd.ms-excel", fileName);
}
catch (Exception e)
{
Console.WriteLine(e);
return null;
}
}
#endregion
边栏推荐
- Common sense of resolution
- 【软件工程】期末重点
- Pinduoduo updates the merchant live broadcast service agreement and strictly punishes the illegal merchants
- 2022-06-10 工作记录--JS-获取到某一日期N天后的日期
- VRRP skills topic
- [QT] QT event handling
- Panorama of enterprise power in China SSD industry
- 剑指 Offer 13. 机器人的运动范围
- Vulnhub Vegeta: 1
- STP spanning tree protocol Foundation
猜你喜欢

加分利器 不负所托 | 知道创宇获攻防演练防守方感谢信!

2022年安全员-A证考题及答案

1. fully explain the basic principles of IPSec

CDN principle

vulnhub DC: 2

Selection and comparison of message oriented middleware MQ

O (n) complexity hand tear sorting interview questions | an article will help you understand counting sorting

Recommended course: workplace writing training

Introduction to machine learning compilation course learning notes lesson 1 overview of machine learning compilation

Web security XSS foundation 06
随机推荐
In the multi network card environment, the service IP registered by Nacos is incorrect, resulting in inaccessible services
C language operators and expressions
Pinduoduo updates the merchant live broadcast service agreement and strictly punishes the illegal merchants
非单文件组件
vulnhub Vegeta: 1
Envoy obtain the real IP address of the client
Solve the problem of non secure websites requesting localhost to report CORS after chrome94
STP spanning tree protocol Foundation
China smallpox vaccine market trend report, technical innovation and market forecast
Recommended course: workplace writing training
Cross border e-commerce, early entry and early benefit
Dynamic memory management (1)
Research and investment strategy report on China's nano silver wire conductive film industry (2022 Edition)
MySQL夺命10问,你能坚持到第几问?
剑指 Offer 42. 连续子数组的最大和
结合源码剖析Oauth2分布式认证与授权的实现流程
docker安装redis-简单而无坑
Cat write multiline content to file
2022-06-10 工作记录--JS-获取到某一日期N天后的日期
详细了解关于sentinel的实际应用

