当前位置:网站首页>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);
}
边栏推荐
- MySQL -- Introduction and use of single line functions
- CLP information - how does the digital transformation of credit business change from star to finger?
- Stringutils and collectionutils
- Introduction to A-frame virtual reality development
- Introduction to unity shader essentials reading notes Chapter III unity shader Foundation
- Avoid playing with super high conversion rate in material minefields
- Typescript basic knowledge sorting
- 老姜的特点
- PMP 考试常见工具与技术点总结
- What insurance products should be bought for the elderly?
猜你喜欢
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
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
Makefile judge custom variables
[error record] configure NDK header file path in Visual Studio
@EnableAsync @Async
AI 助力艺术设计抄袭检索新突破!刘芳教授团队论文被多媒体顶级会议ACM MM录用
Alibaba test engineer with an annual salary of 500000 shares notes: a complete set of written tests of software testing
Huawei rip and BFD linkage
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
What is regression testing? Talk about regression testing in the eyes of Ali Test Engineers
随机推荐
求esp32C3板子连接mssql方法
功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
Hash table, string hash (special KMP)
7.1 学习内容
Some other configurations on Huawei's spanning tree
Sequence list and linked list
About uintptr_ T and IntPtr_ T type
在寻求人类智能AI的过程中,Meta将赌注押向了自监督学习
swagger中响应参数为Boolean或是integer如何设置响应描述信息
关于 uintptr_t和intptr_t 类型
Analysis and solution of lazyinitializationexception
Query efficiency increased by 10 times! Three optimization schemes to help you solve the deep paging problem of MySQL
Leetcode 121 best time to buy and sell stock (simple)
File contains vulnerability summary
Decompile and modify the non source exe or DLL with dnspy
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
Software testers, how can you quickly improve your testing skills? Ten minutes to teach you
How to be a professional software testing engineer? Listen to the byte five year old test
长文综述:大脑中的熵、自由能、对称性和动力学