Java 如何讀取Excel格式xls、xlsx數(shù)據(jù)工具類
Java 讀取Excel格式xls、xlsx數(shù)據(jù)工具類
需要POI的jar包支持

調(diào)用方式
ReadExcelTest excelTest = new ReadExcelTest();
excelTest.readExcel("D:\\data1.xlsx");
package com.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
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 org.apache.xmlbeans.impl.piccolo.io.FileFormatException;
public class ReadExcelTest {
private static final String EXTENSION_XLS = "xls";
private static final String EXTENSION_XLSX = "xlsx";
/***
* <pre>
* 取得Workbook對(duì)象(xls和xlsx對(duì)象不同,不過(guò)都是Workbook的實(shí)現(xiàn)類)
* xls:HSSFWorkbook
* xlsx:XSSFWorkbook
* @param filePath
* @return
* @throws IOException
* </pre>
*/
private Workbook getWorkbook(String filePath) throws IOException {
Workbook workbook = null;
InputStream is = new FileInputStream(filePath);
if (filePath.endsWith(EXTENSION_XLS)) {
workbook = new HSSFWorkbook(is);
} else if (filePath.endsWith(EXTENSION_XLSX)) {
workbook = new XSSFWorkbook(is);
}
return workbook;
}
/**
* 文件檢查
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
private void preReadCheck(String filePath) throws FileNotFoundException, FileFormatException {
// 常規(guī)檢查
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException("傳入的文件不存在:" + filePath);
}
if (!(filePath.endsWith(EXTENSION_XLS) || filePath.endsWith(EXTENSION_XLSX))) {
throw new FileFormatException("傳入的文件不是excel");
}
}
/**
* 讀取excel文件內(nèi)容
* @param filePath
* @throws FileNotFoundException
* @throws FileFormatException
*/
public void readExcel(String filePath) throws FileNotFoundException, FileFormatException {
// 檢查
this.preReadCheck(filePath);
// 獲取workbook對(duì)象
Workbook workbook = null;
try {
workbook = this.getWorkbook(filePath);
// 讀文件 一個(gè)sheet一個(gè)sheet地讀取
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
System.out.println("=======================" + sheet.getSheetName() + "=========================");
int firstRowIndex = sheet.getFirstRowNum();
int lastRowIndex = sheet.getLastRowNum();
// 讀取首行 即,表頭
Row firstRow = sheet.getRow(firstRowIndex);
for (int i = firstRow.getFirstCellNum(); i <= firstRow.getLastCellNum(); i++) {
Cell cell = firstRow.getCell(i);
String cellValue = this.getCellValue(cell, true);
System.out.print(" " + cellValue + "\t");
}
System.out.println("");
// 讀取數(shù)據(jù)行
for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
Row currentRow = sheet.getRow(rowIndex);// 當(dāng)前行
int firstColumnIndex = currentRow.getFirstCellNum(); // 首列
int lastColumnIndex = currentRow.getLastCellNum();// 最后一列
for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
Cell currentCell = currentRow.getCell(columnIndex);// 當(dāng)前單元格
String currentCellValue = this.getCellValue(currentCell, true);// 當(dāng)前單元格的值
System.out.print(currentCellValue + "\t");
}
System.out.println("");
}
System.out.println("======================================================");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (workbook != null) {
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 取單元格的值
* @param cell 單元格對(duì)象
* @param treatAsStr 為true時(shí),當(dāng)做文本來(lái)取值 (取到的是文本,不會(huì)把“1”取成“1.0”)
* @return
*/
private String getCellValue(Cell cell, boolean treatAsStr) {
if (cell == null) {
return "";
}
if (treatAsStr) {
// 雖然excel中設(shè)置的都是文本,但是數(shù)字文本還被讀錯(cuò),如“1”取成“1.0”
// 加上下面這句,臨時(shí)把它當(dāng)做文本來(lái)讀取
cell.setCellType(Cell.CELL_TYPE_STRING);
}
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
} else {
return String.valueOf(cell.getStringCellValue());
}
}
}
使用poi讀取xlsx格式的Excel總結(jié)
今天遇到的坑
公司實(shí)習(xí)生項(xiàng)目,其中有個(gè)功能是讀取Excel數(shù)據(jù),之前做過(guò)以為很快就能搞定,萬(wàn)萬(wàn)沒(méi)想到,本地寫的一切都正常,可就在要發(fā)布生產(chǎn)了,尼瑪測(cè)試環(huán)境居然出bug了讀取xlsx格式的Excel,讀不了,本地完全可以,就是測(cè)試環(huán)境上不行,心里一萬(wàn)只曹尼瑪奔過(guò)
下面是代碼部分:
我使用的是springmvc,首先是controller部分
@RequestMapping("ReadFromExcel")
@ResponseBody
public Response ReadFromExcel(@RequestParam(value = "file") MultipartFile file,
@RequestAttribute("userNo") String userNo) {
try {
//校驗(yàn)文件
checkFile(file);
List<ArrayList<String>> list =excelService.readExcel(file);
if (CollectionUtils.isEmpty(list)) {
return new Response(ERROR_CODE, "導(dǎo)入的文件沒(méi)有數(shù)據(jù)",false);
}
}catch (Exception e){
logger.error("ReadFromExcel異常",e);
}
return new Response(ERROR_CODE, "導(dǎo)入失敗", false);
}
private void checkFile(MultipartFile file) throws IOException {
//判斷文件是否存在
if(null == file){
logger.error("文件不存在!");
throw new FileNotFoundException("文件不存在!");
}
//獲得文件名
String fileName = file.getOriginalFilename();
logger.info("ReadFromExcel fileName",fileName);
//判斷文件是否是excel文件
if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){
logger.error(fileName + "不是excel文件");
throw new IOException(fileName + "不是excel文件");
}
}
然后是讀取Excel文件部分,也就是service部分
這些網(wǎng)上隨便一搜都能搜到
@Override
public List<ArrayList<String>> readExcel(MultipartFile file) {
List<ArrayList<String>> list = new ArrayList<ArrayList<String>>();
try {
// 檢查文件
logger.info("ExcelServiceImpl 獲取文件名", file.getOriginalFilename());
// 獲得Workbook工作薄對(duì)象
Workbook workbook = getWorkBook(file);
// 創(chuàng)建返回對(duì)象,把每行中的值作為一個(gè)數(shù)組,所有行作為一個(gè)集合返回
logger.info("獲得Workbook工作薄對(duì)象", file.getOriginalFilename());
if (workbook != null) {
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
// 獲得當(dāng)前sheet工作表
Sheet sheet = workbook.getSheetAt(sheetNum);
logger.info("獲得當(dāng)前sheet工作表", file.getOriginalFilename());
if (sheet == null) {
continue;
}
// 獲得當(dāng)前sheet的開(kāi)始行
int firstRowNum = sheet.getFirstRowNum();
// 獲得當(dāng)前sheet的結(jié)束行
int lastRowNum = sheet.getLastRowNum();
// 循環(huán)除了第一行的所有行
for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
// 獲得當(dāng)前行
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
// 獲得當(dāng)前行的開(kāi)始列
int firstCellNum = row.getFirstCellNum();
// 獲得當(dāng)前行的列數(shù)
int lastCellNum = row.getPhysicalNumberOfCells();
ArrayList<String> cells = new ArrayList<>();
// 循環(huán)當(dāng)前行
for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
Cell cell = row.getCell(cellNum);
cells.add(getCellValue(cell));
}
list.add(cells);
}
}
}
} catch (Exception e) {
logger.error("readExcel Exception", e.getMessage());
}
return list;
}
private Workbook getWorkBook(MultipartFile file) {
// 獲得文件名
String fileName = file.getOriginalFilename();
// 創(chuàng)建Workbook工作薄對(duì)象,表示整個(gè)excel
Workbook workbook = null;
try {
// 獲取excel文件的io流
InputStream is = file.getInputStream();
logger.info("獲取excel文件的io流");
// 根據(jù)文件后綴名不同(xls和xlsx)獲得不同的Workbook實(shí)現(xiàn)類對(duì)象
if (fileName.endsWith(xls)) {
// 2003
workbook = new HSSFWorkbook(is);
} else if (fileName.endsWith(xlsx)) {
// 2007
workbook = new XSSFWorkbook(is);
}
} catch (Exception e) {
logger.info(e.getMessage());
}
return workbook;
}
private String getCellValue(Cell cell) {
String cellValue = "";
if (cell == null) {
return cellValue;
}
// 把數(shù)字當(dāng)成String來(lái)讀,避免出現(xiàn)1讀成1.0的情況
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
cell.setCellType(Cell.CELL_TYPE_STRING);
}
// 判斷數(shù)據(jù)的類型
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 數(shù)字
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;
}
spring-servlet.xml 配置如下
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxUploadSize" value="10485760000"/> <property name="maxInMemorySize" value="40960"/> </bean>
最初的maven是這么配置的
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency>
好了,本地走起來(lái)完全沒(méi)毛病,很開(kāi)心,終于可以發(fā)布了,可以早點(diǎn)回學(xué)校寫論文了,發(fā)到測(cè)試環(huán)境,測(cè)試讀取xls也是沒(méi)毛病,可尼瑪,想讀取個(gè)xlsx的文件試試看,網(wǎng)頁(yè)提示404,這什么鬼,打日志查問(wèn)題,還一直以為是前端的哥們出問(wèn)題,可一看日志不對(duì)啊,請(qǐng)求已經(jīng)進(jìn)來(lái)了,可是走到這一步就沒(méi)了 workbook = new XSSFWorkbook(is);這是為什么,趕緊網(wǎng)上查,一堆解決方案,一個(gè)個(gè)試,最后實(shí)在沒(méi)辦法把別人所有的方法一個(gè)個(gè)試,最后又加了如下jar包
<dependency> <groupId>xmlbeans</groupId> <artifactId>xmlbeans</artifactId> <version>2.3.0</version> <type>pom</type> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml-schemas</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-scratchpad</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-examples</artifactId> <version>3.9</version> </dependency>
問(wèn)題是解決了,可卻不知其所以然,記錄一下。以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
IDEA2023.3.4開(kāi)啟SpringBoot項(xiàng)目的熱部署(圖文)
本文使用的開(kāi)發(fā)工具是idea,使用的是springboot框架開(kāi)發(fā)的項(xiàng)目,配置熱部署,可以提高開(kāi)發(fā)效率,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2024-02-02
手把手教你如何利用SpringBoot實(shí)現(xiàn)審核功能
審核功能經(jīng)過(guò)幾個(gè)小時(shí)的奮戰(zhàn)終于完成了,現(xiàn)在我就與廣大網(wǎng)友分享我的成果,這篇文章主要給大家介紹了關(guān)于如何利用SpringBoot實(shí)現(xiàn)審核功能的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05
Spring的BeanFactoryPostProcessor接口示例代碼詳解
這篇文章主要介紹了Spring的BeanFactoryPostProcessor接口,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-02-02
Linux下Java Python啟動(dòng)管理腳本方便程序管理
這篇文章主要為大家介紹了Linux下Java/Python啟動(dòng)管理腳本方便程序管理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11
Java連接Linux服務(wù)器過(guò)程分析(附代碼)
這篇文章主要介紹了Java連接Linux服務(wù)器過(guò)程分析(附代碼),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12
通過(guò)實(shí)例學(xué)習(xí)JAVA對(duì)象轉(zhuǎn)成XML輸出
這篇文章主要介紹了通過(guò)實(shí)例學(xué)習(xí)JAVA對(duì)象轉(zhuǎn)成XML輸出,做流程圖的項(xiàng)目時(shí),新的流程定義為xml的,需要對(duì)xml與java對(duì)象進(jìn)行互轉(zhuǎn),下面我們來(lái)深入學(xué)習(xí),需要的朋友可以參考下2019-06-06

