search
HomeJavajavaTutorialHow to use Java to parse very large Excel files

一、XSSF

package com.yy.demo01;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 
public class dd {public static void main(String[] args) {
	//开始时间
	long begin = System.currentTimeMillis();
	try (//读取一个已存在的Excel文件
			 Workbook workbook = new XSSFWorkbook(new FileInputStream("D:\\1\\demo-data.xlsx"));
					FileOutputStream out = new FileOutputStream("D:\\1\\100w.xlsx")) {
			  
			    //在“已存在”的Excel文件中,创建新的sheet
				Sheet sheet = workbook.createSheet();
				
				//获取格式编码值
				DataFormat dataFormat = workbook.createDataFormat();
				Short dateFormatCode = dataFormat.getFormat("yyyy年MM月dd日 HH:mm:ss");
				Short moneyFormatCode = dataFormat.getFormat("¥#,###");
				
				//创建日期格式对象
				CellStyle dateCellStyle = workbook.createCellStyle();
				dateCellStyle.setDataFormat(dateFormatCode);//设置格式编码
				
				//创建货币格式对象
				CellStyle moneyCellStyle = workbook.createCellStyle();
				moneyCellStyle.setDataFormat(moneyFormatCode);//设置格式编码值
				
			    for(int i = 0; i< 300000;i++) {
			    	String name = "A" + i;
			    	
			    	//创建行
			    	Row row = sheet.createRow(i + 1);
			    	
			    	//创建单元格
			    	Cell cell0 = row.createCell(0);//序号
			    	cell0.setCellValue(String.valueOf(i + 1));
			    	
			    	Cell cell1 = row.createCell(1);//姓名
			    	cell1.setCellValue(name);
			    	
			    	Cell cell2 = row.createCell(2);//日期
			    	cell2.setCellStyle(dateCellStyle);//货币金额格式对象
			    	cell2.setCellValue(new Date());
			    	
			    	Cell cell3 = row.createCell(3);//红包金额
			    	cell3.setCellStyle(moneyCellStyle);//货币金额格式对象
			    	cell3.setCellValue((int)(Math.random()*10000));
			    	
			    }
			    //写入文件
				workbook.write(out);
				//结束时间
				long end = System.currentTimeMillis();
				
				System.out.println("共耗时:" +(end - begin) + "毫秒");
			
			} catch (IOException e) {
 
				e.printStackTrace();
			}
}
 
}

How to use Java to parse very large Excel files

二、SXSSF

package com.yy.demo01;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
 
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
 
public class Demo10 {
	public static void main(String[] args) {
		//开始时间
		long begin = System.currentTimeMillis();
		try (//读取一个已存在的Excel文件
				 Workbook workbook = new SXSSFWorkbook(100);
						FileOutputStream out = new FileOutputStream("D:\\1\\100w.xlsx")) {
				  
				    //在“已存在”的Excel文件中,创建新的sheet
					Sheet sheet = workbook.createSheet();
					
					//获取格式编码值
					DataFormat dataFormat = workbook.createDataFormat();
					Short dateFormatCode = dataFormat.getFormat("yyyy年MM月dd日 HH:mm:ss");
					Short moneyFormatCode = dataFormat.getFormat("¥#,###");
					
					//创建日期格式对象
					CellStyle dateCellStyle = workbook.createCellStyle();
					dateCellStyle.setDataFormat(dateFormatCode);//设置格式编码
					
					//创建货币格式对象
					CellStyle moneyCellStyle = workbook.createCellStyle();
					moneyCellStyle.setDataFormat(moneyFormatCode);//设置格式编码值
					
				    for(int i = 0; i< 300000;i++) {
				    	String name = "A" + i;
				    	
				    	//创建行
				    	Row row = sheet.createRow(i + 1);
				    	
				    	//创建单元格
				    	Cell cell0 = row.createCell(0);//序号
				    	cell0.setCellValue(String.valueOf(i + 1));
				    	
				    	Cell cell1 = row.createCell(1);//姓名
				    	cell1.setCellValue(name);
				    	
				    	Cell cell2 = row.createCell(2);//日期
				    	cell2.setCellStyle(dateCellStyle);//货币金额格式对象
				    	cell2.setCellValue(new Date());
				    	
				    	Cell cell3 = row.createCell(3);//红包金额
				    	cell3.setCellStyle(moneyCellStyle);//货币金额格式对象
				    	cell3.setCellValue((int)(Math.random()*10000));
				    	
				    }
				    //写入文件
					workbook.write(out);
					//结束时间
					long end = System.currentTimeMillis();
					
					System.out.println("共耗时:" +(end - begin) + "毫秒");
				
				} catch (IOException e) {
 
					e.printStackTrace();
				}
	}
 
}

三、easyExcel

准备实体类

public class Order {
    @ExcelProperty("订单编号")
    private String orderId; // 订单编号
    
    @ExcelProperty("支付金额")
    @NumberFormat("¥#,###")
    private Double payment; // 支付金额
    
    @ExcelProperty(value = "创建日期",converter = LocalDateTimeConverter.class)
    private LocalDateTime creationTime; // 创建时间
 
