新版
2022.04.29新增一个版本
maven依赖(可用于生产环境)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.8</version>
<exclusions>
<exclusion>
<artifactId>servlet-api</artifactId>
<groupId>javax.servlet</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8</version>
</dependency>
2、将Excl导入工具类,直接可使用内置main()测试方法
新增说明:
1.支持导出xlsx,且低内存版本;
2.好像添加了一种读取excel的方式;
import com.google.common.collect.Lists;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
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;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* @author liming
* @since 2021/7/14 10:44
*/
public class ExcelUtil {
private final Logger logger = LoggerFactory.getLogger(getClass());
private final static String excel2003L = ".xls"; //2003以下版本的excel
private final static String excel2007U = ".xlsx"; //2007以上版本的excel
/**
* 将excel的列名转换成数组所在位置(从0开始)
* @param colStr 文字
* @param length 文字长度
* @return 列所在数组位置(从0开始)
*/
public int excelColStrToIndex(String colStr, int length) {
int num;
int result = 0;
for(int i = 0; i < length; i++) {
char ch = colStr.charAt(length - i - 1);
num = (ch - 'A' + 1) ;
num *= Math.pow(26, i);
result += num;
}
return result-1;
}
/**
* 将数组的index转换成excel中的列名(从0开始)
* @param columnIndex 数组的Index
* @return excel的列名
*/
public String excelColIndexToStr(int columnIndex) {
columnIndex ++;
if (columnIndex <= 0) {
return null;
}
String columnStr = "";
columnIndex--;
do {
if (columnStr.length() > 0) {
columnIndex--;
}
columnStr = ((char) (columnIndex % 26 + (int) 'A')) + columnStr;
columnIndex = (int) ((columnIndex - columnIndex % 26) / 26);
} while (columnIndex > 0);
return columnStr;
}
/**
* 描述:获取IO流中的数据,组装成List<String[]>对象
* @param file 物理文件地址
* @param index 第几张工作簿(以0开始)
* @param startRow 工作簿中行开始(以0开始)
* @param startCol 工作簿中列开始(以0开始)
* @param length 从startCol开始,读取几列数据
* @return list
* @throws Exception
*/
public List<String[]> getExcelData(File file, int index, int startRow, int startCol, int length) throws Exception {
List<String[]> list = null;
// 创建Excel工作薄
Workbook work = this.getWorkbook(file);
if (null == work) {
throw new Exception("Excel为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
List<Object> tampList = null;
list = new ArrayList<>();
// 获取需要的excel工作簿
sheet = work.getSheetAt(index);
if (sheet == null) {
throw new Exception("Excel工作薄为空!");
}
//遍历当前sheet中的所有行
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
//遍历所有的列
tampList = new ArrayList<>();
for (int y = startCol; y < length; y++) {
cell = row.getCell(y);
if (cell != null) {
tampList.add(this.getCellValue(cell));
} else {
tampList.add("");
}
}
list.add(tampList.toArray(new String[0]));
}
return list;
}
/**
* 从excel中获取数据
* @param file 物理文件地址
* @param sheetNumber 第几张工作簿(以0为起点)
* @param beginRow 从第几行开始(以1为起点)
* @param beginColumn 从第几列开始(以0为起点)
* @param columnSize 每行数据获取多少列(以1开始)
* @return List
* @throws Exception 错误信息
*/
public List<List<String>> getExcelDataList(File file, int sheetNumber, int beginRow, int beginColumn, int columnSize) throws Exception {
// 获取excel
Workbook work = this.getWorkbook(file);
if (null == work) {
throw new Exception("Excel为空!");
}
// 获取需要的excel工作簿
Sheet sheet = work.getSheetAt(sheetNumber);
if (sheet == null) {
throw new Exception("Excel工作薄为空!");
}
List<List<String>> responseList = new ArrayList<>();
//遍历当前sheet中的所有行
Row row = null;
Cell cell = null;
List<String> tampList = null;
for (int i = beginRow; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
//遍历所有的列
tampList = new ArrayList<>();
for (int y = beginColumn; y < columnSize; y++) {
cell = row.getCell(y);
tampList.add(this.getCellValueToString(cell));
}
responseList.add(tampList);
}
return responseList;
}
/**
* 描述:获取IO流中的数据,组装成List<Object[]>对象
* @param file spring的文件流
* @param fileType 文件后缀
* @param index 第几张工作簿(以0开始)
* @param startRow 工作簿中第行开始(以0开始)
* @param length 每行里列的长度
* @return
* @throws Exception
*/
public List<Object[]> getExcelData(MultipartFile file, String fileType, int index, int startRow, int length) {
List<Object[]> list = null;
// 创建Excel工作薄
Workbook work = null;
try {
work = this.getWorkbook(file, fileType);
} catch (Exception e) {
logger.error(e.getMessage());
e.printStackTrace();
}
if (null == work) {
return Lists.newArrayList();
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
List<Object> tampList = null;
list = new ArrayList<Object[]>();
// 获取需要的excel工作簿
sheet = work.getSheetAt(index);
if (sheet == null) {
logger.error("Excel工作薄为空!");
return Lists.newArrayList();
}
//遍历当前sheet中的所有行
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
//遍历所有的列
tampList = new ArrayList<>();
for (int y = 0; y < length; y++) {
cell = row.getCell(y);
if (cell == null){
tampList.add("");
} else {
tampList.add(this.getCellValue(cell));
}
}
list.add(tampList.toArray());
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param file
* @return
* @throws Exception
*/
public Workbook getWorkbook(File file) throws Exception {
Workbook wb = null;
String fileType = file.getName().substring(file.getName().lastIndexOf("."));
//2003以下
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(new FileInputStream(file));
}
//2007以上
else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(new FileInputStream(file));
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param file
* @return
* @throws Exception
*/
public Workbook getWorkbook(MultipartFile file, String fileType) throws Exception {
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
Workbook wb = null;
//2003以下
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(inputStream);
}
//2007以上
else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(inputStream);
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell 单元格
* @return
*/
public Object getCellValue(Cell cell) {
if (Objects.isNull(cell)) {
return "";
}
//用String接收所有返回的值
String value = null;
//格式化number String字符
DecimalFormat df = new DecimalFormat("0");
//日期格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//格式化数字
DecimalFormat df2 = new DecimalFormat("0.00");
switch (cell.getCellType()) {
//String类型的数据
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
//数值类型(取值用cell.getNumericCellValue() 或cell.getDateCellValue())
case Cell.CELL_TYPE_NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
//Boolean类型
case Cell.CELL_TYPE_BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
//表达式类型
case Cell.CELL_TYPE_FORMULA:
value = String.valueOf(cell.getCellFormula());
break;
//异常类型 不知道何时算异常
case Cell.CELL_TYPE_ERROR:
value = String.valueOf(cell.getErrorCellValue());
break;
//空,不知道何时算空
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
value = "";
break;
}
return value;
}
/**
* 描述:对表格中数值进行格式化
* @param cell 单元格
* @return 单元格数据
*/
public String getCellValueToString(Cell cell) {
if (Objects.isNull(cell)) {
return null;
}
//用String接收所有返回的值
String value = null;
//格式化number String字符
DecimalFormat df = new DecimalFormat("0");
//日期格式化
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
//格式化数字
DecimalFormat df2 = new DecimalFormat("0.00");
switch (cell.getCellType()) {
//String类型的数据
case Cell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
//数值类型(取值用cell.getNumericCellValue() 或cell.getDateCellValue())
case Cell.CELL_TYPE_NUMERIC:
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
//Boolean类型
case Cell.CELL_TYPE_BOOLEAN:
value = String.valueOf(cell.getBooleanCellValue());
break;
//表达式类型
case Cell.CELL_TYPE_FORMULA:
value = String.valueOf(cell.getCellFormula());
break;
//异常类型 不知道何时算异常
case Cell.CELL_TYPE_ERROR:
value = String.valueOf(cell.getErrorCellValue());
break;
//空,不知道何时算空
case Cell.CELL_TYPE_BLANK:
value = "";
break;
default:
value = "";
break;
}
if ("".equals(value)) {
value = null;
}
return value;
}
/**
* 导出excel到指定路径
* @param list 数据
* @param filePath 文件保存路径
* @throws IOException 错误
*/
public void exportListToXls(List<String[]> list, String filePath) throws IOException {
//创建HSSFWorkbook对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建HSSFSheet对象
HSSFSheet sheet = wb.createSheet("sheet0");
for (int i = 0; i < list.size(); i++) {
String[] strings = list.get(i);
//创建HSSFRow对象
HSSFRow row = sheet.createRow(i);
for (int i1 = 0; i1 < strings.length; i1++) {
//创建HSSFCell对象
HSSFCell cell = row.createCell(i1);
//设置单元格的值
cell.setCellValue(strings[i1]);
}
}
File file = new File(filePath);
if (!file.isFile()) {
if (!file.getParentFile().isDirectory()) {
file.getParentFile().mkdirs();
}
}
//输出Excel文件
FileOutputStream output = new FileOutputStream(filePath);
wb.write(output);
output.flush();
output.close();
wb = null;
output = null;
}
/**
* 导出excel到指定路径
* @param list 数据
* @param filePath 文件保存路径
* @throws IOException 错误
*/
public void exportListToXlsx(List<String[]> list, String filePath) throws IOException {
//创建HSSFWorkbook对象
SXSSFWorkbook wb = new SXSSFWorkbook();
//创建HSSFSheet对象
Sheet sheet = wb.createSheet("数据");
for (int i = 0; i < list.size(); i++) {
String[] strings = list.get(i);
//创建HSSFRow对象
Row row = sheet.createRow(i);
for (int i1 = 0; i1 < strings.length; i1++) {
//创建HSSFCell对象
Cell cell = row.createCell(i1);
//设置单元格的值
cell.setCellValue(strings[i1]);
}
}
File file = new File(filePath);
if (!file.isFile()) {
if (!file.getParentFile().isDirectory()) {
file.getParentFile().mkdirs();
}
}
//输出Excel文件
FileOutputStream output = new FileOutputStream(filePath);
wb.write(output);
output.flush();
output.close();
wb = null;
output = null;
}
}
旧版
1、依赖包
maven依赖(3.6是比较稳定的版本,可用于生产环境)
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.6</version>
</dependency>
2、将Excl导入工具类,直接可使用内置main()测试方法
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* @description: POI 工具类
* @author: Leemeea
* @create: 2019-07-25 16:48
*/
public class ExcelUtil {
private final static String excel2003L = ".xls"; //2003以下版本的excel
private final static String excel2007U = ".xlsx"; //2007以上版本的excel
/**
* 描述:获取IO流中的数据,组装成List<Object[]>对象
* @param file 物理文件地址
* @param index 第几张工作簿(以0开始)
* @param startRow 工作簿中第行开始(以0开始)
* @return
* @throws Exception
*/
public List<Object[]> getExcelData(File file, int index, int startRow) throws Exception {
List<Object[]> list = null;
// 创建Excel工作薄
Workbook work = this.getWorkbook(file);
if (null == work) {
throw new Exception("Excel为空!");
}
Sheet sheet = null;
Row row = null;
Cell cell = null;
List<Object> tampList = null;
list = new ArrayList<Object[]>();
// 获取需要的excel工作簿
sheet = work.getSheetAt(index);
if (sheet == null) {
throw new Exception("Excel工作薄为空!");
}
//遍历当前sheet中的所有行
for (int i = startRow; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
//遍历所有的列
tampList = new ArrayList<Object>();
for (int y = 0; y < row.getLastCellNum(); y++) {
cell = row.getCell(y);
tampList.add(this.getCellValue(cell));
}
list.add(tampList.toArray());
}
return list;
}
/**
* 描述:根据文件后缀,自适应上传文件的版本
* @param file
* @return
* @throws Exception
*/
public Workbook getWorkbook(File file) throws Exception {
Workbook wb = null;
String fileType = file.getName().substring(file.getName().lastIndexOf("."));
if (excel2003L.equals(fileType)) {
wb = new HSSFWorkbook(new FileInputStream(file)); //2003以下
} else if (excel2007U.equals(fileType)) {
wb = new XSSFWorkbook(new FileInputStream(file)); //2007以上
} else {
throw new Exception("解析的文件格式有误!");
}
return wb;
}
/**
* 描述:对表格中数值进行格式化
* @param cell
* @return
*/
public Object getCellValue(Cell cell) {
//用String接收所有返回的值
String value = null;
DecimalFormat df = new DecimalFormat("0"); //格式化number String字符
SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd"); //日期格式化
DecimalFormat df2 = new DecimalFormat("0.00"); //格式化数字
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING: //String类型的数据
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC: //数值类型(取值用cell.getNumericCellValue() 或cell.getDateCellValue())
if ("General".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if (HSSFDateUtil.isCellDateFormatted(cell)) {
value = sdf.format(HSSFDateUtil.getJavaDate(cell.getNumericCellValue()));
} else {
value = df2.format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean类型
value = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //表达式类型
value = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_ERROR: //异常类型 不知道何时算异常
value = String.valueOf(cell.getErrorCellValue());
break;
case Cell.CELL_TYPE_BLANK: //空,不知道何时算空
value = "";
break;
default:
value = "";
break;
}
if (value.equals("") || value == null) {
value = "";
}
if (cell == null) {
return "";
}
return value;
}
//读取excel里的字段
public static void main(String[] args) {
ExcelUtil importExcelUtil = new ExcelUtil();
//excel 导入数据demo
File file = new File("C:\\Users\\Sin\\Desktop\\111.xlsx");
List<Object[]> dataList = null;
try {
dataList = importExcelUtil.getExcelData(file, 0, 0);
} catch (Exception e) {
e.printStackTrace();
}
//数据封装格式一,将表格中的数据遍历取出后封装进对象放进List
for (int i = 0; i < dataList.size(); i++) {
System.out.println("----------------"+dataList.get(i).length);
for (Object obj: dataList.get(i) ) {
System.out.println(obj);
}
}
}
}
把代码放入项目可以直接调用