当前位置:网站首页>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);
}
边栏推荐
- File contains vulnerability summary
- GUI 应用:socket 网络聊天室
- be based on. NETCORE development blog project starblog - (14) realize theme switching function
- Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
- @EnableAsync @Async
- Introduction to unity shader essentials reading notes Chapter III unity shader Foundation
- Network layer - routing
- Function: store the strings entered in the main function in reverse order. For example, if you input the string "ABCDEFG", you should output "gfedcba".
- All in one 1412: binary classification
- How to be a professional software testing engineer? Listen to the byte five year old test
猜你喜欢

【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client

A dichotomy of Valentine's Day

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

Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing

Introduction to A-frame virtual reality development

Fundamentals of machine learning: feature selection with lasso
![CesiumJS 2022^ 源码解读[8] - 资源封装与多线程](/img/d2/99932660298b4a4cddd7e5e69faca1.png)
CesiumJS 2022^ 源码解读[8] - 资源封装与多线程

From functional testing to automated testing, how did I successfully transform my salary to 15K +?
![[error record] configure NDK header file path in Visual Studio](/img/9f/89f68c037dcf68a31a2de064dd8471.jpg)
[error record] configure NDK header file path in Visual Studio

Struct in linked list
随机推荐
MySQL -- Introduction and use of single line functions
GUI application: socket network chat room
Long article review: entropy, free energy, symmetry and dynamics in the brain
Mongodb learning notes: command line tools
[prefix and notes] prefix and introduction and use
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
A-Frame虚拟现实开发入门
It is worthy of "Alibaba internal software test interview notes" from beginning to end, all of which are essence
What is the GPM scheduler for go?
Function: write function fun to find s=1^k+2^k +3^k ++ The value of n^k, (the cumulative sum of the K power of 1 to the K power of n).
Day05 表格
Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing
Severity code description the project file line prohibits the display of status error c4996 fopen ('fscanf ', StrCmp): this function or variable may be unsafe The most comprehensive solution
Luogu p1309 Swiss wheel
All in one 1412: binary classification
不得不会的Oracle数据库知识点(三)
Analysis and solution of lazyinitializationexception
Who moved my code!
功能:编写函数fun求s=1^k+2^k +3^k + ......+N^k的值, (1的K次方到N的K次方的累加和)。
Avoid playing with super high conversion rate in material minefields