java 讀取excel數據 poi導入excel 數據 java實現導入excel數據
一、說明
1、在實際開發中,可能有需求需要將excel導入到業務系統中,具體實現可以使用Apache poi 來實現。
2、依賴pom如下:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
二、代碼實現
1、創建ExcelImport 類,實現excel數據導入
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
/**
* description: Excel 數據導入
* @version v1.0
* @author w
* @date 2020年3月30日下午9:46:27
**/
public class ExcelImport {
private ExcelImport INSTANSE = new ExcelImport();
/**
* excel 2003 suffix
*/
private static final String EXCEL_XLS_SUFFIX = ".xls" ;
/**
* excel 2007 或以上 suffix
*/
private static final String EXCEL_XLSX_SUFFIX = ".xlsx";
/**
* 分隔符 "."
*/
public static final String POINT = ".";
/**
* description: 讀取excel數據
* @param file
* @return List<List<Object>>
* @version v1.0
* @author w
* @date 2020年3月31日 下午3:36:39
*/
public static List<List<Object>> importFile (File file) throws Exception{
if(file == null) {
return null ;
}
if(file.getName().endsWith(EXCEL_XLS_SUFFIX)) {
return readXls(new FileInputStream(file));
}
if(file.getName().endsWith(EXCEL_XLSX_SUFFIX)) {
return readXlsx(new FileInputStream(file));
}
throw new RuntimeException("文件不對,必須是excel文件,後綴名以:"+EXCEL_XLS_SUFFIX + " 或者 "+ EXCEL_XLSX_SUFFIX);
}
/**
* description: 導入excel --- 支持web
* @param fileName
* @param inputStream
* @throws Exception
* @return List<List<Object>>
* @version v1.0
* @author w
* @date 2020年3月31日 下午4:51:01
*/
public static List<List<Object>> importFile (MultipartFile multipartFile) throws Exception{
if(multipartFile == null) {
return null ;
}
if(multipartFile.getOriginalFilename().endsWith(EXCEL_XLS_SUFFIX)) {
return readXls(multipartFile.getInputStream());
}
if(multipartFile.getOriginalFilename().endsWith(EXCEL_XLSX_SUFFIX)) {
return readXlsx(multipartFile.getInputStream());
}
throw new RuntimeException("文件不對,必須是excel文件,後綴名以:"+EXCEL_XLS_SUFFIX + " 或者 "+ EXCEL_XLSX_SUFFIX);
}
/**
* description: 讀取03版excel
* @param file
* @return List<List<Object>>
* @version v1.0
* @author w
* @date 2020年3月31日 下午3:38:44
*/
private static List<List<Object>> readXls(InputStream inputStream) throws Exception {
List<List<Object>> list = new ArrayList<>();
// 讀取excel
HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
// 獲取sheet 頁數量
int sheets = workbook.getNumberOfSheets();
for(int num = 0 ; num < sheets ; num++ ) {
HSSFSheet sheet = workbook.getSheetAt(num);
if(null == sheet) {
continue ;
}
// sheet 頁的總行數
int rows = sheet.getLastRowNum();
// startRow 開始讀取的行數 --- 第二行開始讀
for( int startRow = 1 ;startRow <= rows ; startRow ++) {
HSSFRow row = sheet.getRow(startRow);
List<Object> rowList = new ArrayList<>();
if(null != row) {
// row 行中的 單元格總個數
short cells = row.getLastCellNum();
for(int x = 0 ; x <= cells ; x++) {
HSSFCell cell = row.getCell(x);
if(null == cell) {
rowList.add("");
}else {
rowList.add(getXlsValue(cell));
}
}
list.add(rowList);
}
}
}
return list;
}
/**
* description: 獲取 03 版 excel數據
* @param cell
* @return String
* @version v1.0
* @author w
* @date 2020年3月31日 下午3:54:14
*/
private static String getXlsValue(HSSFCell cell) {
if ( cell.getCellType() == cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == cell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if(HSSFDateUtil.isCellDateFormatted(cell)){
Date date = HSSFDateUtil.getJavaDate(cell.getNumericCellValue());
cellValue = new SimpleDateFormat("yyyy/MM/dd").format(date);
}else{
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(cell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT)+1,cellValue.length());
if(strArr.equals("00")){
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
// 其他類型的值,統一設置爲 string
// http://blog.csdn.net/ysughw/article/details/9288307
cell.setCellType(Cell.CELL_TYPE_STRING);
return String.valueOf(cell.getStringCellValue());
}
}
/**
* description: 讀取07或以上版本的 excel
* @param file
* @throws Exception
* @return List<List<Object>>
* @version v1.0
* @author w
* @date 2020年3月31日 下午4:01:25
*/
private static List<List<Object>> readXlsx(InputStream inputStream) throws Exception {
List<List<Object>> list = new ArrayList<>();
// 讀取excel ,封裝到 XSSFWorkbook 對象
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
int sheets = workbook.getNumberOfSheets();
for(int num = 0 ;num < sheets ; num++) {
XSSFSheet sheet = workbook.getSheetAt(num);
if(null == sheet) {
continue ;
}
// 獲取sheet頁的總行數
int rows = sheet.getLastRowNum();
for(int startRow = 1 ; startRow <= rows ; startRow++ ) {
// startRow 開始讀取的行數, 從第二行開始讀取
XSSFRow row = sheet.getRow(startRow);
List<Object> rowList = new ArrayList<>();
if(null != row) {
// 獲取行總單元格個數
short cells = row.getLastCellNum();
for(int x = 0 ; x < cells ; x++) {
XSSFCell cell = row.getCell(x);
if(cell == null) {
rowList.add("");
}else {
rowList.add(getXlsxValue(cell));
}
}
list.add(rowList);
}
}
}
return list;
}
/**
* description: 獲取07或以上版本 excel 數據
* @param cell
* @return Object
* @version v1.0
* @author w
* @date 2020年3月31日 下午4:09:03
*/
private static Object getXlsxValue(XSSFCell cell) {
if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
String cellValue = "";
if (DateUtil.isCellDateFormatted(cell)) {
Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
cellValue = new SimpleDateFormat("yyyy/MM/dd").format(date);
} else {
DecimalFormat df = new DecimalFormat("#.##");
cellValue = df.format(cell.getNumericCellValue());
String strArr = cellValue.substring(cellValue.lastIndexOf(POINT) + 1, cellValue.length());
if (strArr.equals("00")) {
cellValue = cellValue.substring(0, cellValue.lastIndexOf(POINT));
}
}
return cellValue;
} else {
// 其他類型的值,統一設置爲 string
// http://blog.csdn.net/ysughw/article/details/9288307
//cell.setCellType(Cell.CELL_TYPE_STRING);
return String.valueOf(cell.getStringCellValue());
}
}
}
2、測試,直接本地測試 :
@Test
public void test() {
String path = "F:\\poi導出2.xlsx" ;
File file = new File(path);
try {
List<List<Object>> importFile = ExcelImport.importFile(file);
System.out.println(importFile);
} catch (Exception e) {
e.printStackTrace();
}
}
3、查看控制中輸出的數據和excel中的是否一致。
三、總結
1、本示例使用的是 poi 3.15版的,其他版本可能需要做部分調整。
2、對於導入excel數據類型轉換,不一定考慮到全部,請根據實際業務情況調整。
3、web情況下導入,請自行創建頁面測試,ExcelImport 類中已經提供對應的方法支持。
4、需要源碼請私聊我,謝謝。