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;
}

}
发布了77 篇原创文章 · 获赞 9 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/wscwsc58888/article/details/13005245
vo