poi實現匯入excel資料到資料庫工具類
阿新 • • 發佈:2019-01-05
前言
在日常開發中,我們經常會遇到excel資料的匯入匯出,這塊功能本身沒有什麼複雜的業務邏輯,只是需要一些簡單的工具類,這裡簡單實現一個讀取excel資料儲存到資料庫中(我們可能需要對excel中的資料進行比對挑選,符合條件的資料才儲存到資料庫中)。其實不管要不要做比對或者檢查,其原理都是一樣的。首先我們需要上傳excel檔案到指定目錄(當然這裡的excel檔案肯定要按照指定的模板來填寫資料,所以一般肯定有一個模板檔案),然後通過poi的工具類來讀取excel中的資料,在程式碼中讀取到excel的資料之後,我們再將合適的資料儲存到資料庫中,這裡不管你是通過jdbc,mybatis,還是hibernate來進行資料儲存,不管你是mysql,還是oracle。其原理都是一樣的,對於上傳檔案到指定目錄,這個對大家來說應該都是小菜一碟,所以我們這裡涉及的核心程式碼就是excel資料的讀取。
下面的工具類是基於poi的來讀取2003,2007版本的excel資料工具類。
具體程式碼
要使用poi我們需要在專案注入相關poi的jar包,這裡是基於poi3.12版本的pom依賴
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
<exclusions>
<exclusion>
<artifactId>commons-codec</artifactId >
<groupId>commons-codec</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency >
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.12</version>
</dependency>
接下來是具體的excel資料匯入工具類,已經測試過可以直接使用,程式碼中唯一需要修改的就是excel檔案的位置,這個可以根據自己的測試檔案位置來進行修改
public class ReadExcel {
/**
* 對外提供讀取excel 的方法
* */
public static List<List<Object>> readExcel(File file) throws IOException {
String fileName = file.getName();
String extension = fileName.lastIndexOf(".") == -1 ? "" : fileName
.substring(fileName.lastIndexOf(".") + 1);
if ("xls".equals(extension)) {
return read2003Excel(file);
} else if ("xlsx".equals(extension)) {
return read2007Excel(file);
} else {
throw new IOException("不支援的檔案型別");
}
}
/**
* 讀取 office 2003 excel
*
* @throws IOException
* @throws FileNotFoundException
*/
private static List<List<Object>> read2003Excel(File file) throws IOException {
List<List<Object>> list = new LinkedList<List<Object>>();
HSSFWorkbook hwb = new HSSFWorkbook(new FileInputStream(file));
HSSFSheet sheet = hwb.getSheetAt(0);
Object value = null;
HSSFRow row = null;
HSSFCell cell = null;
int counter = 0;
for (int i = sheet.getFirstRowNum(); counter < sheet
.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
} else {
counter++;
}
List<Object> linked = new LinkedList<Object>();
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
continue;
}
DecimalFormat df = new DecimalFormat("0");// 格式化 number String
// 字元
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");// 格式化日期字串
DecimalFormat nf = new DecimalFormat("0.00");// 格式化數字
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle()
.getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else {
value = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value = "";
break;
default:
value = cell.toString();
}
/*if (value == null || "".equals(value)) {
continue;
}*/
linked.add(value);
}
list.add(linked);
}
return list;
}
/**
* 讀取Office 2007 excel
* */
private static List<List<Object>> read2007Excel(File file) throws IOException {
List<List<Object>> list = new LinkedList<List<Object>>();
// 構造 XSSFWorkbook 物件,strPath 傳入檔案路徑
XSSFWorkbook xwb = new XSSFWorkbook(new FileInputStream(file));
// 讀取第一章表格內容
XSSFSheet sheet = xwb.getSheetAt(0);
Object value = null;
XSSFRow row = null;
XSSFCell cell = null;
int counter = 0;
for (int i = sheet.getFirstRowNum(); counter < sheet
.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
} else {
counter++;
}
List<Object> linked = new LinkedList<Object>();
for (int j = row.getFirstCellNum(); j <= row.getLastCellNum(); j++) {
cell = row.getCell(j);
if (cell == null) {
continue;
}
DecimalFormat df = new DecimalFormat("0");// 格式化 number String // 字元
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");// 格式化日期字串
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_STRING:
value = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_NUMERIC:
if ("@".equals(cell.getCellStyle().getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else if ("General".equals(cell.getCellStyle()
.getDataFormatString())) {
value = df.format(cell.getNumericCellValue());
} else {
value = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
}
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
value = cell.getBooleanCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
value = "";
break;
default:
value = cell.toString();
}
/*if (value == null || "".equals(value)) {
continue;
}*/
linked.add(value);
}
list.add(linked);
}
return list;
}
public static void main(String[] args) {
try {
List<List<Object>> excleDataList=readExcel(new File("C:\\aaaa.xlsx"));
for(int i=1;i<excleDataList.size();i++){
if(i==1){
System.out.println("excel中的第二行,第二列的值是"+excleDataList.get(1).get(1).toString());
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
我的本地測試結果是
原excel檔案的內容如下
總結
上面的工具類能夠讀取excel資料,但是有一點侷限性,就是如果excle中的資料比較多,poi的效能就不太給力了,所以如果單個excel中的資料量不是很大,可以採用這中方式來進行功能實現。