1. 程式人生 > >EXCEL多sheet頁公用類讀取方式

EXCEL多sheet頁公用類讀取方式

大概思路:

1.獲取前臺傳遞過來的FILE檔案及需要解析的XML檔案ID

XML 如下:

<?xml version="1.0" encoding="UTF-8" ?>
<excels>
<!-- 電力排程機構-->
<excel id="SCSERC-DLDUJG" class="excelTemplateReaderHorizontal">
<!--  用來封裝的class-->
<sheet name="本排程機構基本資訊" pojo="com.bsi.pojo.PowerDispatchOffice">

<row>
<cell index="0" title="企業名稱" property="enterpriseName"/>
<cell index="1" title="統一社會信用程式碼/組織機構程式碼" property="creditCode"/>
<cell index="2" title="企業所屬行業類別" property="qysshyClass"/>
<cell index="3" title="企業型別" property="qyClass"/>
<cell index="4" title="企業所在區域" property="qyRegion"/>
<cell index="5" title="企業住所" property="qyResidence"/>
<cell index="6" title="註冊資金" property="registeredCapital"/>
<cell index="7" title="註冊日期" property="registerDate"/>

</row>
</sheet>
<sheet name="本排程機構法定代表人基本資訊" pojo="com.bsi.pojo.PowerDispatchOffice">
<row>
<cell index="0" title="所在企業名稱" property="nameOfEnterprise"/>
<cell index="1" title="統一社會信用程式碼/組織機構程式碼" property="creditCode"/>
<cell index="2" title="法定代表人姓名" property="legalRepresentativeName"/>
<cell index="3" title="企業型別" property="qyClass"/>
<cell index="4" title="個人證件型別" property="personalPapersType"/>
<cell index="5" title="個人證件號碼" property="code"/>
<cell index="6" title="性別" property="sex"/>

</row>
</sheet>
<sheet name="市場主體不良行為資訊" pojo="com.bsi.pojo.PowerDispatchOffice">
<row>
<cell index="0" title="企業名稱" property="enterpriseName"/>
<cell index="1" title="統一社會信用程式碼/組織機構程式碼" property="creditCode"/>
<cell index="2" title="不良行為分類" property="blxwClass"/>
<cell index="3" title="不良行為描述" property="blxwDescribe"/>
<cell index="4" title="處理措施" property="handleStep"/>
<cell index="5" title="處理依據" property="handleBasis"/>
<cell index="6" title="處理日期" property="handleDate"/>
<cell index="7" title="處理單位" property="handleOffice"/>

</row>
</sheet>


</excel>
</excels>


2. 將其XML id 和FILE 檔案傳遞給ExcelTemplateDefine 模板 去解析XML

// 根據ID,取得對應的解析模板
Element e = ExcelReader.getInstance().getTreeElement(id);
parseExcel(id,e, file);

3. 呼叫parseExcel方法去解析EXCEL 


大致程式碼如下:


/**匯入處理
* @throws Exception */
@SuppressWarnings({ "rawtypes", "unchecked" })
public void importExcel() throws Exception {
excelTemplateDefine.execute(importFileType, importFile);
Map<String, List> dataMap = excelTemplateDefine.getParseDate();
Iterator<Entry<String,List>> it = dataMap.entrySet().iterator();
String success = "";
while (it.hasNext())     
{    
Entry<String, List> entry = (Entry<String, List>)it.next();
List list = entry.getValue();
for(int i=0;i<list.size();i++){
Object object  = excelEnterpriseService.saveAEnterprise(importFileType,list.get(i));
if(!object.equals("1")){
success += entry.getKey()+">>>>>"+ object ;
}
}
       
}
if(StringUtils.isNotBlank(success)){
JsonUtils.outputString(success, getResponse());
}else{
JsonUtils.outputString("資料匯入成功!", getResponse());
}


}


excelTemplateDefine.execute(importFileType, importFile);

方法如下:

package com.bsi.excel.parse;


import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;






import com.bsi.excel.exception.ExcelException;
import com.bsi.util.SpringUtil;
import com.bsi.util.StringUtils;


