java使用POI獲取單元格的值,如果單元格爲合併單元格,則取合併的值 :
java代碼
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
List<CellRangeAddress> rangeList = new ArrayList<>();
int sheetMergeCount = sheet.getNumMergedRegions();
for (int i = 0; i < sheetMergeCount; i++) {
rangeList.add(sheet.getMergedRegion(i));
}
//cellVal = WorkbookUtil.getStringValue(cell, evaluator);
cellVal = getValue(sheet, rownum, cell,evaluator,rangeList);
@Override
public String getValue(Sheet sheet, int row,Cell cell,FormulaEvaluator evaluator,List<CellRangeAddress> rangeList) {
//獲取合併單元格的總數,並循環每一個合併單元格,
int column = cell.getColumnIndex();
for(CellRangeAddress range : rangeList) {
int firstColumn = range.getFirstColumn();
int lastColumn = range.getLastColumn();
int firstRow = range.getFirstRow();
int lastRow = range.getLastRow();
//判斷當前單元格是否在合併單元格區域內,是的話就是合併單元格
if ((row >= firstRow && row <= lastRow) && (column >= firstColumn && column <= lastColumn)) {
Row fRow = sheet.getRow(firstRow);
Cell fCell = fRow.getCell(firstColumn);
//獲取合併單元格首格的值
return WorkbookUtil.getStringValue(fCell, evaluator);
}
}
//非合併單元格個返回空
return WorkbookUtil.getStringValue(cell, evaluator);
}
工具類WorkbookUtil
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
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;
public class WorkbookUtil {
/**
* 取得字符串數據
* @param cell
* @param evaluator
* @return
*/
public static String getStringValue(Cell cell,FormulaEvaluator evaluator){
String listCode="";
if(cell==null) {
return listCode;
}
switch (cell.getCellType()) {
case NUMERIC:// 數字類型
if (org.apache.poi.ss.usermodel.DateUtil.isCellDateFormatted(cell)) {// 處理日期格式、時間格式
SimpleDateFormat sdf = null;
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat
.getBuiltinFormat("h:mm")) {
sdf = new SimpleDateFormat("HH:mm");
} else {// 日期
sdf = new SimpleDateFormat("yyyy-MM-dd");
}
Date date = cell.getDateCellValue();
listCode = sdf.format(date);
} else if (cell.getCellStyle().getDataFormat() == 58) {
// 處理自定義日期格式:m月d日(通過判斷單元格的格式id解決,id的值是58)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
double value = cell.getNumericCellValue();
Date date = org.apache.poi.ss.usermodel.DateUtil
.getJavaDate(value);
listCode = sdf.format(date);
} else {
CellValue cellValue = evaluator.evaluate(cell);
if( cellValue.getCellType()==CellType.NUMERIC) {
listCode = ""+ cellValue.getNumberValue();
}else {
listCode =cellValue.getStringValue();
}
Double value = cell.getNumericCellValue();
CellStyle style = cell.getCellStyle();
DecimalFormat format = new DecimalFormat();
String temp = style.getDataFormatString();
// 單元格設置成常規
if (temp.equals("General")) {
format.applyPattern("#.000000000");
}else{
format.applyPattern("0.0000000#");//推薦
}
listCode = Double.valueOf(format.format(value)).doubleValue()+"";
if(listCode.indexOf("E") != -1) {
BigDecimal num = new BigDecimal(listCode);
if(num != null){
if(num.compareTo(BigDecimal.ZERO)==0){
listCode = "0";
}else{
listCode = num.stripTrailingZeros().toPlainString();
}
}
}else {
}
if(listCode.contains(",")) {
listCode = listCode.replaceAll(",", "");
}
listCode = WorkbookUtil.replaceBlank(listCode);
if(listCode.contains(".")) {
String[] xxx = listCode.split("\\.");
if(xxx[0].equals("")) {
listCode = "0"+listCode;
}
String xx = xxx[1] ;
try {
if(Integer.parseInt(xx) == 0) {
listCode = xxx[0];
if(listCode.trim().equals("")) {
listCode = "0";
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
break;
case STRING:// String類型
listCode = cell.getRichStringCellValue().toString();
break;
case BLANK: //本就是空
listCode = "";
case FORMULA: //帶函數的數據
default:
try {
listCode="";
CellValue cellValue = evaluator.evaluate(cell);
if(cellValue == null) {
listCode = cell.getRichStringCellValue().toString();
} else {
if( cellValue.getCellType()==CellType.NUMERIC) {
listCode = ""+ new BigDecimal(cell.getNumericCellValue());//防止科學計數法
}else {
listCode =cellValue.getStringValue();
}
}
}
catch(Exception e) {
try {
listCode= ""+ cell.getStringCellValue();
} catch (Exception e2) {
listCode = "";
}
}
break;
}
return listCode==null?"":listCode.trim();
}
/**
* 取得Double數據
* @param cell
* @param evaluator
* @return
*/
public static Double getDoubleValue(Cell cell,FormulaEvaluator evaluator){
Double big = new Double(0.0);
String valueString = getStringValue(cell, evaluator);
valueString = WorkbookUtil.replaceBlank(valueString);
if(valueString!=null &&
!"".equals(valueString.trim()) &&WorkbookUtil.isNum(valueString)) {
big = Double.parseDouble(valueString);
}
return big;
}
/**
* 取得BigDecimal數據
* @param cell
* @param evaluator
* @return
*/
public static BigDecimal getBigDecimalValue(Cell cell,FormulaEvaluator evaluator){
return new BigDecimal(getDoubleValue(cell, evaluator));
}
/**
* 取得Long數據
* @param cell
* @param evaluator
* @return
*/
public static Long getLongValue(Cell cell,FormulaEvaluator evaluator){
Long big = new Long(0);
String valueString = getStringValue(cell, evaluator);
valueString = WorkbookUtil.replaceBlank(valueString);
if(valueString!=null &&
!"".equals(valueString.trim()) &&WorkbookUtil.isNum(valueString)) {
big = Long.parseLong(valueString);
}
return big;
}
/**
* 取得Integer數據
* @param cell
* @param evaluator
* @return
*/
public static Integer getIntegerValue(Cell cell,FormulaEvaluator evaluator){
Integer big = new Integer(0);
String valueString = getStringValue(cell, evaluator);
valueString = WorkbookUtil.replaceBlank(valueString);
if(valueString!=null &&
!"".equals(valueString.trim()) &&WorkbookUtil.isNum(valueString)) {
big = Integer.parseInt(valueString);
}
return big;
}
/**
* 用於判斷row是否有數據
* @param row
* @param evaluator
* @return
*/
public static Boolean isNull(Row row,FormulaEvaluator evaluator,Integer totalCell){
Boolean isDingE= true;
if(totalCell ==null) {
totalCell=(int) row.getLastCellNum();
}
for(int i = 0; i<totalCell; i++) {
Cell cell=row.getCell(i);
if (cell!=null) {
String listCode=getStringValue( cell, evaluator);
if(listCode!=null&&!listCode.trim().equals("")) {
isDingE=false;
}
}
}
return isDingE;
}
/**
* 查找單元格是否有指定的內容
* @param row
* @param evaluator
* @return
*/
public static Boolean findText(Row row,FormulaEvaluator evaluator,Integer totalCell,String text){
if(row == null) {
return false;
}
if(totalCell ==null) {
totalCell=(int) row.getLastCellNum();
}
for(int i = 0; i<totalCell; i++) {
Cell cell=row.getCell(i);
if (cell!=null) {
String listCode=getStringValue( cell, evaluator);
if(listCode!=null && listCode.trim().equals(text)) {
return true;
}
}
}
return false;
}
/**
* 測試表格的指定行數據的所有單元格是否等於指定文字,以指定文字開頭,或者包含指定文字
* @param row
* @param evaluator
* @param totalCell
* @param text
* @param isStartWith
* @return
*/
public static Boolean findStartWithText(Row row,FormulaEvaluator evaluator,Integer totalCell,String text,Boolean isStartWith){
if(totalCell ==null) {
totalCell=(int) row.getLastCellNum();
}
for(int i = 0; i<totalCell ; i++) {
Cell cell=row.getCell(i);
if (cell!=null) {
String listCode=getStringValue( cell, evaluator);
if(isStartWith == null){
//爲null表示等於指定內容
if(listCode!=null && listCode.trim().equals(text)) {
return true;
}
}else if(isStartWith){
//爲true,表示以特定文字開頭
if(listCode!=null && listCode.trim().startsWith(text)) {
return true;
}
}else{
//否則只要包含有特定文字即可
if(listCode!=null && listCode.trim().contains(text)) {
return true;
}
}
}
}
return false;
}
/**
* 用於判斷數據是否是數字或者字母組成
* @param listCode
* @return
*/
public static Boolean isCharOrNum(String listCode){
if(listCode==null) {
return false;
}
Pattern p=Pattern.compile("^[0-9.a-z-]+$");
Matcher m=p.matcher(listCode);
return m.matches();
}
/**
* 用於判斷數據是否是數字或者字母組成
* @param listCode
* @return
*/
public static Boolean isNum(String listCode){
if(listCode==null) {
return false;
}
Pattern p=Pattern.compile("^[0-9,.]+$");
Matcher m=p.matcher(listCode);
return m.matches();
}
/**
* 用於取得把中文數字轉化爲阿拉伯數字的map
* @return
*/
public static Map<String, String> getNumMap(){
Map<String, String> map = new HashMap<String, String>();
map.put("零", "0");
map.put("一", "1");
map.put("二", "2");
map.put("三", "3");
map.put("四", "4");
map.put("五", "5");
map.put("六", "6");
map.put("七", "7");
map.put("八", "8");
map.put("九", "9");
return map;
}
/**
* 字符串匹配
* 方式一:基本正則表達式實現
* @param str
* @param reg
* @return
*/
public static boolean matchMatcher(String str,String reg){
Pattern pattern =Pattern.compile(reg);
Matcher matcher=pattern.matcher(str);
return matcher.matches();
}
/**
* 字符串匹配
* 方式二:利用Pattern自帶實現
* @param str
* @param reg
* @return
*/
public static boolean matchPattern(String str,String reg){
return Pattern.matches(reg, str);
}
/**
* 字符串匹配
* 方式三:String自帶實現
* @param str
* @param reg
* @return
*/
public static boolean matchStr(String str,String reg){
return str.matches(reg);
}
/**
* 去空格(注意,中間有空字符也會去掉)
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = "";
if (str!=null) {
Pattern p = Pattern.compile(" | |\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 去所有空字符後,判斷是否爲“”字符串
* 注意,中間有空字符也會去掉
* @param str
* @return
*/
public static Boolean isBlankString(String str) {
if(str ==null) {
return true;
}
return "".equals(WorkbookUtil.replaceBlank( str));
}
/**
* 基本創建execel單元格的方法
* @param sheet
* @param rownum 行數
* @param colnum 列數
* @param cellType
* @param cellvalue
* @param cellStyle
* @param firstRow 合併開始行數
* @param lastRow 合併結束行數
* @param firstCol 合併開始列數
* @param lastCol 合併結束列數
*/
public static void createCell(Sheet sheet,int rownum,int colnum,CellType cellType,
Object cellvalue,CellStyle cellStyle,
int firstRow, int lastRow, int firstCol, int lastCol) {
if(sheet == null ) {
return;
}
Row row ;
if(sheet.getRow(rownum) !=null) {
row = sheet.getRow(rownum);
}else {
row = sheet.createRow(rownum);
}
Cell cell = row.createCell(colnum, cellType);
if(cellvalue ==null) {
cell.setCellValue("");
}else {
if(cellvalue instanceof BigDecimal) {
BigDecimal bd = ((BigDecimal)cellvalue);
if(bd.compareTo(BigDecimal.ZERO) == 0) {
cell.setCellValue(0);
}else {
cell.setCellValue(bd.setScale(3, BigDecimal.ROUND_HALF_UP).doubleValue());
}
}else {
cell.setCellValue(cellvalue.toString());
}
}
if(cellStyle != null) {
cell.setCellStyle(cellStyle);
}
if(firstRow >=0 && lastRow>=0 &&firstCol>=0&&lastCol>=0) {
CellRangeAddress region = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
sheet.addMergedRegion(region);
for (int i = firstRow; i <= lastRow; i++) {
Row row2 = sheet.getRow(i)==null? sheet.createRow(i):sheet.getRow(i);
for (int j = firstCol; j <= lastCol; j++) {
Cell cell2 = row2.getCell(j)==null? row2.createCell(j):row2.getCell(j);
cell2.setCellStyle(cellStyle);
}
}
//setRegionStyle(sheet,region,cellStyle);
}
}
/**
* 合併第colnum列的firstRow--lastRow行
* @param sheet
* @param colnum
* @param cellType
* @param cellvalue
* @param cellStyle
* @param firstRow
* @param lastRow
*/
public static void createCellAddRow(Sheet sheet,int colnum,CellType cellType,
Object cellvalue,CellStyle cellStyle, int firstRow, int lastRow) {
createCell(sheet, firstRow, colnum, cellType, cellvalue, cellStyle, firstRow, lastRow, colnum, colnum);
}
/**
* 合併第rownum行的firstCol--lastCol列
* @param sheet
* @param rownum
* @param cellType
* @param cellvalue
* @param cellStyle
* @param firstCol
* @param lastCol
*/
public static void createCellAddCol(Sheet sheet,int rownum,CellType cellType,
Object cellvalue,CellStyle cellStyle,
int firstCol, int lastCol) {
createCell(sheet, rownum, firstCol, cellType, cellvalue, cellStyle, rownum, rownum, firstCol, lastCol);
}
/**
* 創建簡單的字符串類型的execel單元格
* @param sheet
* @param rownum
* @param colnum
* @param cellvalue
*/
public static void createStringCell(Sheet sheet,int rownum,int colnum,
Object cellvalue) {
createCell(sheet, rownum, colnum, CellType.STRING, cellvalue, null, -1, rownum, colnum, colnum);
}
/**
* 創建簡單的數字類型的execel單元格
* @param sheet
* @param rownum
* @param colnum
* @param cellvalue
*/
public static void createNumCell(Sheet sheet,int rownum,int colnum,
Object cellvalue) {
createCell(sheet, rownum, colnum, CellType.NUMERIC, cellvalue, null, -1, rownum, colnum, colnum);
}
/**
* 創建簡單的字符串類型的execel單元格
* @param sheet
* @param rownum
* @param colnum
* @param cellvalue
*/
public static void createStringCell(Sheet sheet,int rownum,int colnum,
Object cellvalue,CellStyle cellStyle) {
createCell(sheet, rownum, colnum, CellType.STRING, cellvalue, cellStyle, -1, rownum, colnum, colnum);
}
/**
* 創建簡單的數字類型的execel單元格
* @param sheet
* @param rownum
* @param colnum
* @param cellvalue
*/
public static void createNumCell(Sheet sheet,int rownum,int colnum,
Object cellvalue,CellStyle cellStyle) {
createCell(sheet, rownum, colnum, CellType.NUMERIC, cellvalue, cellStyle, -1, rownum, colnum, colnum);
}
/**
* excel 列下標 A-B-.... 轉化爲 0-1-....
* @param name
* @return
*/
public static int nameToColumn(String name) {
int column = -1;
for (int i = 0; i < name.length(); ++i) {
int c = name.charAt(i);
column = (column + 1) * 26 + c - 'A';
}
return column;
}
/**
* excel 列下標0-1-.... 轉化爲 A-B-....
* @param i
* @return
*/
public static String getColumnNum(int i) {
String strResult = "";
int intRound = i / 26;
int intMod = i % 26;
if (intRound != 0) {
strResult = String.valueOf(((char) (intRound + 64)));
}
strResult += String.valueOf(((char) (intMod + 64)));
return strResult;
}
/**
* 對list中的對象,按fieldName字段排序,fieldName裏面的數據是1-1-1類似的數據
* @param list
* @param fieldName 此字段必須是String 類型的1-1-1之類的數據
* @throws Exception
*/
public static boolean sortList(List<?> list,final String fieldName) {
if(list == null) {
return false ;
}
Collections.sort(list,new Comparator<Object>(){
@Override
public int compare(Object o1, Object o2) {
try {
if(o1 ==null) {
return 1;
}else if(o2 ==null) {
return -1;
}
java.lang.reflect.Method m=null;
Class<?> clazz=o1.getClass();
m = clazz.getMethod("get"+new StringBuffer().append(Character.toUpperCase(fieldName.charAt(0))).append(fieldName.substring(1)).toString());
String code1=(String)m.invoke(o1);
String code2=(String)m.invoke(o2);
if(code1 ==null) {
return 1;
}else if(code2 == null) {
return -1;
}else if(code1.equals(code2)) {
return 0;
}
if(code1.split("-").length == code2.split("-").length) {
String[] codeList1 = code1.split("-");
String[] codeList2 = code2.split("-");
for (int i=0;i<codeList1.length;i++) {
if(!WorkbookUtil.isNum(codeList1[i]) && WorkbookUtil.isNum(codeList2[i])) {
return 1;
}else if(WorkbookUtil.isNum(codeList1[i]) && !WorkbookUtil.isNum(codeList2[i])) {
return -1;
}else if(!WorkbookUtil.isNum(codeList1[i]) && !WorkbookUtil.isNum(codeList2[i])) {
return codeList1[i].compareTo(codeList2[i]);
}else {
Integer c1 = Integer.parseInt(codeList1[i]);
Integer c2 = Integer.parseInt(codeList2[i]);
if(c1 != c2) {
return c1-c2;
}else {
continue;
}
}
}
return 0;
}else if(code1.split("-").length > code2.split("-").length) {
return 1;//code1 放 code2 後面
}else{
return -1;
}
} catch (Exception e) {
return 1;
}
}
});
return true ;
}
/**
* 對list中的對象,按fieldName字段排序,fieldName裏面的數據是字符串(大部分是int,也可能包含字母)
* @param list
* @param fieldName
* @throws Exception
*/
public static boolean sortListByIntString(List<?> list,final String fieldName) {
if(list == null) {
return false ;
}
Collections.sort(list,new Comparator<Object>(){
@Override
public int compare(Object obj1, Object obj2) {
try {
java.lang.reflect.Method m=null;
Class<?> clazz=obj1.getClass();
m = clazz.getMethod("get"+new StringBuffer().append(Character.toUpperCase(fieldName.charAt(0))).append(fieldName.substring(1)).toString());
String o1=(String)m.invoke(obj1);
String o2=(String)m.invoke(obj2);
if(o1 == null) {
return 1;
}
if(o2 == null) {
return -1;
}
if(o1.equals(o2)) {
return 0;
}
try {
int i = Integer.parseInt(o1) - Integer.parseInt(o2);
return i;
} catch (NumberFormatException e) {
return o1.compareTo(o2);
}
} catch (Exception e) {
return 1;
}
}
});
return true ;
}
/**
* 合併單元格處理,獲取合併行
*
* @param sheet
* @return List<CellRangeAddress>
*/
public static List<CellRangeAddress> getCombineCell(Sheet sheet) {
List<CellRangeAddress> list = new ArrayList<CellRangeAddress>();
// 獲得一個 sheet 中合併單元格的數量
int sheetmergerCount = sheet.getNumMergedRegions();
// 遍歷合併單元格
for (int i = 0; i < sheetmergerCount; i++) {
// 獲得合併單元格加入list中
CellRangeAddress ca = sheet.getMergedRegion(i);
list.add(ca);
}
return list;
}
/**
* 判斷單元格是否爲合併單元格,是的話則將單元格的值返回
*
* @param listCombineCell
* 存放合併單元格的list
* @param cell
* 需要判斷的單元格
* @param sheet
* sheet
* @return
*/
public static CellRangeAddress isCombineCell(List<CellRangeAddress> listCombineCell,
Cell cell, Sheet sheet) throws Exception {
if(cell ==null) {
return null;
}
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for (CellRangeAddress ca : listCombineCell) {
// 獲得合併單元格的起始行, 結束行, 起始列, 結束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
if (cell.getColumnIndex() >= firstC
&& cell.getColumnIndex() <= lastC) {
return ca;
}
}
}
return null;
}
/**
*獲取合併單元格的列數
*
* @param listCombineCell
* 存放合併單元格的list
* @param cell
* 需要獲取值的的單元格
* @param sheet
* sheet
* @return
*/
public static int getMergeCol(List<CellRangeAddress> listCombineCell,
Cell cell, Sheet sheet) throws Exception {
int firstC = 0;
int lastC = 0;
int firstR = 0;
int lastR = 0;
for (CellRangeAddress ca : listCombineCell) {
// 獲得合併單元格的起始行, 結束行, 起始列, 結束列
firstC = ca.getFirstColumn();
lastC = ca.getLastColumn();
firstR = ca.getFirstRow();
lastR = ca.getLastRow();
if (cell.getRowIndex() >= firstR && cell.getRowIndex() <= lastR) {
if (cell.getColumnIndex() >= firstC
&& cell.getColumnIndex() <= lastC) {
return lastC-firstC;
}
}
}
return 0;
}
public static InputStream toInputStream(Workbook wb) {
try {
ByteArrayOutputStream outputStream=new ByteArrayOutputStream(4096);
wb.write(outputStream);
outputStream.flush();
outputStream.close();
wb.close();
byte[] buf=outputStream.toByteArray();
return new BufferedInputStream(new ByteArrayInputStream(buf));
} catch (IOException e) {
}
return null;
}
}