POI工具類,對Excle文件的每行數據 映射爲VO

我們在日常工作中,對Excle的操作是很頻繁的。爲了方便使用。我們想把對應的每一行數據轉換爲VO。以下是項目中常用的工具類。

這裏解決了合併單元格的問題了。

解析需要引用Jar包:


  poi-3.9-20121203.jar;

poi-ooxml-schemas-3.9-20121203.jar

poi-ooxml-3.9-20121203.jar

poi-scratchpad-3.9-20121203.jar

xmlbeans-2.3.0.jar

stax-api-1.0.1.jar

dom4j-1.6.1.jar


Maven構建

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.9</version>
</dependency>


如果只是解析2003版的話,包可以不加這麼多。我這個是2003、2007版都可以解析的。

package wsc.com.it.excel;



import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;


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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class ExcelParseUtil {


@SuppressWarnings({ "unchecked", "unused" })
public static void main(String[] args) throws Exception {
ExcelParseUtil excelParse = new ExcelParseUtil();
String fileName = "parse.xlsx";
File file = new File(fileName);
String sheetName = "ExcleVO";
int beginRow = 1;
String strKeys = "username,password";//注意,一定要與Excel的標題相同,VO最好也相同
List<ExcelVO> excelList = new ArrayList<ExcelVO>();
excelList = (List<ExcelVO>) excelParse.importExcelFile(file, fileName,
sheetName, beginRow, ExcelVO.class, strKeys);



for (ExcelVO excelVO : excelList) {
System.out.println(excelVO.getUsername() +"     s"+excelVO.getPassword());

}
}


private static final int VERSION2003 = 2003;
private static final int VERSION2007 = 2007;
private int version = 2003;


// 解析並取得Excel文件 的數據
private List<?> importExcelFile(File file, String fileName,
String sheetName, int beginRow, Class<?> objClass, String strKeys)
throws Exception {
String[] strKey = strKeys.split(",");
Workbook workbook = getWbByInVserion(file, fileName);
Sheet sheet = workbook.getSheet(sheetName);
return getSheetData(sheet, beginRow, objClass, strKey);
}


// 獲取Excel文件的版本
private Workbook getWbByInVserion(File file, String fileName) {
Workbook workbook = null;
InputStream stream = null;
if (".xls".equalsIgnoreCase(fileName.substring(fileName
.lastIndexOf(".")))) {
version = VERSION2003;
} else if (".xlsx".equalsIgnoreCase(fileName.substring(fileName
.lastIndexOf(".")))
|| ".xlsm".equalsIgnoreCase(fileName.substring(fileName
.lastIndexOf(".")))) {
version = VERSION2007;
} else {
System.out.println("文件格式不正確");
}


if (version == VERSION2003) {
try {
stream = new FileInputStream(file);
workbook = new HSSFWorkbook(stream);
} catch (IOException e1) {
System.out.println("文件沒有找到");
}
} else if (version == VERSION2007) {
try {
stream = new FileInputStream(file);
workbook = new XSSFWorkbook(stream);
} catch (IOException e1) {
System.out.println("文件沒有找到或者生成workWook有問題");
}
}


return workbook;
}


// 獲取Sheet表中的數據
private List<?> getSheetData(Sheet sheet, int beginRow, Class<?> objClass,
String[] strKey) throws Exception {
List<Object> objList = new ArrayList<Object>();
Object obj = objClass.newInstance();
int rowCountSize = sheet.getLastRowNum();
Row row = null;
for (int rowIndex = beginRow; rowIndex < rowCountSize; rowIndex++) {
row = sheet.getRow(rowIndex);
if (row != null) {
obj = getRowValueByStr(sheet, row, objClass, strKey);
objList.add(obj);
}
}
return objList;
}


// 把每一行對解析爲一個VO
private Object getRowValueByStr(Sheet sheet, Row row, Class<?> objClass,
String[] strKey) throws Exception {
Object obj = objClass.newInstance();
// 判斷單元格是否爲空
boolean cellValueFlag = false;
// 反射
PropertyDescriptor pd = null;
Method method = null;
String cellValue = null;
for (short keyIndex = 0; keyIndex < strKey.length; keyIndex++) {
pd = new PropertyDescriptor(strKey[keyIndex], objClass);
method = pd.getWriteMethod();
if (method == null) {
throw new Exception();
}
cellValue = getCellValueWithmerge(sheet, row.getCell(keyIndex));
cellValue = Pattern.compile("^\\s*|\\s*$").matcher(cellValue)
.replaceAll("");
method.invoke(obj, cellValue);
if (cellValue != null || "".equals(cellValue)) {
cellValueFlag = true;
}
}


if (cellValueFlag) {
return obj;
} else {
return null;
}
}


// 獲取合併單元格的數據
private String getCellValueWithmerge(Sheet sheet, Cell cell) {
int sheetMergeCount = sheet.getNumMergedRegions();
int firstColumn = 0;
int lastColumn = 0;
int firstRow = 0;
int lastRow = 0;
CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 0);
for (int i = 0; i < sheetMergeCount; i++) {
cellRangeAddress = sheet.getMergedRegion(i);
firstColumn = cellRangeAddress.getFirstColumn();
lastColumn = cellRangeAddress.getLastColumn();
firstRow = cellRangeAddress.getFirstRow();
lastRow = cellRangeAddress.getLastRow();
}
if (cell != null) {
if (cell.getRowIndex() >= firstRow && cell.getRowIndex() <= lastRow) {
if (cell.getColumnIndex() >= firstColumn
&& cell.getColumnIndex() <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellStringValue(fCell);
}
}
}
return getCellStringValue(cell);
}


// 取得單元格的值
private String getCellStringValue(Cell cell) {
if (cell == null) {
return "";
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return String.valueOf(cell.getBooleanCellValue());
} else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {//公式
try {
return String.valueOf((long)cell.getNumericCellValue());
} catch (Exception e) {
return String.valueOf(cell.getRichStringCellValue());
}
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {//數字
if (HSSFDateUtil.isCellDateFormatted(cell)) {//日期格式
Date dateValue = cell.getDateCellValue();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
return df.format(dateValue);
}else {
return String.valueOf((long)cell.getNumericCellValue());
}
} else {
return "";
}
}
}


class ExcelVO {


private String username ;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章