/**
 * 解析XML資料
 * 
 * 根據傳進去的模板,自動解析資料,並返回
 */
@Component("excelTemplateDefine")
@Scope("prototype")
public class ExcelTemplateDefine {


@SuppressWarnings("rawtypes")
private Map<String, List> parseDate;


private List<ExcelException> businessExceptionList;


@SuppressWarnings("rawtypes")
public void execute(String id, File file) throws Exception {
// init
parseDate = new HashMap<String, List>();
businessExceptionList = new ArrayList<ExcelException>();


// 根據ID,取得對應的解析模板
Element e = ExcelReader.getInstance().getTreeElement(id);
parseExcel(id,e, file);
}


@SuppressWarnings("rawtypes")
public void parseExcel(String idMoBan,Element e, File file) throws Exception {
Workbook workbook = new HSSFWorkbook(new FileInputStream(file));
List<Sheet> lists = getSheets(workbook);
for (Sheet sheet : lists) {
// 取得對應的service
if(e==null){continue;}
IExcelTemplateReader searvice = getService(e.attributeValue("class"));
System.out.println("開始解析sheet:" + sheet.getSheetName());
try {
Element sheetElement = getSheetElement(idMoBan,sheet.getSheetName(), e);
// 如果sheet是空的
if (sheetElement != null && sheetElement.attribute("noRead") == null) {
// 取得解析資料
List list = searvice.parseSheet(sheet, sheetElement);
// 進行驗證
// doValidate(sheetElement, list);
parseDate.put(sheet.getSheetName(), list);
}
} catch (Exception a) {
System.out.println(file.getAbsolutePath());
if (a instanceof ExcelException) {
ExcelException ec = (ExcelException) a;
ec.setPosition(ec.getPosition() + "," + sheet.getSheetName() + "工作薄");
}
throw a;
}
}
}


// 多執行緒匯入
@SuppressWarnings({ "rawtypes", "unchecked" })
public void doValidate(Element sheetElement, List list) throws Exception {
if (businessExceptionList == null) {
businessExceptionList = new ArrayList<ExcelException>();
}
Element element = sheetElement.element("validates");
if (element != null) {
List<Element> validateList = element.elements("validate");
if (validateList != null && !validateList.isEmpty()) {
for (Element validateE : validateList) {
String validateClassName = validateE.attributeValue("class");
if (StringUtils.isBlank(validateClassName)) {
validateClassName = "excelTemplaterHorizontalValidate";
}
// 遮蔽驗證
ExcelValidate excelValidate = (ExcelValidate) SpringUtil.getBean(validateClassName);
String pojoName = sheetElement.attributeValue("pojo");
excelValidate.execute(list, validateE, Class.forName(pojoName)); // 取得業務規則的異常
businessExceptionList.addAll(excelValidate.getExcelExceptionList());
}
}


}
}


private IExcelTemplateReader getService(String className) throws Exception {
IExcelTemplateReader searvice = (IExcelTemplateReader) SpringUtil.getBean(className);
return searvice;
}


// 取得所有sheet
public List<Sheet> getSheets(Workbook workbook) {
if (null != workbook) {
int sheetNum = workbook.getNumberOfSheets();
List<Sheet> sheets = new ArrayList<Sheet>();
for (int i = 0; i < sheetNum; i++) {
sheets.add(workbook.getSheetAt(i));
}
return sheets;
}
return null;
}


// 根據sheet名稱,取得解析的格式
@SuppressWarnings("unchecked")
public Element getSheetElement(String moBanId,String name, Element e ) throws Exception {
Element sheetElement = null;
// 預設的解析格式,沒有sheet的名稱
Element defaultElement = null;
List<Element> list = e.elements("sheet");
if (list != null && !list.isEmpty()) {
for (Element subElement : list) {
Attribute attribute = subElement.attribute("name");
if (attribute != null) {
if (name.equalsIgnoreCase(attribute.getValue())) {
sheetElement = subElement;
break;
}else if(StringUtils.isNotBlank(moBanId)&&moBanId.equals(attribute.getValue())){
sheetElement = subElement;
break;
}
} else {// 取得預設的解析格式
defaultElement = subElement;
}
}
}
// 根據sheet名稱,沒有找到對應的解析格式,則取預設的計解析格式
if (sheetElement == null) {
sheetElement = defaultElement;
}
return sheetElement;
}


@SuppressWarnings("rawtypes")
public Map<String, List> getParseDate() {
return parseDate;
}


@SuppressWarnings("rawtypes")
public void setParseDate(Map<String, List> parseDate) {
this.parseDate = parseDate;
}


public List<ExcelException> getBusinessExceptionList() {
return businessExceptionList;
}


public void setBusinessExceptionList(List<ExcelException> businessExceptionList) {
this.businessExceptionList = businessExceptionList;
}
}


