栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

excel工具类和获取对象的属性名和属性值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

excel工具类和获取对象的属性名和属性值

package com.clouddo.basicdb.common;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class PoiUtil {


public static List readExcel(MultipartFile file) throws IOException {
return readExcel(file.getInputStream(),file.getOriginalFilename(),1,0);
}


public static List readExcel(InputStream file, String fileName, int starRow, int starCell) {
Workbook wb = null;
//判断文件类型 03或是07
try {
if (isExcel2007(fileName)) {
wb = new XSSFWorkbook(file);
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook(file);
}
} catch (Exception e) {
logger.error(“解析excel文档流有误。”, e);
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
List list = new ArrayList<>();
//选择sheet文件
Sheet sheet = wb.getSheetAt(0);

 //获得最大行数
 int lastRowNum = sheet.getLastRowNum();
 //System.out.println("最大row行数是:"+lastRowNum);
 for (int i = starRow; i <= lastRowNum; i++) {
     //获取第i行的数据
     Row row = sheet.getRow(i);
     //获取第i行的最大cell格
     int lastCellNum = row.getLastCellNum();
     //System.out.println("第"+(i+1)+"行最大cell格数是:"+lastCellNum);
     //创建保存数据的String 数组对象
     String[] obj = new String[lastCellNum];
     for (int j = starCell; j < lastCellNum; j++) {
         Cell cell = row.getCell(j);
         //获取当前cell表格的值,并放入obj
         obj[j] = getMyCellType(cell);
     }
     list.add(obj);
 }
 wb.close();
 logger.info("读取excel,成功将其转成Object数组");
 return list;

} catch (Exception e) {
logger.error(“解析excel文档流有误。”, e);
return null;
}
}


public static void downLoadExcel(String[] columnNames, String[] keyList, List objList, String filePath, String fileName){
if (objList.size() > 1000000){
List> lists = fixedGrouping(objList, 1000000);
for (int i = 0; i < lists.size(); i++) {
downLoadExcelManySheet(columnNames,keyList,lists,filePath,fileName,0);
}
}else {
downLoadExcelSingleSheet(columnNames,keyList,objList,filePath,fileName);
}
}

private static void downLoadExcelManySheet(String[] columnNames, String[] keyList, List> objList, String filePath, String fileName,int num) {
Workbook wb = null;
//判断文件类型 03或是07
if (isExcel2007(fileName)) {
wb = new SXSSFWorkbook();
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook();
}
//创建sheet
for (int a = 0; a < objList.size(); a++) {
List objects = objList.get(a);
Sheet sheet = wb.createSheet(“sheet” + a);
//创建第一行,存放key
Row row = sheet.createRow(0);
for (int i = 0; i < keyList.length; i++) {
row.createCell(i).setCellValue(keyList[i]);
}
//先创建object空对象
Object project = null;
for (int i = 0; i < objects.size(); i++) {
Row row1 = sheet.createRow(i+1);
for (int j = 0; j < columnNames.length; j++) {
//创建obj实例
project = objects.get(i);
row1.createCell(j).setCellValue(getValueByName(columnNames[j],project)+"");
}
}
}
//将文件响应到电脑
try {
FileOutputStream fileOut = new FileOutputStream(filePath+""+fileName);
wb.write(fileOut);
} catch (Exception e) {
e.printStackTrace();
}
}

private static void downLoadExcelSingleSheet(String[] columnNames, String[] keyList, List objList, String filePath, String fileName) {
Workbook wb = null;
//判断文件类型 03或是07
if (isExcel2007(fileName)) {
wb = new SXSSFWorkbook();
}
if (isExcel2003(fileName)) {
wb = new HSSFWorkbook();
}
//创建sheet
Sheet sheet = wb.createSheet();

 //创建第一行,存放key
 Row row = sheet.createRow(0);
 for (int i = 0; i < keyList.length; i++) {
     row.createCell(i).setCellValue(keyList[i]);
 }
 //先创建object空对象
 Object project = null;
 for (int i = 0; i < objList.size(); i++) {
     Row row1 = sheet.createRow(i+1);
     for (int j = 0; j < columnNames.length; j++) {
         //创建obj实例
         project = objList.get(i);
         row1.createCell(j).setCellValue(getValueByName(columnNames[j],project)+"");
     }
 }
 //将文件响应到电脑
 try {
     FileOutputStream fileOut = new FileOutputStream(filePath+"\"+fileName);
     wb.write(fileOut);
 } catch (Exception e) {
     e.printStackTrace();
 }

}

//利用反射获得对象的值
private static Object getValueByName(String fieldName, Object obj){
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = “get” + firstLetter + fieldName.substring(1);
Method method = obj.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(obj, new Object[] {});
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

//获得cell的值
private static String getMyCellType(Cell cell){
String value = “”;
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC: // 数字
//如果为时间格式的内容
if (DateUtil.isCellDateFormatted(cell)) {
//注:format格式 yyyy-MM-dd hh:mm:ss 中小时为12小时制,若要24小时制,则把小h变为H即可,yyyy-MM-dd HH:mm:ss
SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-MM-dd hh:mm:ss”);
value=sdf.format(DateUtil.getJavaDate(cell.getNumericCellValue())).toString();
break;
} else {
value = new DecimalFormat(“0”).format(cell.getNumericCellValue());
}
break;
case Cell.CELL_TYPE_STRING: // 字符串
value = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN: // Boolean
value = cell.getBooleanCellValue() + “”;
break;
case Cell.CELL_TYPE_FORMULA: // 公式
value = cell.getCellFormula() + “”;
break;
case Cell.CELL_TYPE_BLANK: // 空值
value = “”;
break;
case Cell.CELL_TYPE_ERROR: // 故障
value = “非法字符”;
break;
default:
value = “未知类型”;
break;
}
return value;
}

// 关闭文件流
private static void close(MultipartFile file) {
try {
InputStream inputStream = file.getInputStream();
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
//关闭流
private static void close(InputStream file) {
if (file != null) {
try {
file.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
}

//验证手机号格式是或正确
private static boolean isMobile(String str) {
Pattern p = null;
Matcher m = null;
boolean isMatch = false;
//制定验证条件
String regex1 = “1[3,4,5,7,8][0-9]{9} " ; S t r i n g r e g e x 2 = " ( ( 13 [ 0 − 9 ] ) ∣ ( 14 [ 579 ] ) ∣ ( 15 ( [ 0 − 3 , 5 − 9 ] ) ) ∣ ( 16 [ 6 ] ) ∣ ( 17 [ 0135678 ] ) ∣ ( 18 [ 0 − 9 ] ∣ 19 [ 89 ] ) ) d 8 "; String regex2 = "^((13[0-9])|(14[579])|(15([0-3,5-9]))|(16[6])|(17[0135678])|(18[0-9]|19[89]))\d{8} ";Stringregex2="((13[0−9])∣(14[579])∣(15([0−3,5−9]))∣(16[6])∣(17[0135678])∣(18[0−9]∣19[89]))d8”;
p = Pattern.compile(regex2);
m = p.matcher(str);
isMatch = m.matches();
return isMatch;
}


private static List> fixedGrouping(List source, Integer n) {
if (null == source || source.size() == 0 || n <= 0)
return null;
List> result = new ArrayList<>();
int remainder = source.size() % n;
int size = (source.size() / n);
for (int i = 0; i < size; i++) {
List subset = null;
subset = source.subList(i * n, (i + 1) * n);
result.add(subset);
}
if (remainder > 0) {
List subset = null;
subset = source.subList(size * n, size * n + remainder);
result.add(subset);
}
return result;
}

private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);

private static String suffix_xls = “.xls”;

private static String suffix_xlsx = “.xlsx”;

// 判断是否是03的excel:xls
private static boolean isExcel2003(String filePath) {
return filePath.matches("^.+.(?i)(xls)$");
}

// 判断是否是07的excel:xlsx
private static boolean isExcel2007(String filePath) {
return filePath.matches("^.+.(?i)(xlsx)$");
}

// 根据后缀名判断excel是否合法
private static boolean isCorrectExcel(String filePath) {
if (isExcel2003(filePath) || isExcel2003(filePath)) {
return true;
} else {
return false;
}
}

}
————————————————
版权声明:本文为CSDN博主「仄.」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44186783/article/details/85682463

获取Java对象中所有的属性名称和属性值

1,首先我们创建一个Java实体类Person,并创建属性name,age,gender,代码如下:

public class Person {
private String name;
private int age;
private String gender;

public Person(String n,int a,String g) {
	name = n;
	age = a;
	gender = g;
}

public String getName() {
	return name;
}

public int getAge() {
	return age;
}
public String getGender() {
	return gender;
}

}
2、创建对象
Person person = new Person(“zhangsan”, 30, “男”);
3、创建获取属性数组的方法

  
private static String[] getFiledName(Object o){  
    Field[] fields=o.getClass().getDeclaredFields();  
    String[] fieldNames=new String[fields.length];  
    for(int i=0;i 

// System.out.println(fields[i].getType());
fieldNames[i]=fields[i].getName();
}
return fieldNames;
}
4,根据属性名称获取对应的属性值(通过get方法)

private static Object getFieldValueByName(String fieldName, Object o) {
try {
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getter = “get” + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[] {});
Object value = method.invoke(o, new Object[] {});
return value;
} catch (Exception e) {

        return null;    
    }    
}   

5、完美调用
StringBuilder sbName = new StringBuilder();
StringBuilder sbValue = new StringBuilder();
String[] fieldNames = getFiledName(person);

	  for(int j=0 ; j 

6、打印结果:
attribute name:name/age/gender
attribute value:zhangsan/30/男

————————————————
版权声明:本文为CSDN博主「Richard152」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/a1527238987/article/details/79121372


  1. 1 ↩︎

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/341087.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号