import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

/**
 * POI解析Excel
 */
public class ExcelReaderUtil {
    /**
     * 根据fileType不同读取excel文件
     * 
     * @param path
     * @param path
     * @throws IOException
     */
    public static List<List<String>> readExcel(String path) {
        String fileType = path.substring(path.lastIndexOf(".") + 1);
        // return a list contains many list
        List<List<String>> lists = new ArrayList<List<String>>();
        // 读取excel文件
        InputStream is = null;
        try {
            is = new FileInputStream(path);
            // 获取工作薄
            Workbook wb = null;
            if (fileType.equals("xls")) {
                wb = new HSSFWorkbook(is);
            } else if (fileType.equals("xlsx")) {
                wb = new XSSFWorkbook(is);
            } else {
                return null;
            }

            // 读取第一个工作页sheet
            Sheet sheet = wb.getSheetAt(0);
            // 第一行为标题
            for (Row row : sheet) {
                ArrayList<String> list = new ArrayList<String>();
                for (Cell cell : row) {
                    // 根据不同类型转化成字符串
                    cell.setCellType(Cell.CELL_TYPE_STRING);
                    list.add(cell.getStringCellValue());
                }
                lists.add(list);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null)
                    is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return lists;
    }

    /**
     * 创建Excel.xls
     * 
     * @param lists
     *            需要写入xls的数据
     * @param titles
     *            列标题
     * @param name
     *            文件名
     * @return
     * @throws IOException
     */
    public static Workbook creatExcel(List<List<String>> lists,String[] titles, String name) throws IOException {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        String nowDate = df.format(new Date());
        // System.out.println(lists);
        // 创建新的工作薄
        Workbook wb = new HSSFWorkbook();
        // 创建第一个sheet(页),并命名
        Sheet sheet = wb.createSheet(name);
        // 手动设置列宽。第一个参数表示要为第几列设;,第二个参数表示列的宽度,n为列高的像素数。
        for (int i = 0; i < titles.length; i++) {
            sheet.setColumnWidth((short) i, (short) (35.7 * 150));
        }

        // 创建第一行
        Row row = sheet.createRow((short) 0);

        // 创建两种单元格格式
        CellStyle cs = wb.createCellStyle();
        CellStyle cs2 = wb.createCellStyle();

        // 创建两种字体
        Font f = wb.createFont();
        Font f2 = wb.createFont();

        // 创建第一种字体样式(用于列名)
        f.setFontHeightInPoints((short) 10);
        f.setColor(IndexedColors.BLACK.getIndex());
        f.setBoldweight(Font.BOLDWEIGHT_BOLD);

        // 创建第二种字体样式(用于值)
        f2.setFontHeightInPoints((short) 10);
        f2.setColor(IndexedColors.BLACK.getIndex());

        // 设置第一种单元格的样式(用于列名)
        cs.setFont(f);
        cs.setBorderLeft(CellStyle.BORDER_THIN);
        cs.setBorderRight(CellStyle.BORDER_THIN);
        cs.setBorderTop(CellStyle.BORDER_THIN);
        cs.setBorderBottom(CellStyle.BORDER_THIN);
        cs.setAlignment(CellStyle.ALIGN_CENTER);

        // 设置第二种单元格的样式(用于值)
        cs2.setFont(f2);
        cs2.setBorderLeft(CellStyle.BORDER_THIN);
        cs2.setBorderRight(CellStyle.BORDER_THIN);
        cs2.setBorderTop(CellStyle.BORDER_THIN);
        cs2.setBorderBottom(CellStyle.BORDER_THIN);
        cs2.setAlignment(CellStyle.ALIGN_CENTER);
        // 设置列名
        for (int i = 0; i < titles.length; i++) {
            Cell cell = row.createCell(i);
            cell.setCellValue(titles[i]);
            cell.setCellStyle(cs);
        }
        if (lists == null || lists.size() == 0) {
            return wb;
        }
        // 设置每行每列的值
        for (short i = 1; i <= lists.size(); i++) {
            // Row 行,Cell 方格 , Row 和 Cell 都是从0开始计数的
            // 创建一行,在页sheet上
            Row row1 = sheet.createRow((short) i);
            for (short j = 0; j < titles.length; j++) {
                // 在row行上创建一个方格
                Cell cell = row1.createCell(j);
                cell.setCellValue(lists.get(i - 1).get(j));
                cell.setCellStyle(cs2);
            }
             // 输出文件     
            FileOutputStream fileOut = new FileOutputStream("d:/"+nowDate+"处理后的单位名称.xls");     
            wb.write(fileOut);     
            fileOut.close(); 
        }
        return wb;
    }
    
    private static List<List<String>> transposeStr(List<List<String>> resources) {
        List<List<String>> converts = new LinkedList<List<String>>();
        for (List<String> list : resources) {
            for (String str : list) {
                if(StringUtils.isNotBlank(str)&&str.indexOf("&nbsp;")==-1){//剔除空串,同时搜索字符"&nbsp;",若不存在       
                    List<String> newList = new LinkedList<String>();
                    newList.add(str);
                    converts.add(newList);
                }else if(str.indexOf("&nbsp;")!=-1){//搜索字符"&nbsp;",若存在
                    String strSearch=str.replace("&nbsp;","");//剔除子串"&nbsp;"
                    String [] strSearchls=strSearch.split(",");//分割字符串
                    for(String str2 : strSearchls){
                        List<String> newList = new LinkedList<String>();
                        newList.add(str2);
                        converts.add(newList);
                    }
                }
            }
        }
        return converts;
    }
    
    public static void main(String[] args) {
        //输出A在B中的内容
        String pathA = "d:/提案查询(流程).xlsx";//提案查询(流程).xlsx
        String pathB = "d:/单位名称查询.xlsx";//单位名称查询.xlsx
        List<List<String>> listA = readExcel(pathA);
        List<List<String>> listsA=transposeStr(listA);//listsA为去除空串和&nbsp;后的list<string>
//        System.out.println("listsA:"+listsA);
        ArrayList<List<String>> listsNewA=new ArrayList<List<String>>(new HashSet<List<String>>(listsA));//去重
//        System.out.println("listsNewA:"+listsNewA);

        List<List<String>> listB = readExcel(pathB);
//        System.out.println("listB:"+listB);
        listB.retainAll(listsNewA);
//        System.out.println(listB.size()+"处理后"+listB);
        String[] titles={"处理后的单位名称"};
        String name="处理结果";
        try {
            creatExcel(listB,titles,name);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /*
         * for (List<String> list : lists) { for (String strs : list) {
         * System.out.println(strs); } }
         */
    }
}
posted on 2019-02-25 13:49  weakup  阅读(201)  评论(0编辑  收藏  举报