JAVA poi合并任意列 相同数据单元格
程序员文章站
2024-02-28 18:50:22
...
以下为poi合并单元格
所需要jar如下
commons-collections
poi
java 1.8 版本
以下为代码
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.commons.collections.CollectionUtils;
public class ExportExcelMerge {
public static void main(String[] args) throws IOException {
String[] headers = { "贴现人","付息人","合同号","票号","合同开始日","合同到期日","贴现本金","贴现利率","利息天数","开票贴现利息","开票增值税","开票价税合计","转贴现类型","转贴现日期","转贴现凭证号","转贴现金额","贴现余额","摊销开始日","摊销到期日","摊销天数","转贴现应冲销利息","转贴现应冲销增值税","当月实际摊销利息","当月实际应交增值税","结余利息","结余增值税额","再贴现日期","再贴现凭证号","再贴现金额"};
//List<AntibacterialDrugUse> adu = aduMapper.selectSampleResult(batchNo);
List<String[]> dataset = new ArrayList<String[]>();
// for (AntibacterialDrugUse adus : adu) {
// for (AntibacterialDrugDetail aaa : adus.getAdrugs()) {
// dataset.add(new String[] {adus.getClinicno(),adus.getVisitTime(),adus.getPatientName(),adus.getAge(),adus.getVisitDoctor(),adus.getVisitDept(),adus.getDiagnoseName(),adus.getRecipeCost().toString(),adus.getDrugCount().toString(),adus.getSumDrugCost().toString(),adus.getAntiCount().toString(),adus.getSumAntiCost().toString(),aaa.getAntiName(),aaa.getDrugDose(),aaa.getDrugSpec(),aaa.getDrugCost().toString()});
//}
//}
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190705","CR20190705000016","5000000","0","20190705","20190705","1","0","0","2292.98","137.58","74685.53","4481.14"
});
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190705","CR20190705000016","5000000","0","20190706","20190711","6","0","0","0","0","74685.53","4481.14"
});
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190712","CR20190705000016","-5000000","5000000","20190712","20190715","4","0","0","1310.27","78.62","73375.26","4402.52"
});
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190716","CR20190716000002","5000000","0","20190716","20190716","1","0","0","2292.98","137.58","71082.28","4264.94"
});
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190716","CR20190716000002","5000000","0","20190717","20190722","6","0","0","0","0","71082.28","4264.94"
});
dataset.add(new String[] {"衡水新希望六和农牧有限公司","河北千喜鹤肉类产业有限公司","2018财司贴008号-2019144","190765100004320190225351968201","20190314","20200225","5000000","2.5","348","113993.7","6839.63","120833.33","回购式","20190723","CR20190716000002","-5000000","5000000","20190723","20190731","9","0","0","2948.11","176.89","68134.17","4088.05"
});
// try {
// exportExelMerge("贴现利息台账.xls", title, dataset,false, response, new Integer[]{0}, new Integer[]{0,1,2,3,4,5,6,7,8,9,10,11}, null, null);
//} catch (IOException e) {
//// TODO Auto-generated catch block
//e.printStackTrace();
//}
try {
OutputStream out = new FileOutputStream("E://贴现利息台账.xls");
ExportExcelMerge.createExcelMerge("贴现利息台账.xls", headers, dataset, true, out, new Integer[]{0,1}, new Integer[]{6,9,10,11}, new Integer[]{}, new Integer[]{});
out.close();
//JOptionPane.showMessageDialog(null, "导出成功!");
System.out.println("excel导出成功!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @param fileName 文件名称
* @param headers 表头
* @param dataset 数据集
* @param isSortDataSet 是否对数据排序
* @param response HttpServletResponse
* @param mergeBasis 合并基准列 可选
* @param mergeCells 要合并的列 可选
* @param sumCellsMap 要求和的列 可选
* @param timeCells 时间列 可选
* @throws IOException
*/
public static void exportExelMerge(String fileName,final String[] headers,List<String[]> dataset,boolean isSortDataSet,HttpServletResponse response, final Integer[] mergeBasis, final Integer[] mergeCells, final Integer[] sumCells, final Integer[] timeCells) throws IOException{
String title = "Sheet1";
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));createExcelMerge(title,headers,dataset,isSortDataSet,response.getOutputStream(),mergeBasis,mergeCells,sumCells,timeCells);
response.setStatus(HttpServletResponse.SC_OK);
response.flushBuffer();
}
/**
* @param title 文件名称
* @param headers 表头
* @param dataset 数据集
* @param isSortDataSet 是否对数据排序
* @param out OutputStream
* @param mergeBasis 合并基准列 可选
* @param mergeCells 要合并的列
* @param sumCells 要求和的列
* @param timeCells 时间列 可选
*/
public static void createExcelMerge(String title, final String[] headers,List<String[]> dataset,boolean isSortDataSet, OutputStream out, final Integer[] mergeBasis, final Integer[] mergeCells, final Integer[] sumCells, final Integer[] timeCells){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth(15); // 设置表格默认列宽度为15个字节
HSSFCellStyle headStyle = createHeadStyle(workbook); // 生成头部样式
HSSFCellStyle commonDataStyle = createCommonDataStyle(workbook); // 生成一般数据样式
//不生产合计行
//HSSFCellStyle numStyle = createNumStyle(workbook); //生成数字类型保留两位小数样式
// HSSFCellStyle sumRowStyle = createSumRowStyle(workbook); //生成合计行样式
if(headers == null || headers.length <= 0){
return;
}
HSSFRow row = sheet.createRow(0); // 产生表格标题行
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(headStyle);
HSSFRichTextString text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
if(isSortDataSet && mergeBasis != null && mergeBasis.length > 0){ //是否排序数据
Collections.sort(dataset, new Comparator<String[]>() {
public int compare(String[] o1, String[] o2) {
String s1 = "";
String s2 = "";
for(int i = 0 ; i < mergeBasis.length ; i++){
s1+=(o1[mergeBasis[i].intValue()]+Character.valueOf((char)127).toString());
s2+=(o2[mergeBasis[i].intValue()]+Character.valueOf((char)127).toString());
}
if(timeCells != null && timeCells.length > 0){
for(int i = 0 ; i < timeCells.length ; i++){
s1+= o1[timeCells[i].intValue()];
s2+= o2[timeCells[i].intValue()];
}
}
if(s1.compareTo(s2) < 0){
return -1;
}else if(s1.compareTo(s2) == 0){
return 0;
}else{
return 1;
}
}
});
}
// 遍历集合数据,产生数据行
Iterator<String[]> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
String[] dataSources = it.next() ;
for (int i = 0; i < dataSources.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(commonDataStyle);
cell.setCellValue(dataSources[i]);
}
}
try {
if(mergeBasis != null && mergeBasis.length > 0 && mergeCells != null && mergeCells.length > 0){
for(int i = 0 ; i < mergeCells.length ; i++){
mergedRegion(sheet,mergeCells[i],1,sheet.getLastRowNum(),workbook,mergeBasis);
}
}
//不统计合计行
// if(sumCells != null && sumCells.length > 0){
// createSumRow(sheet, row, headers, sumCells, sumRowStyle, numStyle);
// }
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 创建合计行
* @param sheet
* @param row
* @param headers
* @param sumCells
* @param sumRowStyle
* @param numStyle
*/
@SuppressWarnings("unused")
private static void createSumRow(HSSFSheet sheet , HSSFRow row , final String[] headers, final Integer[] sumCells , HSSFCellStyle sumRowStyle,HSSFCellStyle numStyle){
row=sheet.createRow(sheet.getLastRowNum()+1);
for (int i = 0; i < headers.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellStyle(sumRowStyle);
}
for(int i = 1 ; i < sheet.getLastRowNum() ; i++){
for(int j = 0 ; j < sumCells.length ; j++){
sheet.getRow(i).getCell(sumCells[j]).setCellValue(Double.parseDouble(sheet.getRow(i).getCell(sumCells[j]).getStringCellValue()));
sheet.getRow(i).getCell(sumCells[j]).setCellStyle(numStyle);
}
}
HSSFCell sumCell = row.getCell(0);
sumCell.setCellValue("合计:");
String sumFunctionStr = null;
// for(int i = 0 ; i < sumCells.length ; i++){
// sumFunctionStr = "SUM("+CellReference.convertNumToColString(sumCells[i])+"2:"+CellReference.convertNumToColString(sumCells[i])+sheet.getLastRowNum()+")";
// row.getCell(sumCells[i]).setCellFormula(sumFunctionStr);
// }
}
/**
* 合并单元格
* @param sheet
* @param cellLine
* @param startRow
* @param endRow
* @param workbook
* @param mergeBasis
*/
private static void mergedRegion(HSSFSheet sheet, int cellLine,int startRow, int endRow, HSSFWorkbook workbook, Integer[] mergeBasis) {
HSSFCellStyle style = workbook.createCellStyle(); // 样式对象
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平
String s_will = sheet.getRow(startRow).getCell(cellLine).getStringCellValue(); // 获取第一行的数据,以便后面进行比较
int count = 0;
Set<Integer> set = new HashSet<Integer>();
CollectionUtils.addAll(set, mergeBasis);
for (int i = 2; i <= endRow; i++) {
String s_current = sheet.getRow(i).getCell(cellLine).getStringCellValue();
if (s_will.equals(s_current)) {
boolean isMerge = true;
if(!set.contains(cellLine)){//如果不是作为基准列的列 需要所有基准列都相同
for(int j = 0 ; j < mergeBasis.length ; j++){
if(!sheet.getRow(i).getCell(mergeBasis[j]).getStringCellValue()
.equals(sheet.getRow(i-1).getCell(mergeBasis[j]).getStringCellValue())){
isMerge = false;
}
}
}else{//如果作为基准列的列 只需要比较列号比本列号小的列相同
for(int j = 0 ; j < mergeBasis.length && mergeBasis[j] < cellLine ; j++){
if(!sheet.getRow(i).getCell(mergeBasis[j]).getStringCellValue()
.equals(sheet.getRow(i-1).getCell(mergeBasis[j]).getStringCellValue())){
isMerge = false;
}
}
}
if(isMerge){
count++;
}else{
sheet.addMergedRegion(new CellRangeAddress( startRow, startRow+count,cellLine , cellLine));
startRow = i;
s_will = s_current;
count = 0;
}
} else {
sheet.addMergedRegion(new CellRangeAddress( startRow, startRow+count,cellLine , cellLine));
startRow = i;
s_will = s_current;
count = 0;
}
if (i == endRow && count > 0) {
sheet.addMergedRegion(new CellRangeAddress(startRow,startRow+count ,cellLine , cellLine));
}
}
}
/**
* 标题单元格样式
* @param workbook
* @return
*/
private static HSSFCellStyle createHeadStyle(HSSFWorkbook workbook){
//标题单元格样式
HSSFCellStyle headStyle = workbook.createCellStyle();
headStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
headStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
headStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
headStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
headStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
headStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
headStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//标题单元格字体
HSSFFont headFont = workbook.createFont();
headFont.setColor(HSSFColor.VIOLET.index);
headFont.setFontHeightInPoints((short) 12);
headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
headStyle.setFont(headFont);
return headStyle;
}
/**
* 合计行单元格样式
* @param workbook
* @return
*/
@SuppressWarnings("unused")
private static HSSFCellStyle createSumRowStyle(HSSFWorkbook workbook){
//合计行单元格样式
HSSFCellStyle sumRowStyle = workbook.createCellStyle();
sumRowStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
sumRowStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
sumRowStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
sumRowStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
sumRowStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
sumRowStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
sumRowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
sumRowStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
//合计行单元格字体
HSSFFont sumRowFont = workbook.createFont();
sumRowFont.setColor(HSSFColor.VIOLET.index);
sumRowFont.setFontHeightInPoints((short) 12);
sumRowFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
sumRowStyle.setFont(sumRowFont);
return sumRowStyle;
}
/**
* 普通数据单元格样式
* @param workbook
* @return
*/
private static HSSFCellStyle createCommonDataStyle(HSSFWorkbook workbook){
//普通数据单元格样式
HSSFCellStyle commonDataStyle = workbook.createCellStyle();
commonDataStyle.setFillForegroundColor(HSSFColor.WHITE.index);
commonDataStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
commonDataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
commonDataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
commonDataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
commonDataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
commonDataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
commonDataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
//普通数据单元格字体
HSSFFont commonDataFont = workbook.createFont();
commonDataFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字体应用到当前的样式
commonDataStyle.setFont(commonDataFont);
return commonDataStyle;
}
/**
* 自定义保留两位小数数字单元格格式
* @param workbook
* @return
*/
@SuppressWarnings("unused")
private static HSSFCellStyle createNumStyle(HSSFWorkbook workbook){
//自定义保留两位小数数字单元格格式
HSSFCellStyle numStyle = workbook.createCellStyle();
numStyle.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
numStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
numStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
numStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
numStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
numStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
numStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
numStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
numStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("#,##0.00"));
//自定义保留两位小数数字单元格字体
HSSFFont numFont = workbook.createFont();
numFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
//把字体应用到当前的样式
numStyle.setFont(numFont);
return numStyle;
}
/*
* 自定义方法 用于自己场景 于页面中下载
*/
public static void createExcelMerge(IActionContext context, String string, String[] headers, List<String[]> dataset,
boolean b, OutputStream out, Integer[] integers, Integer[] integers2, Integer[] integers3,
Integer[] integers4,String str) {
// TODO Auto-generated method stub
//合并单元格
createExcelMerge(string, headers, dataset, b, out, integers, integers2,integers3,integers4);
//用于本地测试
//String arg42 = "/servlet/fileUploadServlet?action=export&filePathName=" + "E:\\reslut.xls" + "&fileName=" + "reslut" + ".xls";
//文件下载路径
String arg42 = "/servlet/fileUploadServlet?action=export&filePathName=" + str + "&fileName=" + "reslut" + ".xls";
Forward arg43 = context.getForward();
arg43.setTarget("_self");
arg43.setPath(arg42);
context.setForward(arg43);
}
}
一下为Vo 转换为 String 的类
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class EntityToString {
//定义基本类型
static Map<Class<?>, Object> classes = new HashMap<Class<?>, Object>();
//定义超过此长度截取
static Integer subStrLength = 200;
static{
classes.put(byte.class, "");
classes.put(short.class, "");
classes.put(int.class, "");
classes.put(long.class, "");
classes.put(float.class, "");
classes.put(double.class, "");
classes.put(char.class, "");
classes.put(boolean.class, "");
classes.put(Byte.class, "");
classes.put(Short.class, "");
classes.put(Integer.class, "");
classes.put(Long.class, "");
classes.put(Float.class, "");
classes.put(Double.class, "");
classes.put(Character.class, "");
classes.put(Boolean.class, "");
classes.put(String.class, "");
}
/**
* @Title: getString
* @author: linyan
* @Description:
* @param o 需要转换的对象
* @return
*/
public static String getString(Object o) {
return getString(o,1);
}
/**
* @Title: getString
* @author: linyan
* @Description:
* @param o 需要转换的对象
* @param endLeve 结束 等级
* @return
*/
public static String getString(Object o,Integer endLeve ) {
return getString(o,0,endLeve);
}
/**
* @Title: getString
* @author: linyan
* @Description:
* @param o 需要转换的对象
* @param leve 等级
* @param endLeve 结束 等级
* @return
*/
public static String getString(Object o,Integer leve,Integer endLeve )
{
Integer lev = leve + 1;
Class<?> c = o.getClass();
String result = "";
// if (leve==0) {
// result+=c.getSimpleName();
// }
//不需要此括号
//result+= "{";
// 获取类中的所有定义字段
Field[] fields = c.getDeclaredFields();
//循环遍历字段,获取字段对应的值
for (Field field : fields)
{
// 如果不为空,设置可见性(也就是设置私有变量可以访问),然后返回
field.setAccessible(true);
try
{
//有值
if(field.get(o) != null){
Class<?> fieldClass = field.get(o).getClass();
//如果是基本类型 直接 取值 用get直接取
if(classes.containsKey(fieldClass)){
//result += field.getName() + "=" + subStr(field.get(o)) +",";
if(field.get(o) == null || field.get(o) == ""){
result += ",";
}else{
result +=subStr(field.get(o)) +",";
}
}else if(field.get( o ) instanceof Iterable ){ // 迭代器 类型的
result += field.getName()+ " = ";
result += iterableClass(field.get( o ),leve,endLeve);
}else if(field.get( o ) instanceof Map){ // Map 类型的
result += field.getName( )+ " = ";
result += mapClass(field.get(o), leve, endLeve);
}else if(fieldClass.isArray()){ // 数组类型
Object object = field.get(o);
result += field.getName()+ " = ";
result += arrayClass(object, leve, endLeve);
}else { // 其他 类型的
/*这个判断是我 自己加的 只对 我现在的项目 有用
判断 字段值 的 包名 中 是否 有 entity 并且 现在的层级 不能 大于 结束 层级
如果有 就是 自己写的类 那么字段的 值 也 要 生成 为 string 类型
*/
if (fieldClass.getCanonicalName().indexOf("entity")>-1&&leve!=endLeve) {
// result += field.getName() + "=" + getString(field.get(o),lev,endLeve) +",";
result += getString(field.get(o),lev,endLeve) +",";
}else { // 这个就是真正的 其他类型了 如 file 等
//result += field.getName() + "=" + field.get(o) +",";
if(field.get(o) == null || field.get(o) == ""){
result += ",";
}else{
result += field.get(o) +",";
}
}
}
}else {
//没有值
//result += field.getName() + "=" + field.get(o) +",";
if(field.get(o) == null || field.get(o) == ""){
result += ",";
}else{
result += field.get(o) +",";
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
//去除 最后一个 ,
if(result.indexOf(",")>=0) result = result.substring(0 , result.length()-1);
//return result+"}"; 不需要前后括号
return result;
}
/**
* @Title: iterableClass
* @author: linyan
* @Description: 迭代器 类型
* @param obj
* @param leve
* @param endLeve
* @return
*/
public static String iterableClass(Object obj,Integer leve,Integer endLeve){
String result = "[";
Iterable<?> ite = (Iterable<?>)obj;
for (Object object : ite) {
if(object != null){
if (classes.containsKey(object.getClass())) {
result += subStr(object) +",";
}else if(object instanceof Iterable){
result += iterableClass(object,leve,endLeve);
}else if(object instanceof Map){
result += mapClass(object, leve, endLeve);
}else if(object.getClass().isArray()){
result += arrayClass(object, leve, endLeve);
}else {
result += elseClass(object,leve,endLeve);
}
}else{
result += null;
}
}
if(result.indexOf( "," )>=0) result = result.substring( 0 , result.length()-1 );
result += "],";
return result;
}
/**
* @Title: mapClass
* @author: linyan
* @Description: Map 类型
* @param obj
* @param leve
* @param endLeve
* @return
*/
public static String mapClass(Object obj,Integer leve,Integer endLeve){
String result = "{";
Map<?,?> map1 = (Map<?,?>)obj;
for (Map.Entry<?, ?> entry1 : map1.entrySet()) {
if (entry1.getValue() != null) {
if (classes.containsKey(entry1.getValue().getClass())) {
result += entry1.getKey()+"="+ subStr(entry1.getValue()) +",";
}else if(entry1.getValue() instanceof Iterable){
result += entry1.getKey()+ "=" + iterableClass(entry1.getValue(),leve,endLeve);
}else if(entry1.getValue() instanceof Map){
result += entry1.getKey()+ "=" + mapClass(entry1.getValue(),leve,endLeve);
}else if(obj.getClass().isArray()){
result += entry1.getKey()+ "=" + arrayClass(entry1.getValue(), leve, endLeve);
}else {
result += entry1.getKey()+ "=" + elseClass(entry1.getValue(),leve,endLeve);
}
}else{
result += null;
}
}
if(result.indexOf( "," )>=0) result = result.substring( 0 , result.length()-1 );
result += "},";
return result;
}
/**
* @Title: arrayClass
* @author: linyan
* @Description: 数组 类型
* @param object
* @param leve
* @param endLeve
* @return
*/
public static String arrayClass(Object object,Integer leve,Integer endLeve){
String result = "[";
int length = Array.getLength(object) ;
for (int i = 0; i < length; i++) {
Object object2 = Array.get(object,i);
if (object2!=null) {
if (classes.containsKey(object2.getClass())) {
result += subStr(object2)+",";
}else if(object2 instanceof Iterable){
result += iterableClass(object2,leve,endLeve);
}else if (object2 instanceof Map) {
result += mapClass(object2, leve, endLeve);
}else if (object2.getClass().isArray()) {
result += arrayClass(object2, leve, endLeve);
}else {
result += elseClass(object2,leve,endLeve);
}
}else{
result += null;
}
}
if(result.indexOf( "," )>=0) result = result.substring( 0 , result.length()-1 );
result += "],";
return result;
}
/**
* @Title: elseClass
* @author: linyan
* @Description: 其他类型
* @param object
* @param leve
* @param endLeve
* @return
*/
public static String elseClass(Object object,Integer leve,Integer endLeve){
String result = "";
Integer le = leve + 1;
if (object.getClass().getCanonicalName().indexOf("entity")>-1&&leve!=endLeve) {
// 设置字段可见,即可用get方法获取属性值。
result += getString(object,le,endLeve) +",";
}else {
// 设置字段可见,即可用get方法获取属性值。
result += object+",";
}
return result;
}
/**
* @Title: subStr
* @author: linyan
* @Description: 截取字符串
* @param object
* @return
*/
public static String subStr(Object object){
if (object!=null) {
if (object.toString().length()>subStrLength) {
return object.toString().substring(0, subStrLength);
}else{
return object.toString();
}
}else{
return "";
}
}
}
上一篇: 什么是ETag
下一篇: MySQL主从同步原理介绍