    public Order() {
        this.orderId = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddhhmmss"))
                + UUID.randomUUID().toString().substring(0, 5);
        this.payment = Math.random() * 10000;
        this.creationTime = LocalDateTime.now();
    }
 
    public String getOrderId() {
        return orderId;
    }
 
    public void setOrderId(String orderId) {
        this.orderId = orderId;
    }
 
    public Double getPayment() {
        return payment;
    }
 
    public void setPayment(Double payment) {
        this.payment = payment;
    }
 
    public LocalDateTime getCreationTime() {
        return creationTime;
    }
 
    public void setCreationTime(LocalDateTime creationTime) {
        this.creationTime = creationTime;
    }
 
 
 
    @Override
    public String toString() {
        return "Order [orderId=" + orderId + ", payment=" + payment + ", creationTime=" + creationTime + "]";
    }
}

准备converter转换类(兼容LocateDateTime日期时间类)

public class LocalDateTimeConverter implements Converter<LocalDateTime> {
 
    @Override
    public Class<LocalDateTime> supportJavaTypeKey() {
        return LocalDateTime.class;
    }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }
 
    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty contentProperty,
            GlobalConfiguration globalConfiguration) {
        return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }
 
    @Override
    public CellData<String> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty,
            GlobalConfiguration globalConfiguration) {
        return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
 
}

写入300000条数据

public class Demo {
    public static void main(String[] args) {
        // 写入100w
        EasyExcel.write("c:\\test\\run\\easy.xlsx", Order.class)
                 .sheet("订单列表")
                 .doWrite(data());
    }
    
    // 创建100w条订单数据
    private static List<Order> data() {
        List<Order> list = new ArrayList<Order>();
        for (int i = 0; i < 300000; i++) {
            list.add(new Order());
        }
        return list;
    }
}

How to use Java to parse very large Excel files

所以easyExcel最快,XSSF最慢且占用cpu最高

The above is the detailed content of How to use Java to parse very large Excel files. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How does the class loader subsystem in the JVM contribute to platform independence?How does the class loader subsystem in the JVM contribute to platform independence?Apr 23, 2025 am 12:14 AM

The class loader ensures the consistency and compatibility of Java programs on different platforms through unified class file format, dynamic loading, parent delegation model and platform-independent bytecode, and achieves platform independence.

Does the Java compiler produce platform-specific code? Explain.Does the Java compiler produce platform-specific code? Explain.Apr 23, 2025 am 12:09 AM

The code generated by the Java compiler is platform-independent, but the code that is ultimately executed is platform-specific. 1. Java source code is compiled into platform-independent bytecode. 2. The JVM converts bytecode into machine code for a specific platform, ensuring cross-platform operation but performance may be different.

How does the JVM handle multithreading on different operating systems?How does the JVM handle multithreading on different operating systems?Apr 23, 2025 am 12:07 AM

Multithreading is important in modern programming because it can improve program responsiveness and resource utilization and handle complex concurrent tasks. JVM ensures the consistency and efficiency of multithreads on different operating systems through thread mapping, scheduling mechanism and synchronization lock mechanism.

What does 'platform independence' mean in the context of Java?What does 'platform independence' mean in the context of Java?Apr 23, 2025 am 12:05 AM

Java's platform independence means that the code written can run on any platform with JVM installed without modification. 1) Java source code is compiled into bytecode, 2) Bytecode is interpreted and executed by the JVM, 3) The JVM provides memory management and garbage collection functions to ensure that the program runs on different operating systems.

Can Java applications still encounter platform-specific bugs or issues?Can Java applications still encounter platform-specific bugs or issues?Apr 23, 2025 am 12:03 AM

Javaapplicationscanindeedencounterplatform-specificissuesdespitetheJVM'sabstraction.Reasonsinclude:1)Nativecodeandlibraries,2)Operatingsystemdifferences,3)JVMimplementationvariations,and4)Hardwaredependencies.Tomitigatethese,developersshould:1)Conduc

How does cloud computing impact the importance of Java's platform independence?How does cloud computing impact the importance of Java's platform independence?Apr 22, 2025 pm 07:05 PM

Cloud computing significantly improves Java's platform independence. 1) Java code is compiled into bytecode and executed by the JVM on different operating systems to ensure cross-platform operation. 2) Use Docker and Kubernetes to deploy Java applications to improve portability and scalability.

What role has Java's platform independence played in its widespread adoption?What role has Java's platform independence played in its widespread adoption?Apr 22, 2025 pm 06:53 PM

Java'splatformindependenceallowsdeveloperstowritecodeonceandrunitonanydeviceorOSwithaJVM.Thisisachievedthroughcompilingtobytecode,whichtheJVMinterpretsorcompilesatruntime.ThisfeaturehassignificantlyboostedJava'sadoptionduetocross-platformdeployment,s

How do containerization technologies (like Docker) affect the importance of Java's platform independence?How do containerization technologies (like Docker) affect the importance of Java's platform independence?Apr 22, 2025 pm 06:49 PM

Containerization technologies such as Docker enhance rather than replace Java's platform independence. 1) Ensure consistency across environments, 2) Manage dependencies, including specific JVM versions, 3) Simplify the deployment process to make Java applications more adaptable and manageable.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),