解析模板類:

/**
 * 單例模式,讀取整個excel
 *
 */
public class ExcelReader {


private static ExcelReader instance;


private File file;


private ExcelReader() {
file = new File(FileUtil.getWebContentPath() + "exceltemplate");
}


public synchronized static ExcelReader getInstance() {
if (instance == null) {
instance = new ExcelReader();
}
return instance;
}


// 取得excel解析模板
@SuppressWarnings("unchecked")
public Element getTreeElement(String name) throws Exception {
if (file.exists() && file.isDirectory()) {
for (File inputXml : file.listFiles()) {//獲取專案中 exceltemplate資料夾下的所有的XML
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
Element employees = document.getRootElement();
List<Element> list = employees.elements();
for (Element employee : list) {
if (name.equals(employee.attribute("id").getValue())) {
System.out.println(inputXml.getAbsoluteFile());
return employee;
}
}
}
}
return null;
}
}



public class ExcelTemplateReaderHorizontal extends IExcelTemplateReader {


@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public List parseSheet(Sheet sheet, Element sheetElement) throws Exception {
this.sheet = sheet;


String pojoName = sheetElement.attributeValue("pojo");
// 初始化變數
List resultList = new ArrayList();
int rowNum = sheet.getPhysicalNumberOfRows();
if (rowNum > 0) {


rowElement = sheetElement.element("row");
List<Element> list = rowElement.elements("cell");
String subjectClass = sheet.getRow(0).getCell(0).getStringCellValue();
String infoClass = sheet.getRow(1).getCell(0).getStringCellValue();
String infoClassName = sheet.getRow(2).getCell(0).getStringCellValue();
for (x = 4; x < rowNum; x++) {
Row row = sheet.getRow(x);
if (row == null) {
continue;
}

try {
Object object = fillObject(subjectClass,infoClass,infoClassName,list, row, pojoName);
if (object != null)
resultList.add(object);
} catch (ExcelException e) {
e.setPosition("第" + (++x) + "行," + "第" + (++y) + "列");
throw e;
} catch (Exception e1) {
e1.printStackTrace();
ExcelException e = new ExcelException();
e.setMsg("資料格式不對!");
e.setPosition("第" + (++x) + "行," + "第" + (++y) + "列");
throw e;
}
/*if (cell_first != null) {

}else{//cell_first == null
Object object = fillObject(list, row, pojoName);
if (object != null){resultList.add(object);}
}*/
}
}
return resultList;
}


/**
*  預設:
*  1、指定匯入行範圍first last或者first lastKey
*  2、指定匯入行 range
*  3、如果第一個cell為數字,則表示該條記錄為可以用記錄sequence
*  4、根據cell的值來匯入
*  **/
private boolean canParse(Element rowElement, Cell cell_first) {
return canParseForNotNull(rowElement, cell_first) 
|| canParseForNum(rowElement, cell_first) 
|| canParseForFirst(rowElement, cell_first) 
|| canParseFoRrange(rowElement, cell_first);

}


private boolean canParseForNotNull(Element rowElement, Cell cell_first) {
Attribute cellValueRanger = rowElement.attribute("cellValueRanger");
if (cellValueRanger != null) {
return true;
}
return false;
}


private boolean canParseForNum(Element rowElement, Cell cell_first) {
Attribute attributeSequence = rowElement.attribute("sequence");
if (attributeSequence != null) {
String firsCelltValue = getMulCellValue(cell_first);
/*// 如果第一個cell為數字,則表示該條記錄為可以用記錄
return StringUtils.isNumeric(firsCelltValue);*/
return true;
}
return false;
}


private boolean canParseForFirst(Element rowElement, Cell cell_first) {
Attribute attribute = rowElement.attribute("first");
if (attribute != null) {
int first = Integer.parseInt(rowElement.attributeValue("first"));
if (first > x) {
return false;
}


Attribute attributeLast = rowElement.attribute("last");
if (attributeLast != null) {
int last = Integer.parseInt(attributeLast.getValue());
if (last >= x) {
return true;
}
}
attributeLast = rowElement.attribute("lastKey");
if (attributeLast != null) {
String firsCelltValue = getMulCellValue(cell_first);
String[] attributeValArray = attributeLast.getValue().split(",");
for (String str : attributeValArray) {
if ("".equals(str)) {
if (StringUtils.isBlank(firsCelltValue)) {
return false;
}
} else if (firsCelltValue.indexOf(str) >= 0) {
return false;
}
}
return true;
}


}
return false;
}


private boolean canParseFoRrange(Element rowElement, Cell cell_first) {
Attribute attributeRange = rowElement.attribute("range");
if (attributeRange != null) {
String ranges = attributeRange.getValue();
String[] array = ranges.split(",");
Set<String> strSet = new HashSet<String>(Arrays.asList(array));
if (strSet.contains(Integer.toString(x))) {
return true;
}
}
return false;
}

// 取得一行資料
private Object fillObject(String subjectClass,String infoClass,String infoClassName,List<Element> list, Row row, String pojoName) throws Exception {
if (StringUtils.isNotBlank(pojoName)) {
return fillObjectForModel( subjectClass, infoClass, infoClassName,list, row, pojoName);
} else {
return fillObjectForArray(list, row);
}
}


// 將一行的資料,轉換成物件
private Object fillObjectForModel(String subjectClass,String infoClass,String infoClassName,List<Element> list, Row row, String pojoName) throws Exception {
Object obj = Class.forName(pojoName).newInstance();


// 判斷是否根據cellValue來過濾
if (!cellValueRange(row)) {
return null;
}
String remark = "";
for (Element e : list) {
// cell的序號
y = Integer.parseInt(e.attributeValue("index"));
// 增加去重屬性
Attribute keArribute = e.attribute("key");
// pojo對應屬性名
String property = e.attributeValue("property");
Cell cell = row.getCell(y);
String cellVal =null;
if(y==0){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,請填寫資料!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}
if(property.equals("creditCode")){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,請填寫資料!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}else{
cellVal= getMulCellValue(cell);
Pattern p = Pattern.compile("//[^_IOZSVa-z\\W]{2}\\d{6}[^_IOZSVa-z\\W]{10}//g");   
Matcher matcher = p.matcher(cellVal);
Pattern pattern = Pattern.compile("//^([0-9A-Z]){8}-[0-9|X]$//");   
Matcher matchers = pattern.matcher(cellVal);
if(matcher.matches()==true||matchers.matches()==true){
// 增加對特殊行的處理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 轉換cell的值
Object converterResult = converterVal(e, cellVal);
// 將值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
continue;

}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,資料格式錯誤!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}
}
if(property.equals("code")){
if(cell==null){
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,請填寫資料!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}else{
cellVal= getMulCellValue(cell);
Pattern p = Pattern.compile("^\\d{15}$|^\\d{17}[0-9Xx]$");   
Matcher matcher = p.matcher(cellVal);
if(matcher.matches()==true){
// 增加對特殊行的處理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}
// 轉換cell的值
Object converterResult = converterVal(e, cellVal);
// 將值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
continue;

}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,資料格式錯誤!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
}

}
if(property.length()>4){
String date  = property.substring(property.length()-4,property.length());
if (cell == null) {
if(date.equals("Date")||date.equals("date")){
System.out.println(" property = " + property);
BeanMapper.setPropertyValue(obj, property, null);
continue;
}else{
System.out.println(" property = " + property);
BeanMapper.setPropertyValue(obj, property, "");
continue;
}
}
if(date.equals("Date")||date.equals("date")){
if(cell.getDateCellValue() instanceof Date){
BeanMapper.setPropertyValue(obj, property, cell.getDateCellValue());
}else{
System.out.println("第"+x + "行," + "第" + y + "列");
remark +="第"+x + "行," + "第" + y + "列,請填寫正確的日期 如:1997/7/8!,";
BeanMapper.setPropertyValue(obj, "remark", remark.substring(0,remark.length()-1));
continue;
}
 
}else{
cellVal= getMulCellValue(cell);
// 增加對特殊行的處理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}


// 轉換cell的值
Object converterResult = converterVal(e, cellVal);
// 將值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
}
}else{


cellVal= getMulCellValue(cell);
// 增加對特殊行的處理
if (isSpeciaRow(cellVal, row, obj)) {
return obj;
}
// 增加key去重
if (keArribute != null) {
if (keySet.contains(cellVal)) {
return null;
}
keySet.add(cellVal);
}


// 轉換cell的值
Object converterResult = converterVal(e, cellVal);
// 將值放入Pojo中
BeanMapper.setPropertyValue(obj, property, converterResult);
// 放入list中
}
}
BeanMapper.setPropertyValue(obj, "subjectClass", subjectClass);
BeanMapper.setPropertyValue(obj, "infoClass", infoClass);
BeanMapper.setPropertyValue(obj, "infoClassName", infoClassName);
return obj;
}


