/**
* 设置单元格值
* @param wb
* @param cell
* @param sale
*/
public static void setBodyCellValue(HSSFWorkbook wb,HSSFCell cell,String sale){
CellStyle style = cell.getCellStyle();
Pattern p = Pattern.compile("^\\d+$");
Matcher matcher = p.matcher(sale);
Pattern p2 = Pattern.compile("^[-]?\\d+[.]{1}\\d+[%]{1}$");
Matcher matcher2 = p2.matcher(sale);
Pattern p3 = Pattern.compile("^\\d+[\\d|,]+$");//千分位 如355,656
Matcher matcher3 = p3.matcher(sale);
if (matcher.matches()) {// 是数字当作double处理
cell.setCellValue(Double.parseDouble(sale));
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
cell.setCellStyle(style);
}else if (matcher2.matches()) {//百分比
sale = sale.replace("%", "");
Double d = Double.parseDouble(sale)/100;
cell.setCellValue(d);
//设置百分比格式
String formart = "0.";
if(sale.contains(".")){
sale = sale.replace(".", "#");
String numArr[] = sale.split("#");
String ss = "";
if(numArr!=null&&numArr.length==2){
int length = numArr[1].length();
for (int i = 0; i < length; i++) {
ss+="0";
}
}else{
ss="0";
}
formart+=ss;
}else{
formart+="0";
}
formart+="%";
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
style.setDataFormat(wb.createDataFormat().getFormat(formart));
cell.setCellStyle(style);
}else if(matcher3.matches()){
sale = sale.replace(",", "");
Integer salesNum = Integer.valueOf(sale);
cell.setCellValue(salesNum);
style.setDataFormat(wb.createDataFormat().getFormat("#,##0"));
cell.setCellStyle(style);
}
else{//字符串
cell.setCellValue(sale+" ");
}
}
POI单元格数据类型匹配
最新推荐文章于 2020-12-19 14:03:04 发布