POI對Excel進行讀取操作,工具類,便於操作資料
一:首先POI對Excel 操作進行了一系列的封裝,匯入,匯出Excel這裡藉助於POI提供的jar包
專案當中匯入POI提供的Jar包,這裡使用Maven管理
進行匯入jar包
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.14</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.14</version>
</dependency>
二:所有的Jar包匯入成功後,需要寫讀取Excel的方法
public class ReadExcelUtils {
private Logger logger = Logger.getLogger(ReadExcelUtils.class);
private static DecimalFormat df = new DecimalFormat("0");
private Workbook wb;
private Sheet sheet;
private Row row;
public ReadExcelUtils(String filepath) {
if (filepath == null) {
return;
}
String ext = filepath.substring(filepath.lastIndexOf("."));
try {
InputStream is = new FileInputStream(filepath);
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(is);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(is);
} else {
wb = null;
}
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
}
public ReadExcelUtils(InputStream in, String fileName) throws IllegalArgumentException {
if (in == null || StringUtils.isBlank(fileName)) {
throw new IllegalArgumentException();
}
String ext = fileName.substring(fileName.lastIndexOf("."));
try {
if (".xls".equals(ext)) {
wb = new HSSFWorkbook(in);
} else if (".xlsx".equals(ext)) {
wb = new XSSFWorkbook(in);
} else {
wb = null;
}
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException", e);
} catch (IOException e) {
logger.error("IOException", e);
}
}
/**
* 讀取Excel表格表頭的內容
*
* @return String 表頭內容的陣列
* @author zengwendong
*/
public String[] readExcelTitle() throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(0);
// 標題總列數
int colNum = row.getPhysicalNumberOfCells();
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = row.getCell(i).getStringCellValue();
}
return title;
}
/**
* 讀取Excel表格表頭的內容
*
* @return String 表頭內容的陣列
* startHeader 表頭開始行數
* @author zengwendong
*/
public String[] readExcelTitleHeader(Integer startHeader) throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(startHeader);
// 標題總列數
int colNum = row.getPhysicalNumberOfCells();
String[] title = new String[colNum];
for (int i = 0; i < colNum; i++) {
title[i] = row.getCell(i).getStringCellValue();
}
return title;
}
/**
* 讀取Excel資料內容
*
* @return Map 包含單元格資料內容的Map物件
* @author zengwendong
*/
public Map<Integer, Map<Integer, Object>> readExcelContent() throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
Map<Integer, Map<Integer, Object>> content = new HashMap<Integer, Map<Integer, Object>>();
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
String obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.put(i, cellValue);
}
return content;
}
/**
* 讀取Excel資料內容
*
* @return Map 包含單元格資料內容的Map物件
* @author zengwendong
*/
public List<Map<Integer, Object>> readExcelList() throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
List<Map<Integer, Object>> content = new ArrayList<>();
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
String obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.add(cellValue);
}
return content;
}
/**
* 讀取Excel資料內容
*
* @return Map 包含單元格資料內容的Map物件
* @author zengwendong
*/
public List<Map<Integer, Object>> readExcelListHeader(Integer header) throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
List<Map<Integer, Object>> content = new ArrayList<>();
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = header; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<Integer, Object> cellValue = new HashMap<Integer, Object>();
while (j < colNum) {
String obj = getCellFormatValue(row.getCell(j));
cellValue.put(j, obj);
j++;
}
content.add(cellValue);
}
return content;
}
/**
* 工具類 Map<String,Object> 為表頭對應的資料 String 表頭 Object 對應的資料
* [{社群(行政村)名稱=330327888121}, {社群(行政村)名稱=83303888882121}]
* @return
* @throws Exception
*/
public List<Map<String, Object>> readExcelList1() throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
List<Map<String, Object>> content = new ArrayList<>();
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
String[] titles = this.readExcelTitle();
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
int j = 0;
Map<String, Object> cellValue = new HashMap<String, Object>();
while (j < colNum) {
String obj = getCellFormatValue(row.getCell(j));
System.out.println(obj);
cellValue.put(titles[j], obj);
j++;
}
content.add(cellValue);
}
return content;
}
public List<String> readExcelColContext(int colNum) throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
List<String> columnList = new ArrayList<String>();
sheet = wb.getSheetAt(0);
// 得到總行數
int rowNum = sheet.getLastRowNum();
row = sheet.getRow(0);
// int colNum = row.getPhysicalNumberOfCells();
// 正文內容應該從第二行開始,第一行為表頭的標題
for (int i = 1; i <= rowNum; i++) {
row = sheet.getRow(i);
Object obj = getCellFormatValue(row.getCell(colNum));
columnList.add(obj.toString());
}
return columnList;
}
/**
* 根據Cell型別設定資料
*
* @param cell
* @return
* @author zengwendong
*/
private String getCellFormatValue(Cell cell) {
String cellvalue = "";
if (cell != null) {
// 判斷當前Cell的Type
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:{// 如果當前Cell的Type為NUMERIC
//如果為時間格式的內容
if (HSSFDateUtil.isCellDateFormatted(cell)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小時為12小時制,若要24小時制,則把小h變為H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
cellvalue=sdf.format(HSSFDateUtil.getJavaDate(cell.
getNumericCellValue())).toString();
break;
} else {
cellvalue = df.format(cell.getNumericCellValue());
// cellvalue = new DecimalFormat("0").format(cell.getNumericCellValue());
}
break;
}
case Cell.CELL_TYPE_STRING:// 如果當前Cell的Type為STRING
// 取得當前的Cell字串
cellvalue = cell.getStringCellValue().toString();
break;
default:// 預設的Cell值
cellvalue = "";
}
} else {
cellvalue = "";
}
return cellvalue;
}
/**
* 新增單元格值
*
* @param cellValue1
* @param cellValue2
* @param colNum1
* @param colNum2
* @throws Exception
*/
public void addCellValue(String cellValue1, String cellValue2, int colNum1, int colNum2, int rowNum) throws Exception {
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
sheet = wb.getSheetAt(0);
row = sheet.getRow(rowNum);
row.getCell(colNum1).setCellValue(cellValue1);
row.getCell(colNum2).setCellValue(cellValue2);
}
/**
* 儲存工作薄
*
* @param excelPath
*/
public void saveExcel(String excelPath) throws Exception{
if (wb == null) {
throw new Exception("Workbook物件為空!");
}
FileOutputStream fileOut;
fileOut = new FileOutputStream(excelPath);
wb.write(fileOut);
fileOut.close();
}
通過上述ReadExcelUtils工具類就可以獲取到Excel的表內容
三:測試
通過main方法進行讀取Excel表中資料進行測試
這裡取一個方法測試:
定義的Excel表
public static void main (String[] args) throws Exception {
ReadExcelUtils excel = new ReadExcelUtils("C:\\Users\\Herbert\\Desktop\\測試.xlsx");
List<Map<Integer, Object>> readExcelList = excel.readExcelList();
System.out.println(readExcelList);
}
後臺輸出
[{0=張三, 1=男, 2=23}, {0=李四, 1=女, 2=24}, {0=王五, 1=男, 2=25}]
說明我們已經拿到Excel中的資料
讀取Excel表頭
public static void main(String[] args) throws Exception {
ReadExcelUtils excel = new ReadExcelUtils ("C:\\Users\\Herbert\\Desktop\\測試.xlsx");
String[] readExcelList = excel.readExcelTitleHeader(0);
for(String str :readExcelList){
System.out.println(str);
}
}
後臺輸出
說明讀取Excel表頭也是可以的
歡迎關注公眾號
Good Luck ! ! !