当前位置:网站首页>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);
}
边栏推荐
- 7.1 学习内容
- 【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
- Cesiumjs 2022^ source code interpretation [8] - resource encapsulation and multithreading
- Functions and arrays of shell scripts
- 老姜的特点
- Wechat official account and synchronization assistant
- What is the future of software testing industry? Listen to the test veterans' answers
- 8. Go implementation of string conversion integer (ATOI) and leetcode
- 2-Redis架构设计到使用场景-四种部署运行模式(下)
- Since the "epidemic", we have adhered to the "no closing" of data middle office services
猜你喜欢
2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)
GUI 应用:socket 网络聊天室
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
2-Redis架构设计到使用场景-四种部署运行模式(下)
How to use AHAS to ensure the stability of Web services?
Mobile asynchronous sending SMS verification code solution -efficiency+redis
中电资讯-信贷业务数字化转型如何从星空到指尖?
Introduction to A-frame virtual reality development
Some other configurations on Huawei's spanning tree
随机推荐
All in one 1407: stupid monkey
基于.NetCore开发博客项目 StarBlog - (14) 实现主题切换功能
【.NET+MQTT】.NET6 环境下实现MQTT通信,以及服务端、客户端的双边消息订阅与发布的代码演示
MySQL - use of aggregate functions and group by groups
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
Who moved my code!
技術實踐|線上故障分析及解决方法(上)
Force deduction solution summary 1189- maximum number of "balloons"
Gee: create a new feature and set corresponding attributes
数据库表外键的设计
Windos10 reinstallation system tutorial
CesiumJS 2022^ 源码解读[8] - 资源封装与多线程
【.NET+MQTT】. Net6 environment to achieve mqtt communication, as well as bilateral message subscription and publishing code demonstration of server and client
Fundamentals of machine learning: feature selection with lasso
Thinkphp6 integrated JWT method and detailed explanation of generation, removal and destruction
功能:将主函数中输入的字符串反序存放。例如:输入字符串“abcdefg”,则应输出“gfedcba”。
The force deduction method summarizes the single elements in the 540 ordered array
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).
[common error] custom IP instantiation error
0 basic learning C language - nixie tube dynamic scanning display