// 如果是特殊的列,則自定義處理方法
protected boolean isSpeciaRow(String cellVal, Row row, Object obj) {
return false;
}


// 根據cell值來確定範圍
private boolean cellValueRange(Row row) {
Attribute cellValueRanger = rowElement.attribute("cellValueRanger");
if (cellValueRanger == null) {
return true;
}
String cellValueCnRanger = rowElement.attributeValue("cellValueCnRanger");
int cellValueIndexRanger = Integer.parseInt(rowElement.attributeValue("cellValueIndexRanger"));


Cell cell = row.getCell(cellValueIndexRanger);
String cellValue = getMulCellValue(cell);
Set<String> set = new HashSet<String>(Arrays.asList(cellValueCnRanger.split(",")));
if (set.contains(cellValue.trim())) {
return true;
}
return false;
}


// 將一行的資料,轉換成陣列
private Object fillObjectForArray(List<Element> list, Row row) throws Exception {
Object[] objectArray = new Object[list.size()];
int i = 0;
for (Element e : list) {
// cell的序號
int index = Integer.parseInt(e.attributeValue("index"));
// pojo對應屬性名
Cell cell = row.getCell(index);
String cellValue = null;
// 是否合併單元格
boolean isMerge = isMergedRegion(sheet, x, y);
if (isMerge) {
cellValue = getMergedRegionValue(sheet, row.getRowNum(), y);
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue();
}
// 轉換cell的值
Object converterResult = converterVal(e, cellValue);
// 將值放入陣列中
objectArray[i] = converterResult;
i++;
}
return objectArray;
}
}


