SpringBoot 에서 엑셀 표 의 예제 코드 를 읽 습 니 다.
8561 단어 SpringBootexcel표.
함께 토론 하여 여러 사내 들 에 게 배우다.
CEO 에 게 다가 가 백부 미 를 맞이 하 다.
pom.xml 의존
<!--springboot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<!--springboot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--excel-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--mysql-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
POIUtils 도구 클래스
public class POIUtils {
private final static String xls = "xls";
private final static String xlsx = "xlsx";
private final static String DATE_FORMAT = "yyyy/MM/dd";
/**
* excel ,
* @param file
* @throws IOException
*/
public static List<String> readExcel(MultipartFile file) throws IOException {
//
checkFile(file);
// Workbook
Workbook workbook = getWorkBook(file);
// , ,
// List<String[]> list = new ArrayList<String[]>();
List<String> list = new ArrayList<>();
if(workbook != null){
for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
// sheet
Sheet sheet = workbook.getSheetAt(sheetNum);
if(sheet == null){
continue;
}
// sheet
int firstRowNum = sheet.getFirstRowNum();
// sheet
int lastRowNum = sheet.getLastRowNum();
//
for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){
//
Row row = sheet.getRow(rowNum);
if(row == null){
continue;
}
//
int firstCellNum = row.getFirstCellNum();
//
int lastCellNum = row.getPhysicalNumberOfCells();
// String[] cells = new String[row.getPhysicalNumberOfCells()];
//
for(int cellNum = firstCellNum; cellNum <= lastCellNum;cellNum++){
Cell cell = row.getCell(cellNum);
// cells[cellNum] = getCellValue(cell);
String cellValue = getCellValue(cell);
list.add(cellValue);
}
}
}
workbook.close();
}
return list;
}
//
public static void checkFile(MultipartFile file) throws IOException{
//
if(null == file){
throw new FileNotFoundException(" !");
}
//
String fileName = file.getOriginalFilename();
// excel
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
throw new IOException(fileName + " excel ");
}
}
public static Workbook getWorkBook(MultipartFile file) {
//
String fileName = file.getOriginalFilename();
// Workbook , excel
Workbook workbook = null;
try {
// excel io
InputStream is = file.getInputStream();
// (xls xlsx) Workbook
if(fileName.endsWith(xls)){
//2003
workbook = new HSSFWorkbook(is);
}else if(fileName.endsWith(xlsx)){
//2007
workbook = new XSSFWorkbook(is);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static String getCellValue(Cell cell){
String cellValue = "";
if(cell == null){
return cellValue;
}
// ,
String dataFormatString = cell.getCellStyle().getDataFormatString();
if(dataFormatString.equals("m/d/yy")){
cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
return cellValue;
}
// String , 1 1.0
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
cell.setCellType(Cell.CELL_TYPE_STRING);
}
//
switch (cell.getCellType()){
case Cell.CELL_TYPE_NUMERIC: //
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING: //
cellValue = String.valueOf(cell.getStringCellValue());
break;
case Cell.CELL_TYPE_BOOLEAN: //Boolean
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA: //
cellValue = String.valueOf(cell.getCellFormula());
break;
case Cell.CELL_TYPE_BLANK: //
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR: //
cellValue = " ";
break;
default:
cellValue = " ";
break;
}
return cellValue;
}
}
컨트롤 러 테스트
@RestController
@RequestMapping("/excel")
public class ExcelController {
@PostMapping("/look")
public void look(@RequestParam("excelFile") MultipartFile excelFile){
try {
List<String> list = POIUtils.readExcel(excelFile);
// list.removeIf(Objects::isNull); null
//
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
if (iterator.next() == ""){
iterator.remove();
}
}
// list,
for (String s : list) {
System.out.println(s);
}
// map pojo ,
Map<String,Object> map = new HashMap<>();
map.put("plan",list.get(0));
map.put("er",list.get(2));
map.put("date",list.get(4));
System.out.println(map);
} catch (IOException e) {
e.printStackTrace();
}
}
}
액세스 테스트콘 솔 출력
2020 년도 심사 계획
작성 자:
장삼
시간:
2020/10/10
심사 근거:
1233211234567
심사 목적:
12345555556984552368
내신 팀장:
장기
내신 부 팀장:
불리다
심사 그룹:
제1 조
장 사
이유
릴.
세 시
제2 조
장 오
왕유
왕 기
사대부
{date=2020/10/10,plan=2020 년도 심사 계획,er=장 3}
문제 에 주의 하 다
excel 표 에서 날짜 나 시간 은 자바 에서 읽 을 때 수치 형식 으로 읽 습 니 다.10-10 월-2020 을 얻 었 기 때문에 엑셀 표 날짜 형식의 데 이 터 는 사용자 정의 형식 으로 형식 을 설정 합 니 다.(육친
여기 서 SpringBoot 가 엑셀 표를 읽 는 예제 코드 에 관 한 글 은 여기까지 소개 되 었 습 니 다.더 많은 SpringBoot 가 엑셀 표를 읽 는 내용 은 예전 의 글 을 검색 하거나 아래 의 관련 글 을 계속 찾 아 보 세 요.앞으로 저 희 를 많이 사랑 해 주세요!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
【Java・SpringBoot・Thymeleaf】 에러 메세지를 구현(SpringBoot 어플리케이션 실천편 3)로그인하여 사용자 목록을 표시하는 응용 프로그램을 만들고, Spring에서의 개발에 대해 공부하겠습니다 🌟 마지막 데이터 바인딩에 계속 바인딩 실패 시 오류 메시지를 구현합니다. 마지막 기사🌟 src/main/res...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.