搜尋
首頁Javajava教程Java如何實作超大Excel檔案解析

一、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();
			}
}
 
}

Java如何實作超大Excel檔案解析

二、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;
    }
}

Java如何實作超大Excel檔案解析

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

以上是Java如何實作超大Excel檔案解析的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除
JVM中的類加載程序子系統如何促進平台獨立性?JVM中的類加載程序子系統如何促進平台獨立性?Apr 23, 2025 am 12:14 AM

類加載器通過統一的類文件格式、動態加載、雙親委派模型和平台無關的字節碼,確保Java程序在不同平台上的一致性和兼容性,實現平台獨立性。

Java編譯器會產生特定於平台的代碼嗎?解釋。Java編譯器會產生特定於平台的代碼嗎?解釋。Apr 23, 2025 am 12:09 AM

Java編譯器生成的代碼是平台無關的,但最終執行的代碼是平台特定的。 1.Java源代碼編譯成平台無關的字節碼。 2.JVM將字節碼轉換為特定平台的機器碼,確保跨平台運行但性能可能不同。

JVM如何處理不同操作系統的多線程?JVM如何處理不同操作系統的多線程?Apr 23, 2025 am 12:07 AM

多線程在現代編程中重要,因為它能提高程序的響應性和資源利用率,並處理複雜的並發任務。 JVM通過線程映射、調度機制和同步鎖機制,在不同操作系統上確保多線程的一致性和高效性。

在Java的背景下,'平台獨立性”意味著什麼?在Java的背景下,'平台獨立性”意味著什麼?Apr 23, 2025 am 12:05 AM

Java的平台獨立性是指編寫的代碼可以在任何安裝了JVM的平台上運行,無需修改。 1)Java源代碼編譯成字節碼,2)字節碼由JVM解釋執行,3)JVM提供內存管理和垃圾回收功能,確保程序在不同操作系統上運行。

Java應用程序仍然可以遇到平台特定的錯誤或問題嗎?Java應用程序仍然可以遇到平台特定的錯誤或問題嗎?Apr 23, 2025 am 12:03 AM

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

雲計算如何影響Java平台獨立性的重要性?雲計算如何影響Java平台獨立性的重要性?Apr 22, 2025 pm 07:05 PM

云计算显著提升了Java的平台独立性。1)Java代码编译为字节码,由JVM在不同操作系统上执行,确保跨平台运行。2)使用Docker和Kubernetes部署Java应用,提高可移植性和可扩展性。

Java的平台獨立性在廣泛採用中扮演著什麼角色?Java的平台獨立性在廣泛採用中扮演著什麼角色?Apr 22, 2025 pm 06:53 PM

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

容器化技術(例如Docker)如何影響Java平台獨立性的重要性?容器化技術(例如Docker)如何影響Java平台獨立性的重要性?Apr 22, 2025 pm 06:49 PM

容器化技術如Docker增強而非替代Java的平台獨立性。 1)確保跨環境的一致性,2)管理依賴性,包括特定JVM版本,3)簡化部署過程,使Java應用更具適應性和易管理性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)