/**
 * 解析excel的介面
 * 
 */
public abstract class IExcelTemplateReader {
protected int x;
protected int y;
protected Sheet sheet;
protected Set<String> keySet = new HashSet<String>();


// 模板相關物件
protected Element rowElement;


protected ConverterFunctionProvider provider;


/**
* 解析Excel。返回結果 1、List<Pojo> 2、List<Object[]>

* @param sheet
* @param sheetElement
* @return
* @throws Exception
*/
@SuppressWarnings("rawtypes")
public abstract List parseSheet(Sheet sheet, Element sheetElement) throws Exception;


// 將Excel中值,轉換成指定格式
// 轉換分2種,
// 1、簡易轉換,直接呼叫靜態類
// 2、複雜轉換,實現轉換介面
@SuppressWarnings("unchecked")
public Object converterVal(Element e, String cellValue) throws Exception {
Attribute converterAttribute = e.attribute("converter");
// 簡單轉換
if (converterAttribute != null) {
return CallStaticClass.runMenthodByClassMedthod(converterAttribute.getStringValue(), new Object[] { cellValue });
}
// 複雜轉換
Element converterFunctionElement = e.element("converterFunction");
if (converterFunctionElement != null) {
String className = "";
Map<String, String> argMap = new HashMap<String, String>();


List<Element> argList = converterFunctionElement.elements("arg");


for (Element argElement : argList) {
String name = argElement.attributeValue("name");
String text = argElement.getStringValue();
if ("class.name".equalsIgnoreCase(name)) {
className = text;
} else {
argMap.put(name, text);
}
}
if (provider == null)
provider = (ConverterFunctionProvider) SpringUtil.getBean(className);
return provider.execute(argMap, cellValue);
}
// 沒有任何轉換,直接返回
return cellValue;


}


/**  
* 判斷指定的單元格是否是合併單元格  
* @param sheet   
* @param row 行下標  
* @param column 列下標  
* @return  
*/
public boolean isMergedRegion(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress range = sheet.getMergedRegion(i);
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
if (row >= firstRow && row <= lastRow) {
if (column >= firstColumn && column <= lastColumn) {
return true;
}
}
}
return false;
}


