当前位置:网站首页>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);
}
边栏推荐
- Audio resource settings for U3D resource management
- 基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
- Fundamentals of machine learning: feature selection with lasso
- [error record] configure NDK header file path in Visual Studio
- 不得不会的Oracle数据库知识点(一)
- How to set the response description information when the response parameter in swagger is Boolean or integer
- PMP 考试常见工具与技术点总结
- 0 basic learning C language - nixie tube dynamic scanning display
- gslb(global server load balance)技术的一点理解
- All in one 1412: binary classification
猜你喜欢
[common error] custom IP instantiation error
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
“疫”起坚守 保障数据中台服务“不打烊”
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).
Network layer - routing
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
Eight year test old bird, some suggestions for 1-3 year programmers
Weekly open source project recommendation plan
Mobile asynchronous sending SMS verification code solution -efficiency+redis
What is the future of software testing industry? Listen to the test veterans' answers
随机推荐
Windos10 reinstallation system tutorial
机器学习基础:用 Lasso 做特征选择
Unity Shader入门精要读书笔记 第三章 Unity Shader基础
技術實踐|線上故障分析及解决方法(上)
2-Redis架构设计到使用场景-四种部署运行模式(下)
MySQL uses the view to report an error, explain/show can not be issued; lacking privileges for underlying table
OS interrupt mechanism and interrupt handler
Force deduction solution summary 1189- maximum number of "balloons"
On covariance of array and wildcard of generic type
Leetcode 121 best time to buy and sell stock (simple)
File contains vulnerability summary
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
“疫”起坚守 保障数据中台服务“不打烊”
Long article review: entropy, free energy, symmetry and dynamics in the brain
Sorry, Tencent I also refused
Software testers, how can you quickly improve your testing skills? Ten minutes to teach you
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
QML add gradient animation during state transition
leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction