Excel读写工具类


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.poi.openxml4j.exceptions.InvalidFormatException;
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.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile; 

/** 
 * excel读写工具类 
 * 2016年8月21日 
 */  
public class POIUtil {  
    private static Logger logger  = Logger.getLogger(POIUtil.class);  
    private final static String xls = "xls";  
    private final static String xlsx = "xlsx";  
      
    /** 
     * 读入excel文件,解析后返回 
     * @param inputStream 
     * @throws IOException  
     */  
    public Map<String,List<String[]>> readExcel(InputStream inputStream) throws IOException{  
        //获得Workbook工作薄对象
        Workbook workbook = null;
		try {
			workbook = WorkbookFactory.create(inputStream);
		} catch (EncryptedDocumentException e) {
			e.printStackTrace();
		} catch (InvalidFormatException e) {
			e.printStackTrace();
		}
        //创建返回对象,把每行中的值作为一个数组,所有行作为一个集合返回
		Map<String,List<String[]>> excelMap = new HashMap<>();
          
        if(workbook != null){  
            for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){
            	List<String[]> list = new ArrayList<String[]>();
            	if(sheetNum == 2){
            		break;
            	}
                //获得当前sheet工作表  
                Sheet sheet = workbook.getSheetAt(sheetNum);  
                if(sheet == null){  
                    continue;  
                }  
                //获得当前sheet的开始行  
                int firstRowNum  = sheet.getFirstRowNum();  
                //获得当前sheet的结束行  
                int lastRowNum = sheet.getLastRowNum();  
                
                //获得当前行的开始列  
                int firstCellNum = 0;
                //获得当前行的列数  
                int lastCellNum = 0;
                //循环所有行  
                for(int rowNum = firstRowNum;rowNum <= lastRowNum;rowNum++){  
                    //获得当前行  
                    Row row = sheet.getRow(rowNum);  
                    if(row == null){  
                        continue;  
                    }  
                    
                    if(0 == rowNum){
                        firstCellNum = row.getFirstCellNum();  
                        lastCellNum = row.getLastCellNum();  
                    }
                    
                    String[] cells = new String[lastCellNum];  
                    //循环当前行  
                    for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){  
                        Cell cell = row.getCell(cellNum);  
                        cells[cellNum] = getCellValue(cell);  
                    }  
                    list.add(cells);  
                }
                if(sheetNum == 0){
                	excelMap.put("case", list);
                }else if(sheetNum == 1){
                	excelMap.put("party", list);
                }
            }  
            workbook.close();
        }  
        return excelMap;  
    }  
    public static void checkFile(MultipartFile file) throws IOException{  
        //判断文件是否存在  
        if(null == file){  
            logger.error("文件不存在!");  
            throw new FileNotFoundException("文件不存在!");  
        }  
        //获得文件名  
        String fileName = file.getOriginalFilename();  
        //判断文件是否是excel文件  
        if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){  
            logger.error(fileName + "不是excel文件");  
            throw new IOException(fileName + "不是excel文件");  
        }  
    }  
    public static Workbook getWorkBook(MultipartFile file) {  
        //获得文件名  
        String fileName = file.getOriginalFilename();  
        //创建Workbook工作薄对象,表示整个excel  
        Workbook workbook = null;  
        try {  
            //获取excel文件的io流  
            InputStream is = file.getInputStream();  
            //根据文件后缀名不同(xls和xlsx)获得不同的Workbook实现类对象  
            if(fileName.endsWith(xls)){  
                //2003  
                workbook = new HSSFWorkbook(is);  
            }else if(fileName.endsWith(xlsx)){  
                //2007  
                workbook = new XSSFWorkbook(is);  
            }  
        } catch (IOException e) {  
            logger.info(e.getMessage());  
        }  
        return workbook;  
    }  
    public static String getCellValue(Cell cell){  
        String cellValue = "";  
        if(cell == null){  
            return cellValue;  
        }  
        //把数字当成String来读,避免出现1读成1.0的情况  
        if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){  
            cell.setCellType(Cell.CELL_TYPE_STRING);  
        }  
        //判断数据的类型  
        switch (cell.getCellType()){  
            case Cell.CELL_TYPE_NUMERIC: //数字  
                cellValue = String.valueOf(cell.getNumericCellValue());  
                break;  
            case Cell.CELL_TYPE_STRING: //字符串  
                cellValue = String.valueOf(cell.getStringCellValue());  
                break;  
            case Cell.CELL_TYPE_BOOLEAN: //Boolean  
                cellValue = String.valueOf(cell.getBooleanCellValue());  
                break;  
            case Cell.CELL_TYPE_FORMULA: //公式  
                cellValue = String.valueOf(cell.getCellFormula());  
                break;  
            case Cell.CELL_TYPE_BLANK: //空值   
                cellValue = "";  
                break;  
            case Cell.CELL_TYPE_ERROR: //故障  
                cellValue = "非法字符";  
                break;  
            default:  
                cellValue = "未知类型";  
                break;  
        }  
        return cellValue;  
    }
    
    /**
     * 数据导出至excel
     * @param path
     * @param title
     * @param sheetName
     * @param headers
     * @param datas
     */
	public static String expExs(String path,String title,String sheetName,List<String> headers,List<List<String>> datas){
        try { 
            if(sheetName== null || "".equals(sheetName)){ sheetName = "sheet"; }
            
            //判断路径是否存在
            boolean isExist = new File(path).exists();
            if(!isExist){
                HSSFWorkbook workbook = new HSSFWorkbook();
                HSSFSheet sheet = workbook.createSheet(sheetName);
                  
                FileOutputStream out = new FileOutputStream(new File(path));
                workbook.write(out);
                out.flush();
                out.close();
            }
            FileInputStream file = new FileInputStream(new File(path));
            HSSFWorkbook workbook = new HSSFWorkbook(file);
              
            HSSFSheet sheet = null;
            if(!isExist){
                sheet = workbook.getSheetAt(0);
            }else{
                if(workbook.getSheet(sheetName) == null){
                    sheet = workbook.createSheet(sheetName); //+workbook.getNumberOfSheets()
                }else{
                    System.out.println("文件:["+path+"] ["+sheetName+"] 已经存在...");
                    return "error";
                }
            }
            
            HSSFRow row;
            HSSFCell cell;
              
            // 设置这些样式
            HSSFFont font = workbook.createFont();
            font.setFontName("黑体");//字体
            font.setFontHeightInPoints((short) 14);//字号
              
            HSSFCellStyle cellStyle= workbook.createCellStyle(); //设置单元格样式
            cellStyle.setFillForegroundColor(HSSFColor.PALE_BLUE.index);
            cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setFont(font);
            
            //产生表格大标题
            HSSFRow firstHeaderRow = sheet.createRow(0);
            sheet.addMergedRegion(new CellRangeAddress(0,0,0,headers.size()-1)); 
            HSSFCell yearCell = firstHeaderRow.createCell(0);
            yearCell.setCellValue(title);
            yearCell.setCellStyle(cellStyle);
              
            //产生表格标题行       
            row = sheet.createRow(1);
            row.setHeightInPoints(20);
            for (int i = 0; i < headers.size(); i++) { 
                HSSFRichTextString text = new HSSFRichTextString(headers.get(i).toString());  
                cell = row.createCell(i);
                cell.setCellValue(text); 
                cell.setCellStyle(cellStyle);
            }  
              
            font = workbook.createFont();
            font.setFontName("黑体");//字体
            font.setFontHeightInPoints((short) 12);//字号
            
            cellStyle= workbook.createCellStyle(); 
            cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
            cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
            cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
            cellStyle.setDataFormat((short)0x31);//设置显示格式,避免点击后变成科学计数法了
            cellStyle.setFont(font);
            
            List<String> rowItem;
            //遍历集合数据,产生数据行  
            for (int i = 0; i < datas.size(); i++) { 
                row=sheet.createRow((i+2));
                row.setHeightInPoints(20);
                rowItem = datas.get(i);
  
                for(int j = 0;j < rowItem.size(); j++) {
                     cell = row.createCell(j);
                     cell.setCellStyle(cellStyle);
  
                     cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                     if(rowItem.get(j) != null) {
                         cell.setCellValue(new HSSFRichTextString(rowItem.get(j)));
                     }else{
                         cell.setCellValue(new HSSFRichTextString(""));     
                    }
                }
                
                //合计
                if(i == datas.size() - 1){
                    row = sheet.createRow(i + 2);
                    sheet.addMergedRegion(new CellRangeAddress(i+2,i+2,0,1));
                    cell = row.createCell(0);
                    cell.setCellValue("合计");
                    cell.setCellStyle(cellStyle);
                    for(int k = 0;k < rowItem.size(); k++){
                    	if(k == 0 || k == 1){
                    		continue;
                    	}
                    	cell = row.createCell(k);
                        cell.setCellStyle(cellStyle);
                        cell.setCellType(HSSFCell.CELL_TYPE_STRING);
                        
                        if(rowItem.get(k) != null) {
                            cell.setCellValue(new HSSFRichTextString(rowItem.get(k)));
                        }else{
                            cell.setCellValue(new HSSFRichTextString(""));     
                       }
                    }
                }
            }
              
            for (int i = 0; i < headers.size(); i++) { 
                //sheet.autoSizeColumn((short)i,true);
            	int cellLength = headers.get(i).getBytes().length;
            	if(i == 1){
            		sheet.setColumnWidth(i,cellLength*6*256);
            	}else{
            		sheet.setColumnWidth(i,cellLength*256);
            	}
            }
              
            FileOutputStream out = new FileOutputStream(new File(path));
            workbook.write(out);
            out.flush();
            out.close();
              
        } catch (Exception e) {  
        	e.printStackTrace();
            return "error";
        } 
        System.out.println("文件:["+path+"] ["+sheetName+"] 创建成功...");
        return "success";
    }
    
}
  

猜你喜欢

转载自blog.csdn.net/sheng_xinjun/article/details/81201946