Java利用POI讀寫Excel文件工具類
更新時間:2020年12月31日 10:41:24 作者:Lieforlove
這篇文章主要為大家詳細介紹了Java利用POI讀寫Excel文件的工具類,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了Java讀寫Excel文件工具類的具體代碼,供大家參考,具體內(nèi)容如下
package com.test.app.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
/**
* @Description: Excel讀寫工具類
* @Author: hunger.zhu
* @CreateDate: 2019/4/10 13:21
*/
public class ExcelUtils {
private static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
/**
* 讀取Excel內(nèi)容
* @param file 需要被讀的文件對象
* @param startRow 從哪一行開始讀 (rowIndex從0開始的)
* @param isExcel2003 是否是excel2003還是更高的版本
* @param sheetIndex 讀取哪一個sheet (sheetIndex也是從0開始)
* @return List<List<String>>
* @throws Exception
*/
public static List<List<String>> readExcel(File file, int startRow, boolean isExcel2003, int sheetIndex) throws Exception {
List<List<String>> dataLst;
InputStream is = null;
try {
/** 創(chuàng)建讀取文件的輸入流 */
is = new FileInputStream(file);
/** 根據(jù)版本選擇創(chuàng)建Workbook的方式 */
Workbook wb;
if (isExcel2003) {
wb = new HSSFWorkbook(is);
} else {
wb = new XSSFWorkbook(is);
}
/** 調(diào)用本類的讀取方法讀取excel數(shù)據(jù) */
dataLst = read(wb, startRow, sheetIndex);
} catch (Exception ex) {
logger.error("讀取excel文件異常!", ex);
ex.printStackTrace();
throw ex;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/** 返回最后讀取的結(jié)果 */
return dataLst;
}
private static List<List<String>> read(Workbook wb, int startRow, int sheetIndex) {
/** 總列數(shù) */
int totalCells = 0;
/** 創(chuàng)建集合存儲讀取的數(shù)據(jù) */
List<List<String>> dataLst = new ArrayList<List<String>>();
/** 得到第一個shell */
Sheet sheet = wb.getSheetAt(sheetIndex);
/** 得到Excel的行數(shù) */
int totalRows = sheet.getPhysicalNumberOfRows();
/** 得到Excel的列數(shù) */
if (totalRows >= 1 && sheet.getRow(0) != null) {
totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
}
/** 循環(huán)Excel的行 */
for (int r = startRow; ; r++) {
Row row = sheet.getRow(r);
if (row == null) {
break;
}
List<String> rowLst = new ArrayList<String>();
/** 循環(huán)Excel的列 */
for (int c = 0; c < totalCells; c++) {
Cell cell = row.getCell(c);
String cellValue = "";
if (null != cell) {
// 以下是判斷數(shù)據(jù)的類型
switch (cell.getCellTypeEnum()) {
case NUMERIC: // 數(shù)字
// 判斷是不是日期格式
if (HSSFDateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue() + "";
}else {
cellValue = cell.getNumericCellValue() + "";
}
break;
case STRING: // 字符串
cellValue = cell.getStringCellValue();
break;
case BOOLEAN: // Boolean
cellValue = cell.getBooleanCellValue() + "";
break;
case FORMULA: // 公式
cellValue = cell.getCellFormula() + "";
break;
case BLANK: // 空值
cellValue = "";
break;
case ERROR: // 故障
cellValue = "非法字符";
break;
default:
cellValue = "未知類型";
break;
}
}
rowLst.add(cellValue);
}
/** 保存第r行的第c列 */
boolean isEmptyRow = true;
if (rowLst != null) {
for (String s : rowLst) {
if (s != null && !s.isEmpty()) {
isEmptyRow = false;
}
}
}
if (!isEmptyRow) {
dataLst.add(rowLst);
}
}
return dataLst;
}
/**
* 讀取Excel內(nèi)容
* @param filePath 被讀取文件的絕對路徑
* @param startRow
* @param isExcel2003
* @param sheetIndex
* @return List<List<String>>
* @throws Exception
*/
public static List<List<String>> readExcel(String filePath, int startRow, boolean isExcel2003, int sheetIndex) throws Exception {
return readExcel(new File(filePath) , startRow, isExcel2003, sheetIndex);
}
/**
* 將數(shù)據(jù)寫入Excel工作簿
* @param header 表格的標(biāo)題
* @param dataList 所需寫入的數(shù)據(jù) List<List<String>>
* @param isExcel2003 是否是excel2003還是更高的版本
* @param sheetName 生成的excel中sheet的名字
* @return Workbook 之后直接寫出即可,如workbook.write(new FileOutputStream("E://test/20190410_test.xlsx"));
*/
public static Workbook getWorkbookFromList(List<String> header, List<List<String>> dataList, boolean isExcel2003,
String sheetName) {
Workbook wb;
// 創(chuàng)建Workbook對象(excel的文檔對象)
if (isExcel2003) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
// 建立新的sheet對象(excel的表單)
Sheet sheet = wb.createSheet(sheetName);
// 在sheet里創(chuàng)建第一行,參數(shù)為行索引(excel的行),可以是0~65535之間的任何一個
int rowNum = 0;
Row row0 = sheet.createRow(rowNum);
if (!CollectionUtils.isEmpty(header)) {
// 設(shè)置表頭
for (int i = 0; i < header.size(); i++) {
Cell cell = row0.createCell(i);
// 設(shè)置單元格樣式
cell.setCellStyle(POIUtils.getCellStyle(wb, "Calibri", (short) 12));
// 設(shè)置列寬
sheet.setColumnWidth(i, 256 * 20);
cell.setCellValue(header.get(i));
}
rowNum++;
}
if (!CollectionUtils.isEmpty(dataList)) {
// 填充數(shù)據(jù)
for (List<String> cellList : dataList) {
Row row = sheet.createRow(rowNum);
for (int i = 0; i < cellList.size(); i++) {
Cell cell = row.createCell(i);
cell.setCellStyle(POIUtils.getCellStyle(wb, "Calibri", (short) 12));
if (CollectionUtils.isEmpty(header)) {
sheet.setColumnWidth(i, 256 * 20);
}
cell.setCellValue(cellList.get(i));
}
rowNum++;
}
}
return wb;
}
/**
* 將數(shù)據(jù)寫入Excel工作簿
* @param header 表格的標(biāo)題
* @param dataList 所需寫入的數(shù)據(jù) List<Object>
* @param isExcel2003 是否是excel2003還是更高的版本
* @param sheetName 生成的excel中sheet的名字
* @return Workbook對象,之后直接寫出即可,如workbook.write(new FileOutputStream("E://test/20190410_test.xlsx"));
* @throws Exception
*/
public static Workbook getWorkbookFromObj(List<String> header, List<?> dataList, boolean isExcel2003,
String sheetName) throws Exception {
Workbook wb;
// 創(chuàng)建Workbook對象(excel的文檔對象)
if (isExcel2003) {
wb = new HSSFWorkbook();
} else {
wb = new XSSFWorkbook();
}
// 建立新的sheet對象(excel的表單)
Sheet sheet = wb.createSheet(sheetName);
// 在sheet里創(chuàng)建第一行,參數(shù)為行索引(excel的行),可以是0~65535之間的任何一個
int rowNum = 0;
Row row0 = sheet.createRow(rowNum);
if (!CollectionUtils.isEmpty(header)) {
// 設(shè)置表頭
for (int i = 0; i < header.size(); i++) {
Cell cell = row0.createCell(i);
// 設(shè)置單元格樣式
cell.setCellStyle(POIUtils.getCellStyle(wb, "Calibri", (short) 12));
sheet.setColumnWidth(i, 256 * 20);
cell.setCellValue(header.get(i));
}
rowNum++;
}
if (!CollectionUtils.isEmpty(dataList)) {
// 填充數(shù)據(jù)
Class<? extends Object> objClass = dataList.get(0).getClass();
Field[] fields = objClass.getDeclaredFields();
for (int i = 0; i < dataList.size(); i++) {
// 創(chuàng)建row對象
Row row = sheet.createRow(rowNum);
// 遍歷獲取每一個字段的值
for (int j = 0; j < fields.length; j++) {
String fieldVal = "";
Method[] methods = objClass.getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equalsIgnoreCase("get" + fields[j].getName())) {
String property = (String) method.invoke(dataList.get(i), null);
fieldVal = property == null ? "" : property;
break;
}
}
Cell cell = row.createCell(j);
cell.setCellStyle(POIUtils.getCellStyle(wb, "Calibri", (short) 12));
if (CollectionUtils.isEmpty(header)) {
sheet.setColumnWidth(j, 256 * 20);
}
cell.setCellValue(fieldVal);
}
rowNum++;
}
}
return wb;
}
public static boolean validateExcel(String filePath) {
/** 檢查文件名是否為空或者是否是Excel格式的文件 */
if (filePath == null
|| !(isExcel2003(filePath) || isExcel2007(filePath))) {
// "文件名不是excel格式";
return false;
}
/** 檢查文件是否存在 */
File file = new File(filePath);
if (file == null || !file.exists()) {
// "文件不存在";
return false;
}
return true;
}
public static boolean isExcel2003(String filePath) {
return filePath.matches("^.+\\.(?i)(xls)$");
}
public static boolean isExcel2007(String filePath) {
return filePath.matches("^.+\\.(?i)(xlsx)$");
}
}
以下為POIUtils.java:
package com.test.app.utils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.awt.*;
import java.awt.Color;
/**
* @Description: Excel的單元格樣式
* @Author: hunger.zhu
* @CreateDate: 2019/4/10 13:05
*/
public class POIUtils {
/**
* 設(shè)置單元格的邊框(細)且為黑色,字體水平垂直居中,自動換行
* @param workbook
* @param fontName
* @param fontSize
* @return
*/
public static CellStyle getCellStyle(Workbook workbook, String fontName, short fontSize){
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
// 設(shè)置上下左右四個邊框?qū)挾?
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
// 設(shè)置上下左右四個邊框顏色
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
style.setLeftBorderColor(IndexedColors.BLACK.getIndex());
style.setRightBorderColor(IndexedColors.BLACK.getIndex());
// 水平居中,垂直居中,自動換行
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
style.setWrapText(false);
// 設(shè)置字體樣式及大小
font.setFontName(fontName);
font.setFontHeightInPoints(fontSize);
style.setFont(font);
return style;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot2 整合Nacos組件及環(huán)境搭建和入門案例解析
這篇文章主要介紹了SpringBoot2 整合Nacos組件,環(huán)境搭建和入門案例詳解,在整合springboot2時注意版本 0.2.x.RELEASE 對應(yīng)的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 對應(yīng)的是 Spring Boot 1.x 版本,具體內(nèi)容詳情跟隨小編一起看看吧2022-03-03
IDEA 錯誤 No main class specified的問題
這篇文章主要介紹了IDEA 錯誤 No main class specified的問題,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04
Spring Boot集成MyBatis實現(xiàn)通用Mapper的配置及使用
關(guān)于MyBatis,大部分人都很熟悉。MyBatis 是一款優(yōu)秀的持久層框架,它支持定制化 SQL、存儲過程以及高級映射。這篇文章主要介紹了Spring Boot集成MyBatis實現(xiàn)通用Mapper,需要的朋友可以參考下2018-08-08
Spring如何替換掉默認common-logging.jar
這篇文章主要介紹了Spring如何替換掉默認common-logging.jar,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-05-05

