package com.demo.commons.utils;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@Slf4j
public class ExcelUtils implements Serializable {
private static Workbook getWk(MultipartFile file) throws IOException {
Workbook workbook = null;
if (Objects.requireNonNull(file.getOriginalFilename()).endsWith("xls")) {
workbook = new HSSFWorkbook(file.getInputStream());
} else if (file.getOriginalFilename().endsWith("xlsx")) {
workbook = new XSSFWorkbook(file.getInputStream());
}
return workbook;
}
public static List<String[]> excelToArrayList(MultipartFile file, int sheetNumber) throws IOException {
ArrayList<String[]> resultList = new ArrayList<>();
try {
Sheet sheet = getWk(file).getSheetAt(sheetNumber);
int rsRows = sheet.getRow(0) == null ? -1 : sheet.getLastRowNum();
for (int i = 0; i <= rsRows; i++) {
Row row = sheet.getRow(i);
if (!isRowEmpty(row)) {
int cellCount = row.getLastCellNum();
if (cellCount > 0) {
String[] objects = new String[cellCount];
for (int j = 0; j < cellCount; j++) {
objects[j] = getCellValue(row.getCell(j));
}
resultList.add(objects);
}
}
}
} catch (Exception e) {
log.error("Read excel error.", e);
throw e;
}
return resultList;
}
private static String getCellValue(Cell cell) {
String cellvalue;
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_BLANK:
cellvalue = "";
break;
case Cell.CELL_TYPE_BOOLEAN:
cellvalue = Boolean.toString(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
cellvalue = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(cell.getDateCellValue());
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String temp = cell.getStringCellValue();
if (temp.contains(".")) {
cellvalue = String.valueOf(new Double(temp)).trim();
} else {
cellvalue = temp.trim();
}
}
break;
case Cell.CELL_TYPE_STRING:
cellvalue = cell.getStringCellValue().trim();
break;
case Cell.CELL_TYPE_ERROR:
cellvalue = "";
break;
case Cell.CELL_TYPE_FORMULA:
cell.setCellType(Cell.CELL_TYPE_STRING);
cellvalue = cell.getStringCellValue();
if (cellvalue != null) {
cellvalue = cellvalue.replaceAll("#N/A", "").trim();
}
break;
default:
cellvalue = "";
break;
}
} else {
cellvalue = "";
}
return cellvalue;
}
public static String getSheetName(MultipartFile file, int num) throws IOException {
return getWk(file).getSheetName(num);
}
private static boolean isRowEmpty(Row row) {
if (null != row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK)
return false;
}
}
return true;
}
public static void exportExcel(HttpServletResponse response, String fileName, List<String> title, List<List<String>> excelData) throws IOException {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(fileName);
sheet.setDefaultColumnWidth(10);
HSSFRow headrow = sheet.createRow(0);
for (int i = 0; i < title.size(); i++) {
HSSFCell cell = headrow.createCell(i);
HSSFRichTextString text = new HSSFRichTextString(title.get(i));
cell.setCellValue(text);
}
int rows = 1;
for (List<String> excelDatum : excelData) {
HSSFRow row = sheet.createRow(rows++);
for (int j = 0; j < excelDatum.size(); j++) {
HSSFCell cell = row.createCell(j);
HSSFRichTextString text = new HSSFRichTextString(excelDatum.get(j));
cell.setCellValue(text);
}
}
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes("gb2312"), "ISO8859-1"));
response.flushBuffer();
workbook.write(response.getOutputStream());
}
}
Maven依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10.1</version>
</dependency>