对象转换工具类
map与javabean
map与实体
map与String
package ;
import ;
import ;
import ;
import ;
import .*;
/**
* 转变工具类
*/
public class ConvertUtil {
/**
* 将对象转换为map
* @param bean
* @return
*/
public static <T> Map<String, Object> beanToMap(T bean ) {
Map<String, Object> map = ();
if (bean != null) {
BeanMap beanMap = (bean);
for (Object key : ()) {
((), (key));
}
}
return map;
}
public static <T> Map<String, Object> beanToMap(T bean ,List<String> whiteList) {
Map<String, Object> map = ();
if (bean != null) {
BeanMap beanMap = (bean);
for (Object key : ()) {
if( (())){
((), (key));
}
}
}
return map;
}
/**
* 将map转换为javabean对象
*
* @param map
* @param bean
* @return
*/
public static <T> T mapToBean(Map<String, Object> map, T bean) {
BeanMap beanMap = (bean);
(map);
return bean;
}
/**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = ();
Field[] fields = ();
try {
for (Field field : fields) {
(true);
((), (obj));
}
} catch (Exception e) {
();
}
return map;
}
/**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
public static Map<String, String> object2MapST(Object obj) {
Map<String, String> map = new HashMap<>();
if (obj == null) {
return map;
}
Class clazz = ();
Field[] fields = ();
Object o =null;
try {
for (Field field : fields) {
(true);
o=(obj);
((), o!=null?((obj)):null);
}
} catch (Exception e) {
();
}
return map;
}
/**
* Map转成实体对象
*
* @param map 实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
if (map == null) {
return null;
}
Object obj = null;
try {
obj = ();
Field[] fields = ().getDeclaredFields();
for (Field field : fields) {
int mod = ();
if ((mod) || (mod)) {
continue;
}
(true);
(obj, (()));
}
} catch (Exception e) {
();
}
return obj;
}
/**
*
* Map转String
* @param map
* @return
*/
public static String getMapToString(Map<String,Object> map) {
Set<String> keySet = ();
//将set集合转换为数组
String[] keyArray = (new String[()]);
//给数组排序(升序)
(keyArray);
//因为String拼接效率会很低的,所以转用StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ; i++) {
// 参数值为空,则不参与签名 这个方法trim()是去空格
if ((((keyArray[i]))).trim().length() > 0) {
(keyArray[i]).append(":").append(((keyArray[i])).trim());
}
if (i != - 1) {
(",");
}
}
return ();
}
/**
*
* String转map
* @param str
* @return
*/
public static Map<String,Object> getStringToMap(String str){
//根据逗号截取字符串数组
String[] str1 = (",");
//创建Map对象
Map<String,Object> map = new HashMap<>();
//循环加入map集合
for (int i = 0; i < ; i++) {
//根据":"截取字符串数组
String[] str2 = str1[i].split(":");
//str2[0]为KEY,str2[1]为值
(str2[0],str2[1]);
}
return map;
}
}
StrUtils
package ;
public class StrUtils {
/**
*
* @param str
* @return
*/
public static boolean isBlank(String str) {
return (str == null || ().length() == 0);
}
/**
* 参数加引号处理
* @param str
* @return
*/
public static String addQuotesToParameter(String str) {
if (!StrUtils .isBlank(str)) {
String[] idsArr = (",");
if ( > 0) {
StringBuffer idBuffer = new StringBuffer();
for (int i = 0; i < ; i++) {
("'" + idsArr[i] + "',");
}
str = ().substring(0, ().length() - 1);
}
}
return str;
}
/**
* 去替换横杠
*
* @param str
* @return
*/
public static String getReplaseStr(String str) {
String t_str = null;
if (str != null) {
t_str = ("-", "");
}
return t_str;
}
}
Excel工具类
package ;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
public class ExcelExportUtils {
/**
* 使用Excel模板创建Workbook
* @param request
* @param path
* @return
*/
public static Workbook createWorkbook(HttpServletRequest request, String path){
String realPath = ().getServletContext().getRealPath("/");
File file = new File(realPath + path);
FileInputStream fis = null;
Workbook book = null;
try {
fis = new FileInputStream(file);
String suffix =((".") + 1);
if("xlsx".equalsIgnoreCase(suffix)){
book = new XSSFWorkbook(fis);
}else if("xls".equalsIgnoreCase(suffix)){
book = (fis);
}
return book;
} catch (FileNotFoundException e) {
throw new RuntimeException("文件不存在!");
} catch (IOException e) {
throw new RuntimeException("Workbook文件创建出错!");
} catch (Exception e){
();
}finally{
if(fis != null){
try {
();
} catch (IOException e) {
throw new RuntimeException("文件流关闭出错!");
}
}
}
return book;
}
/**
* 创建行或者获取行
* @param sheet
* @param index
* @return
*/
public static Row createOrGetRow(Sheet sheet, int index){
Row row = null;
row = (index);
if(row != null){
return row;
}
row = (index);
return row;
}
/**
* 创建单元格或者获取单元格
* @param row
* @param index
* @return
*/
public static Cell createOrGetCell(Row row, int index){
Cell cell = null;
cell = (index);
if(cell != null){
return cell;
}
cell = (index);
return cell;
}
/**
* 设置单元格值
* @param value
* @param cell
* @param style
*/
public static void setCellValue(String value, Cell cell, CellStyle style)
{
String reg = "^-?\\d+\\.?\\d*$";
if((value) || value == null){
("");
}else{
if(!"-".equals(value) && (reg)){
((value)); //设置数字
}else{
(value);
}
}
if(style != null){
(style);
}
}
/**
* 导出Excel
* @param response
* @param book
* @param fileName
*/
public static void exportExcel(HttpServletResponse response, Workbook book, String fileName, String suffix){
String excelName = "";
ServletOutputStream out = null;
try {
excelName = (fileName, "UTF-8");
("application/-excel;charset=utf-8");
if("xlsx".equalsIgnoreCase(suffix)){
("Content-Disposition", "attachment;filename=" + excelName + ".xlsx" );
}else if("xls".equalsIgnoreCase(suffix)){
("Content-Disposition", "attachment;filename=" + excelName + ".xls" );
}
out = ();
(out);
();
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("不支持的编码错误!");
} catch (IOException e) {
throw new RuntimeException("获取输出流或输出文件时出错!");
} finally{
try {
if(out != null){
();
}
} catch (IOException e) {
throw new RuntimeException("关闭输出流时出错!");
}
}
}
/**
* 下载指定路径的文件
* @param response
* @param realPath
* @param excelName
*/
public static void downloadTemplet(HttpServletResponse response,
String realPath, String excelName) {
FileInputStream fis = null;
ServletOutputStream out = null;
try {
excelName = (excelName, "UTF-8");
fis = new FileInputStream(new File(realPath));
("application/-excel;charset=utf-8");
("Content-Disposition", "attachment;filename=" + excelName + ".xlsx");
out = ();
byte[] buffer = new byte[1024];
int len = 0;
while((len = (buffer)) != -1){
(buffer, 0, len);
}
} catch (FileNotFoundException e) {
();
throw new RuntimeException("文件找不到!");
} catch (UnsupportedEncodingException e) {
();
throw new RuntimeException("不支持的编码错误!");
} catch (IOException e) {
();
throw new RuntimeException("创建输出流或输出文件时出错!");
}finally {
if(out != null){
try {
();
();
} catch (IOException e) {
();
throw new RuntimeException("关闭输出流时出错!");
}
}
if(fis != null){
try {
();
} catch (IOException e) {
();
throw new RuntimeException("关闭输入流时出错!");
}
}
}
}
/**
* 根据绝对路径创建Workbook
* @param request
* @param filePath
* @return
*/
public static Workbook createWorkbookByRealPath(HttpServletRequest request,
String filePath) {
File file = new File(filePath);
FileInputStream fis = null;
Workbook book = null;
try {
fis = new FileInputStream(file);
book = new XSSFWorkbook(fis);
return book;
} catch (FileNotFoundException e) {
throw new RuntimeException("文件不存在!");
} catch (IOException e) {
throw new RuntimeException("Workbook文件创建出错!");
}finally{
if(fis != null){
try {
();
} catch (IOException e) {
throw new RuntimeException("文件流关闭出错!");
}
}
}
}
public static String getCellValue(Workbook book, Cell cell) {
FormulaEvaluator evaluator = ().createFormulaEvaluator();
if(cell == null || "".equals(().trim())){
return null;
}
String cellValue = "";
int cellType = ();
if(cellType == Cell.CELL_TYPE_FORMULA){ //表达式类型
cellType = (cell).getCellType();
}
switch (cellType) {
case Cell.CELL_TYPE_STRING: //字符串类型
cellValue = (().trim()) ? "" : ().trim();
break;
case Cell.CELL_TYPE_BOOLEAN: //布尔类型
cellValue = (());
break;
case Cell.CELL_TYPE_NUMERIC: //数值类型
if ((cell)) { //判断日期类型
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
cellValue = (());
} else { //否
cellValue = new DecimalFormat("#.######").format(());
}
break;
default: //其它类型,取空串吧
cellValue = null;
break;
}
return cellValue;
}
/**
* 将文件导出到本地
* @param path
* @param book
*/
public static void exportExcel(String path, Workbook book){
File file = new File(path);
if(!()){
().mkdir();
try {
();
} catch (IOException e) {
();
}
}
OutputStream os = null;
try {
os = new FileOutputStream(file);
(os);
();
} catch (FileNotFoundException e) {
();
} catch (IOException e) {
();
} finally{
if(os != null){
try {
();
} catch (IOException e) {
();
}
}
}
}
}
PoiUtils
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .;
import ;
import ;
public class PoiUtils {
public static Row getRow(Sheet sheet , int rowNum){
Row row = (rowNum);
if( row == null){
row = (rowNum);
}
return row;
}
public static Cell getCell(Row row , int cellNum){
Cell cell = (cellNum);
if(cell == null ){
cell = (cellNum);
}
return cell;
}
public static Cell getCell(Sheet sheet,int row ,int cellNum){
return ((sheet,row) , cellNum);
}
public static void setRegionStyle(Sheet sheet , CellRangeAddress address, CellStyle style){
if(address == null) return;
Row row;
Cell cell;
for (int i = (); i < (); i++) {
row = (sheet,i);
for (int j = (); j < (); j++) {
cell = ( row ,j);
(style);
}
}
}
public static void main(String[] args) {
HashMap<Object, Object> t1 = ();
("ymId",201901);
HashMap<Object, Object> t2 = ();
("ymId",201901);
HashMap<Object, Object> context = ();
("t1",t1);
("t2",t2);
("{\"a\":1}");
((" == ",context));
}
public static void setCell(Row row, int cellNum, Double value) {
if (value != null) {
getCell(row, cellNum).setCellValue(value);
}
}
public static void setCell(Row row, int cellNum, String value) {
if (value != null) {
getCell(row, cellNum).setCellValue(value);
}
}
public static void setCell(Row row, int cellNum, String value, CellStyle cellStyle) {
if (value != null) {
Cell cell = getCell(row, cellNum);
(cellStyle);
(value);
}
}
public static void setCell(Row row, int cellNum, Double value, CellStyle cellStyle) {
Cell cell = getCell(row, cellNum);
(cellStyle);
setCell(cell, value);
}
public static void setCell(Cell cell, Double value) {
if (value == null) {
("-");
} else {
(value);
}
}
/**
* @param sheet 模板sheet页(需要设置下拉框的sheet)
* @param textlist 下拉框显示的内容
* @param firstRow 添加下拉框对应开始行
* @param endRow 添加下拉框对应结束行
* @param firstCol 添加下拉框对应开始列
* @param endCol 添加下拉框对应结束列
*/
public static void setHSSFValidation(XSSFSheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol){
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, endRow, firstCol, endCol);
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) (textlist);
XSSFDataValidation validation = (XSSFDataValidation) (
dvConstraint, addressList);
// 07默认setSuppressDropDownArrow(true);
// (true);
// (true);
(validation);
}
}
FormatterUtil
package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
/**
* 格式转换工具类
*/
public class FormatterUtil {
/**
* 四舍五入,保留num个小数位数
*
* @param val double 需要转换的值
* @param num int 保留几位小数
* @return Double
*/
public static Double keepScale2Double(double val, int num) {
int pow = (int) (10, num);
return (double) (val * pow) / pow;
}
/**
* 四舍五入,保留num个小数点后的数字
*
* @param val double 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String getNum(double val, int num) {
String str = "";
str = new BigDecimal(val).setScale(num, BigDecimal.ROUND_HALF_UP) + "";
return str;
}
/**
* 四舍五入,保留num个小数点后的数字
*
* @param val String 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String getNum(String val, int num) {
if(isEmpty(val) || "-".equals(val)) {
return "-";
}
if("0.0".equals(val) || "0".equals(val)) {
return val;
}
String str = "";
str = new BigDecimal((val)).setScale(num, BigDecimal.ROUND_HALF_UP) + "";
return str;
}
/**
* 转成千分位显示
*
* @param val double 需要转换的值
* @return String
*/
public static String formatTosepara(double val) {
DecimalFormat df = new DecimalFormat("#,###");
return (val);
}
/**
* 转成千分位显示
* @param val String 需要转换的值
* @return String
*/
public static String formatTosepara(String val) {
if(val == null || ("-")){
return "-";
}
DecimalFormat df = new DecimalFormat("#,###");
return ((val));
}
/**
* 判断是不是数字 (正整数)
* @param val String
* @return boolean
*/
public static boolean isNumeric(String val){
Pattern pattern = ("[0-9]*");
Matcher isNum = (val);
if( !() ){
return false;
}
return true;
}
/**
* 由"4367700",转为"4,368" 或 "437" (化为以千或为万为单位)
* @param val String 需要转换的值
* @param unit String 单位标识 thousand:千 || 万
* @return String
*/
public static String addThousandUnit(String val, String unit){
Pattern pattern = ("^\\-(\\d*\\.+\\d+)?(\\d*)?$");
if(val == null){
return val;
}
Matcher isNum = (val);
if(!()){
return val;
}
double num = 10000;
if(unit != null && "thousand".equals(unit)){
num = 1000;
}
String result = ("%.1f", ((val) / num));
NumberFormat nf = ();
(true);
return ((result));
}
/**
* 把Double转成百分比值
*
* @param val Double 需要转换的值
* @param num int 保留几位小数
* @return String
*/
public static String percentOfDouble(Double val, int num) {
if (val == null) {
return "";
}
BigDecimal b = new BigDecimal((val * 100)).setScale(num, BigDecimal.ROUND_HALF_UP);
String persentStr = b + "%";
return persentStr;
}
/**
* 转换保留一位小数
*
* @param val double
* @return double
*/
public static double getOneDecimal(double val) {
DecimalFormat dFormat = new DecimalFormat("#.0");
String yearString = (val);
Double temp = (yearString);
return temp;
}
/**
* 转换保留两位小数
*
* @param val double
* @return double
*/
public static String getTwoDecimal(double val) {
DecimalFormat dFormat = new DecimalFormat("0.00");
String str = (val);
return str;
}
/**
* 字符串空判断
*
* @param val String
* @return boolean
*/
public static boolean isEmpty(String val)
{
boolean flag = true;
if(null != val && 0 != ().length()) {
flag = false;
}
return flag;
}
/**
* 添加符号 +
*
* @param val String
* @return String
*/
public static String addSign(String val)
{
if(!isEmpty(val) && !("-"))
{
val = "+" + val;
}
return val;
}
/**
* 判断是否为整数(不带+号那种)
*
* @param obj Object
* @return boolean
*/
public static boolean isPositiveInteger(Object obj) {
boolean flag = false;
try {
if(obj != null){
String source = ();
Pattern pattern = ("^{0,1}[1-9]\\d*");
if((source).matches()){
flag = true;
}
}
} catch (Exception e) {
();
}
return flag;
}
/**
* 判断是否为小数(不带+号那种)
*
* @param obj Object
* @return boolean
*/
public static boolean isPositiveDecimal(Object obj){
boolean flag = false;
try {
if(obj != null){
String source = ();
Pattern pattern = ("{0,1}[0]\\.[1-9]*|{0,1}[1-9]\\d*\\.\\d*");
if((source).matches()){
flag = true;
}
}
} catch (Exception e) {
();
}
return flag;
}
/**
* 判断是否是整数或者是携带一位或者两位的小数
*
* @param obj Object
* @return boolean
*/
public static boolean judgeTwoDecimal(Object obj){
boolean flag = false;
try {
if(obj != null){
String source = ();
Pattern pattern = ("^\\d+(\\.\\d{1,2})?$");
if((source).matches()){
flag = true;
}
}
} catch (Exception e) {
();
}
return flag;
}
/**
* 判断当前月份是第几季度
*
* @param month int
* @return int
*/
public static int getQuarterNumbers(int month){
int nums = 0;
if(month <= 3){
nums = 1;
}else if(month > 3 && month <= 6){
nums = 2;
}else if(month > 6 && month <= 9){
nums = 3;
}else if(month > 9 && month <= 12){
nums = 4;
}
return nums;
}
/**
* 获取相应的国际化季度名称
* @return Map<String,String>
*/
public static Map<String, String> getQuarterKeysMap(){
Map<String, String> keyMap = new HashMap<String, String>();
("1", "common.Q1");
("2", "common.Q2");
("3", "common.Q3");
("4", "common.Q4");
return keyMap;
}
/**
* 处理导出的excel文件中的空格变成+号的问题
*
* @param excelName String
* @return String
*/
public static String encodeExcelName(String excelName){
try {
excelName = (excelName, "utf-8");
excelName = ("+", "%20");
} catch (final IOException e) {
();
} finally {}
return excelName;
}
/**
* 获取外网IP
*
* @param request HttpServletRequest
* @return String
*/
public static String getRemoteHost(HttpServletRequest request){
String ip = ("x-forwarded-for");
if(ip == null || () == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = ("Proxy-Client-IP");
}
if(ip == null || () == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = ("WL-Proxy-Client-IP");
}
if(ip == null || () == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = ();
}
return ("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
}
/**
* 参数增加引号
*
* @param val String
* @return String
*/
public static String addQuotesToParameter(String val) {
if (!isEmpty(val)) {
String[] arr = (",");
if ( > 0) {
StringBuffer idBuffer = new StringBuffer();
for (int i = 0; i < ; i++) {
("'" + arr[i] + "',");
}
val = ().substring(0, ().length() - 1);
}
}
return val;
}
/*
* 数字转汉字数字
*/
public static String numberToChinese(long number) {
final String[] chineseNum = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
final String[] unit = {"", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千"};
final String[] unit_type = {"", "万", "亿"};
// 转数组
char[] numberArray = (number + "").toCharArray();
// 拼接成字符串
StringBuilder dst = new StringBuilder("");
// 循环 上次数字是否是 0
boolean zero = false;
// 单位级别
int type = / 4;
if ( % 4 == 0) {
// 刚好是级别切换
type--;
}
for (int i = 0; i < ; i++) {
int num = (int) numberArray[i] - 48;
// 判断是否到了级别切换
if (i > 0 && ( - i) % 4 == 0) {
//级别切换时,上次为 0,补齐单位名称
if (zero) {
(unit_type[type]);
}
type--;
}
// 数字为0跳过
if (num == 0) {
zero = true;
continue;
}
// 上次为0 且不是级别切换时,添加一个零,
if (zero) {
(chineseNum[0]);
}
// 数字
(chineseNum[num]);
// 单位
if (i < - 1) {
(unit[ - i - 1]);
}
// 上次数字,设置为非 0
zero = false;
}
return ().replace("一十","十");
}
}
FontUtil
package ;
public class FontUtil {
public static void main(String[] args) {
(decodeUnicode("\u63d0\u793a\u4fe1\u606f"));
(chinaToUnicode("提示信息"));
}
/**
* 把中文转成Unicode码
*
* @param str
* @return
*/
public static String chinaToUnicode(String str) {
String result = "";
for (int i = 0; i < (); i++) {
int chr1 = (char) (i);
if (chr1 >= 19968 && chr1 <= 171941) {// 汉字范围 \u4e00-\u9fa5 (中文)
result += "\\u" + (chr1);
} else {
result += (i);
}
}
return result;
}
/**
* 判断是否为中文字符
*
* @param c
* @return
*/
public static boolean isChinese(char c) {
ub = (c);
if (ub == .CJK_UNIFIED_IDEOGRAPHS
|| ub == .CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == .CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == .GENERAL_PUNCTUATION
|| ub == .CJK_SYMBOLS_AND_PUNCTUATION
|| ub == .HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
//Unicode转中文
public static String decodeUnicode(final String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = ("\\\\u");
for (int i = 0; i < ; i++) {
try {
// 汉字范围 \u4e00-\u9fa5 (中文)
if(hex[i].length()>=4){//取前四个,判断是否是汉字
String chinese = hex[i].substring(0, 4);
try {
int chr = (chinese, 16);
boolean isChinese = isChinese((char) chr);
//转化成功,判断是否在 汉字范围内
if (isChinese){//在汉字范围内
// 追加成string
((char) chr);
//并且追加 后面的字符
String behindString = hex[i].substring(4);
(behindString);
}else {
(hex[i]);
}
} catch (NumberFormatException e1) {
(hex[i]);
}
}else{
(hex[i]);
}
} catch (NumberFormatException e) {
(hex[i]);
}
}
return ();
}
}