没有废话,直接上代码。
1.相关jar包。
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
2.实例程序整体结构
ExcelDataVO:实体类;
PoiExcelRead:读取本地Excel数据;
PoiExcelWrite:数据写入新建Excel;
PoiExcelExport:导出新建Excel;
PoiExcel:测试类。
package com.springboot.util; import java.math.BigDecimal; /** * @Date : 2020/7/8 16:00 * @Description : */ public class ExcelDataVO { private String name; private String remake; private long amount; private long lastAmount; private float percent; private float propertyRate; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getRemake() { return remake; } public void setRemake(String remake) { this.remake = remake; } public long getAmount() { return amount; } public void setAmount(long amount) { this.amount = amount; } public long getLastAmount() { return lastAmount; } public void setLastAmount(long lastAmount) { this.lastAmount = lastAmount; } public float getPercent() { return percent; } public void setPercent(float percent) { this.percent = percent; } public float getPropertyRate() { return propertyRate; } public void setPropertyRate(float propertyRate) { this.propertyRate = propertyRate; } }
package com.springboot.util; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.*; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.*; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; /** * @Date : 2020/7/8 14:27 * @Description : */ public class PoiExcelRead { private static Logger logger = Logger.getLogger(PoiExcelRead.class.getName()); // 日志打印类 private static final String XLS = "xls"; private static final String XLSX = "xlsx"; /** * 根据文件后缀名类型获取对应的工作簿对象 * * @param inputStream 读取文件的输入流 * @param fileType 文件后缀名类型(xls或xlsx) * @return 包含文件数据的工作簿对象 * @throws IOException */ public static Workbook getWorkbook(InputStream inputStream, String fileType) throws IOException { Workbook workbook = null; if (fileType.equalsIgnoreCase(XLS)) { workbook = new HSSFWorkbook(inputStream); } else if (fileType.equalsIgnoreCase(XLSX)) { workbook = new XSSFWorkbook(inputStream); } return workbook; } /** * 读取Excel文件内容 * * @param fileName 要读取的Excel文件所在路径 * @return 读取结果列表,读取失败时返回null */ public static List<ExcelDataVO> readExcel(String fileName) { Workbook workbook = null; FileInputStream inputStream = null; try { // 获取Excel后缀名 String fileType = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); // 获取Excel文件 File excelFile = new File(fileName); if (!excelFile.exists()) { logger.warning("指定的Excel文件不存在!"); return null; } // 获取Excel工作簿 inputStream = new FileInputStream(excelFile); workbook = getWorkbook(inputStream, fileType); // 读取excel中的数据 List<ExcelDataVO> resultDataList =