当前位置:网站首页>C import Xls data method summary I (upload files and create Workbooks)
C import Xls data method summary I (upload files and create Workbooks)
2022-07-04 01:10:00 【Xiao Zhong wants to learn!!!】
C# Import .xls Data method summary I ( Upload files and create workbooks )
Preface :
The software used is VS2019
The reference used is :NPOI.dll
NPOI Is built on POI 3.x A program above version ,NPOI Can be installed without Office In the case of Word or Excel The document is read and written .NPOI It's an open source C# Reading and writing Excel、WORD Wait for Microsoft OLE2 Items for component documents .
One 、 Receive uploaded files
About C# The uploaded files are basically used HttpPostedFileBase To receive the uploaded data
Used as a base class of some kind , The former provides access to a single file that has been uploaded by the client .
HttpPostedFileBase() Class has the following private methods that can be used , Are related to the uploaded files later
- ContentLength
When overridden in a derived class , Get the size of the uploaded file ( In bytes ). - ContentType
When overridden in a derived class , Get uploaded files MIME Content type . - FileName
The name of the file on the client , Include directory path . - InputStream
When overridden in a derived class , Get the System.IO.Stream object , To prepare to read the contents of the file . - SaveAs
When overridden in a derived class , Save the contents of the uploaded file .
Two 、 Judge whether the uploaded file conforms to .xls file
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
1、 Get the path of the uploaded file
Top entry required : using System.IO;
// Get file suffix
string fileExtension = Path.GetExtension(excelFile.FileName);
2、 adopt Equals() Determine whether the file type conforms to
Equals() Express : Determines whether this instance is associated with another specified System.String Object has the same value .
return true or false
// Judge whether the document is excel form
if (".xls".Equals(fileExtension.ToLower()) || ".xlsx".Equals(fileExtension.ToLower())){
}else{
}
3、 Declare a binary array to store the uploaded file
The maximum length of the array is the length of the uploaded file
// Declare the binary array to store the file
byte[] fileBytes = new byte[excelFile.ContentLength];
4、 Convert the uploaded file into a binary array and assign the previous variable
The length of the binary array is the size of the uploaded file , By receiving the uploaded file .ContentLength Can get
The first parameter is the binary array written , The second parameter is the write location , The third is the length written
// Convert the file into binary data group and store it in fileBytes
excelFile.InputStream.Read(fileBytes, 0, excelFile.ContentLength);
5、 Convert binary arrays into memory streams
// Convert binary array into memory stream
MemoryStream excelFileStream = new MemoryStream(fileBytes);
6、 Convert memory stream to workbooks
// Convert memory stream to workbooks
IWorkbook workbook = new HSSFWorkbook(excelFileStream);
7、 The complete first part of the code
public ActionResult ImportExcel(HttpPostedFileBase excelFile){
ReturnJson returnJson = new ReturnJson(); // Put back the entity class data created
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){
// Continue to the next step and write the next article
}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);
}
边栏推荐
- Summary of common tools and technical points of PMP examination
- Regular expression of shell script value
- From functools import reduce -- see the use of reduce function from typical examples
- 1-redis architecture design to use scenarios - four deployment and operation modes (Part 1)
- Oracle database knowledge points that cannot be learned (II)
- CLP information - how does the digital transformation of credit business change from star to finger?
- Sequence list and linked list
- Flutter local database sqflite
- Release and visualization of related data
- How to be a professional software testing engineer? Listen to the byte five year old test
猜你喜欢

老姜的特点

1-Redis架构设计到使用场景-四种部署运行模式(上)

A malware detection method for checking PLC system using satisfiability modulus theoretical model

It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction

功能:求出菲波那契数列的前一项与后一项之比的极限的 近似值。例如:当误差为0.0001时,函数值为0.618056。

手机异步发送短信验证码解决方案-Celery+redis

中电资讯-信贷业务数字化转型如何从星空到指尖?

技术实践|线上故障分析及解决方法(上)

Sequence list and linked list

Gauss elimination method and template code
随机推荐
PMP 考试常见工具与技术点总结
HackTheBox-baby breaking grad
GUI application: socket network chat room
Technical practice online fault analysis and solutions (Part 1)
[error record] configure NDK header file path in Visual Studio (three header file paths of NDK | ASM header file path selection related to CPU architecture)
The culprit of unrestrained consumption -- Summary
Introduction to A-frame virtual reality development
[common error] UART cannot receive data error
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
Luogu p1309 Swiss wheel
The difference between fetchtype lazy and eagle in JPA
be based on. NETCORE development blog project starblog - (14) realize theme switching function
不得不会的Oracle数据库知识点(三)
Hash table, string hash (special KMP)
Mongodb learning notes: command line tools
I don't care about you. OKR or KPI, PPT is easy for you
be based on. NETCORE development blog project starblog - (14) realize theme switching function
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
Which insurance products can the elderly buy?
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