/**   
* 獲取合併單元格的值   
* @param sheet   
* @param row   
* @param column   
* @return   
*/
public String getMergedRegionValue(Sheet sheet, int row, int column) {
int sheetMergeCount = sheet.getNumMergedRegions();


for (int i = 0; i < sheetMergeCount; i++) {
CellRangeAddress ca = sheet.getMergedRegion(i);
int firstColumn = ca.getFirstColumn();
int lastColumn = ca.getLastColumn();
int firstRow = ca.getFirstRow();
int lastRow = ca.getLastRow();


if (row >= firstRow && row <= lastRow) {


if (column >= firstColumn && column <= lastColumn) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
return getCellValue(fCell);
}
}
}


return null;
}


/**   
* 獲取單元格的值 ,供外提供呼叫
* @param cell   
* @return   
*/
public String getMulCellValue(Cell cell) {
String cellValue = null;
// 是否合併單元格
boolean isMerge = isMergedRegion(sheet, cell.getRowIndex(), cell.getColumnIndex());
if (isMerge) {
cellValue = getMergedRegionValue(sheet, cell.getRowIndex(), cell.getColumnIndex());
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cellValue = cell.getStringCellValue();
}
return cellValue;
}


/**   
* 獲取單元格的值,不對外提供 
* @param cell   
* @return   
*/
private String getCellValue(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) {
return cell.getCellFormula();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return String.valueOf(cell.getNumericCellValue());
}
return "";
}


public int getX() {
return x;
}


public void setX(int x) {
this.x = x;
}


public int getY() {
return y;
}


public void setY(int y) {
this.y = y;
}


public Sheet getSheet() {
return sheet;
}


public void setSheet(Sheet sheet) {
this.sheet = sheet;
}


public Element getRowElement() {
return rowElement;
}


public void setRowElement(Element rowElement) {
this.rowElement = rowElement;
}


public Set<String> getKeySet() {
return keySet;
}


public void setKeySet(Set<String> keySet) {
this.keySet = keySet;
}
}


BeanMapper.setPropertyValue(obj, "subjectClass", subjectClass);

方法:

public static Object setPropertyValue(Object target, String methodPre, Object val) throws Exception {
Method method2[] = target.getClass().getMethods();
for (int j = 0; j < method2.length; j++) {
String methodName2 = method2[j].getName();
if (methodName2.equalsIgnoreCase("set" + methodPre)) {
method2[j].invoke(target, new Object[] { val });
}
}
return target;
}



EXCEL模型樣式: