java-根据Excel的字段名称实现导入,poi-pinyin4j

实现excel导入。

 

核心导入类---ExcelOperate 

package com.excelUtils;

import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

public class ExcelOperate {

    /**
     * 汉字转全拼
     */
    public static HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper() ;


    public static void main(String[] args) throws Exception {
        // 创建Excel表格
        //createExcel(getStudent());

        // 读取Excel表格
        Student student = new Student();
        testHH testHH = new testHH();
        TrackReport trackReport = new TrackReport();
        List<Object> list = readExcel(trackReport,trackReport.getClass(),"com.excelUtils.TrackReport",TrackReport.class,"F:/桌面/test2.xls");


    }

    /**
     * 初始化数据
     *
     * @return 数据
     */
//    private static List<Student> getStudent() {
//        List<Student> list = new ArrayList<Student>();
//        Student student1 = new Student("小明", "8", "二年级");
//        Student student2 = new Student("小光", "8", "三年级");
//        Student student3 = new Student("小花", "8", "四年级");
//        list.add(student1);
//        list.add(student2);
//        list.add(student3);
//        return list;
//    }

    /**
     * 创建Excel
     *
     * @param list
     *            数据
     */
//    private static void createExcel(List<Student> list) {
//        // 创建一个Excel文件
//        HSSFWorkbook workbook = new HSSFWorkbook();
//        // 创建一个工作表
//        HSSFSheet sheet = workbook.createSheet("学生表一");
//        // 添加表头行
//        HSSFRow hssfRow = sheet.createRow(0);
//        // 设置单元格格式居中
//        HSSFCellStyle cellStyle = workbook.createCellStyle();
//        //cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//
//        // 添加表头内容
//        HSSFCell headCell = hssfRow.createCell(0);
//        headCell.setCellValue("姓名");
//        headCell.setCellStyle(cellStyle);
//
//        headCell = hssfRow.createCell(1);
//        headCell.setCellValue("年龄");
//        headCell.setCellStyle(cellStyle);
//
//        headCell = hssfRow.createCell(2);
//        headCell.setCellValue("年级");
//        headCell.setCellStyle(cellStyle);
//
//        // 添加数据内容
//        for (int i = 0; i < list.size(); i++) {
//            hssfRow = sheet.createRow((int) i + 1);
//            Student student = list.get(i);
//
//            // 创建单元格,并设置值
//            HSSFCell cell = hssfRow.createCell(0);
//            cell.setCellValue(student.getXingming());
//            cell.setCellStyle(cellStyle);
//
//            cell = hssfRow.createCell(1);
//            cell.setCellValue(student.getNianji());
//            cell.setCellStyle(cellStyle);
//
//            cell = hssfRow.createCell(2);
//            cell.setCellValue(student.getNianji());
//            cell.setCellStyle(cellStyle);
//        }
//
//        // 保存Excel文件F:\桌面
//        try {
//            OutputStream outputStream = new FileOutputStream("F:/桌面/工业分级后的化学成分导入模板.xlsx");
//            workbook.write(outputStream);
//            outputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * readExcel(trackReport,trackReport.getClass(),"com.excelUtils.TrackReport",TrackReport.class);
     * 读取Excel
     * @param obj  对应实体类对象引用 trackReport
     * @param clazz trackReport.getClass()
     * @param classPathName  类路径 com.excelUtils.TrackReport
     * @param classn TrackReport.class
     * @param url 文件路径
     * @return excel对应的集合
     * @throws NoSuchFieldException
     * @throws IllegalAccessException
     * @throws InstantiationException
     */
    public static List<Object> readExcel(Object obj,Class<?> clazz,String classPathName,Class classn,String url) throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        List<Object> list = new ArrayList<Object>();
        Workbook workbook = null;
        XSSFWorkbook xssfWorkbook = null;

        //url = "F:/桌面/test2.xls";

        try {
            // 读取Excel文件
            InputStream inputStream = new FileInputStream(url);
            if(url.substring(url.length()-4,url.length()).contains(".xls")){//03读取03格式
                workbook = new HSSFWorkbook(inputStream);
            }else if(url.substring(url.length()-4,url.length()).contains("xlsx")){//07读取07格式
                workbook = new XSSFWorkbook(inputStream);
            }
            inputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        long count = 0;
        // 循环工作表
        for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {

            //保存表头全拼,此处就是为了将excel中的汉字转成对应的全拼用的是pinyin4j
            LinkedHashMap<Integer,String> totals = new LinkedHashMap<Integer, String>();


            Sheet hssfSheet = workbook.getSheetAt(numSheet);
            if (hssfSheet == null) {
                continue;
            }
            // 循环行
            for (int rowNum = 0; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
                System.out.println("当前行:"+rowNum);
                Row hssfRow = hssfSheet.getRow(rowNum);
                if (hssfRow == null) {
                    continue;
                }
                //获取单元格
                for (int cellNum = 0;cellNum<hssfRow.getLastCellNum();cellNum++){
                    Cell hssfCell = hssfRow.getCell(cellNum);

                    // 将单元格中的内容存入集合
                    Object student = new Object();

                    //储存转为全拼的表头
                    if(rowNum==0){//一般第一行为表头,也就是汉字部分,需要进行转成全拼,然后与创建的实体类属性名称对应
                        totals.put(cellNum,hanyuPinyinHelper.toHanyuPinyin(hssfCell.getStringCellValue()));
                    }else{
                        //rowNum不为0的时候位数据位
                        System.out.println(totals.get(cellNum));
                        if (hssfCell==null){//如果为null就给个默认值“NULL”
                            //通过反射调用set
                            setValue(obj, clazz, totals.get(cellNum), classn.getDeclaredField(totals.get(cellNum)).getType(), "null");
                        }else{
                            //通过反射调用set
                            setValue(obj, clazz, totals.get(cellNum), classn.getDeclaredField(totals.get(cellNum)).getType(), hssfCell.getStringCellValue());
                            }

                    }
                }

                //重新创建obj
                try {
                    //添加进list
                    if (!(rowNum==0)){
                        list.add(obj);
                        //通过类名创建obj
                        obj = Class.forName(classPathName).newInstance();
                    }
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();

                }





            }
        }
        return list;
    }



    /**
     * 根据属性,拿到set方法,并把值set到对象中
     * @param obj 对象
     * @param clazz 对象的class
     * @param //fileName 需要设置值得属性
     * @param typeClass
     * @param value
     */
    public static void setValue(Object obj,Class<?> clazz,String filedName,Class<?> typeClass,Object value){
        filedName = removeLine(filedName);
        String methodName = "set" + filedName.substring(0,1).toUpperCase()+filedName.substring(1);
        try{
            Method method =  clazz.getDeclaredMethod(methodName, new Class[]{typeClass});
            method.invoke(obj, new Object[]{getClassTypeValue(typeClass, value)});
        }catch(Exception ex){
            ex.printStackTrace();
        }
    }


    /**
     * 处理字符串  如:  abc_dex ---> abcDex
     * @param str
     * @return
     */
    public static  String removeLine(String str){
        if(null != str && str.contains("_")){
            int i = str.indexOf("_");
            char ch = str.charAt(i+1);
            char newCh = (ch+"").substring(0, 1).toUpperCase().toCharArray()[0];
            String newStr = str.replace(str.charAt(i+1), newCh);
            String newStr2 = newStr.replace("_", "");
            return newStr2;
        }
        return str;
    }


    /**
     * 通过class类型获取获取对应类型的值
     * @param typeClass class类型
     * @param value 值
     * @return Object
     */
    public static Object getClassTypeValue(Class<?> typeClass, Object value){
        if(typeClass == int.class  || value instanceof Integer){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == short.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == byte.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == double.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == long.class){
            if(null == value){
                return 0;
            }
            return value;
        }else if(typeClass == String.class){
            if(null == value){
                return "";
            }
            return value;
        }else if(typeClass == boolean.class){
            if(null == value){
                return true;
            }
            return value;
        }else if(typeClass == BigDecimal.class){
            if(null == value){
                return new BigDecimal(0);
            }
            return new BigDecimal(value+"");
        }else {
            return typeClass.cast(value);
        }
    }

}

 

处理汉字转全拼---HanyuPinyinHelper
package com.excelUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.lang.reflect.Method;

public class HanyuPinyinHelper {

    /**
     * 将文字转为汉语拼音
     * @param //chineselanguage 要转成拼音的中文
     */
    public String toHanyuPinyin(String ChineseLanguage){
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部小写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        defaultFormat.setVCharType(HanyuPinyinVCharType.WITH_V) ;
        try {
            for (int i=0; i<cl_chars.length; i++){
                if (String.valueOf(cl_chars[i]).matches("[\u4e00-\u9fa5]+")){// 如果字符是中文,则将中文转为汉语拼音
                    hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0];
                } else {// 如果字符不是中文,则不转换
                    hanyupinyin += cl_chars[i];
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }

    public static String getFirstLettersUp(String ChineseLanguage){
        return getFirstLetters(ChineseLanguage ,HanyuPinyinCaseType.UPPERCASE);
    }

    public static String getFirstLettersLo(String ChineseLanguage){
        return getFirstLetters(ChineseLanguage ,HanyuPinyinCaseType.LOWERCASE);
    }

    public static String getFirstLetters(String ChineseLanguage,HanyuPinyinCaseType caseType) {
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(caseType);// 输出拼音全部大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            for (int i = 0; i < cl_chars.length; i++) {
                String str = String.valueOf(cl_chars[i]);
                if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                    hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(cl_chars[i], defaultFormat)[0].substring(0, 1);
                } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                    hanyupinyin += cl_chars[i];
                } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母
                    hanyupinyin += cl_chars[i];
                } else {// 否则不转换
                    hanyupinyin += cl_chars[i];//如果是标点符号的话,带着
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }

    public static String getPinyinString(String ChineseLanguage){
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);// 输出拼音全部大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            for (int i = 0; i < cl_chars.length; i++) {
                String str = String.valueOf(cl_chars[i]);
                if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                    hanyupinyin += PinyinHelper.toHanyuPinyinStringArray(
                            cl_chars[i], defaultFormat)[0];
                } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                    hanyupinyin += cl_chars[i];
                } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母

                    hanyupinyin += cl_chars[i];
                } else {// 否则不转换
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }
    /**
     * 取第一个汉字的第一个字符
     * @Title: getFirstLetter
     * @Description: TODO
     * @return String
     * @throws
     */
    public static String getFirstLetter(String ChineseLanguage){
        char[] cl_chars = ChineseLanguage.trim().toCharArray();
        String hanyupinyin = "";
        HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
        defaultFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);// 输出拼音全部大写
        defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);// 不带声调
        try {
            String str = String.valueOf(cl_chars[0]);
            if (str.matches("[\u4e00-\u9fa5]+")) {// 如果字符是中文,则将中文转为汉语拼音,并取第一个字母
                hanyupinyin = PinyinHelper.toHanyuPinyinStringArray(
                        cl_chars[0], defaultFormat)[0].substring(0, 1);;
            } else if (str.matches("[0-9]+")) {// 如果字符是数字,取数字
                hanyupinyin += cl_chars[0];
            } else if (str.matches("[a-zA-Z]+")) {// 如果字符是字母,取字母

                hanyupinyin += cl_chars[0];
            } else {// 否则不转换

            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            System.out.println("字符不能转成汉语拼音");
        }
        return hanyupinyin;
    }

    public static void main(String[] args) {
        HanyuPinyinHelper hanyuPinyinHelper = new HanyuPinyinHelper() ;
        System.out.println(hanyuPinyinHelper.toHanyuPinyin("多发的发独守空房阿道夫打发第三方"));
    }

    /**
     * 根据属性,获取get方法
     * @param ob 对象
     * @param name 属性名
     * @return
     * @throws Exception
     */
    public static Object getGetMethod(Object ob , String name)throws Exception{
        Method[] m = ob.getClass().getMethods();
        for(int i = 0;i < m.length;i++){
            if(("get"+name).toLowerCase().equals(m[i].getName().toLowerCase())){
                return m[i].invoke(ob);
            }
        }
        return null;
    }
}

实体类

package com.excelUtils;

public class Student {

    private String xingming;
    private String nianling;
    private String nianji;

    public Student(String name,String age,String grade){
        this.xingming=name;
        this.nianji=age;
        this.nianji=grade;
    }
    public Student(){}

    public String getXingming() {
        return xingming;
    }

    public void setXingming(String xingming) {
        this.xingming = xingming;
    }

    public String getNianling() {
        return nianling;
    }

    public void setNianling(String nianling) {
        this.nianling = nianling;
    }

    public String getNianji() {
        return nianji;
    }

    public void setNianji(String nianji) {
        this.nianji = nianji;
    }
}

excel

这些就基本是所有的需要用到的东西了。

excel中汉字全拼要与实体类中的对应,

public static void main(String[] args) throws Exception {
        // 创建Excel表格
        //createExcel(getStudent());

        // 读取Excel表格
        Student student = new Student();
        List<Object> list = readExcel(student ,student .getClass(),"com.excelUtils.student ",student .class,"F:/桌面/test2.xls");


    }

然后在

ExcelOperate的main中有例子,创建一个实体类,然后传入类信息和excel文件路径

然后的list就是excel中的所有东西。

当然了,这只是简单的封装,仅适用于excel表头不是那么花里胡哨的。

花里胡哨的应该也可以写,但是这个就应该足够用了。

主要就是pinyin4j与poi的结合使用,是excel的导入变的更简单化,传入任何与excel表头全拼对应的实体类都可以得到对应的excel,list对象,减少了重复写的工作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值