poi读取excel工具类

package com.zhwg.core.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Vector;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
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.DateUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.struts2.ServletActionContext;

import com.zhwg.core.dao.utile.excel.ExcelObject;

public class UploadSave {

/**
 * 
 * @param file
 * @param fileName
 * @param path  上传的绝对路径   http://localhost:8080/cnr/upload/image
 * @param savePath 上传相对路径 /upload/image
 * @return
 */
public String saveFile(File[] file,String[] fileName,String path,String savePath){
	try{
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        if (file != null) {
        	int len = file.length;
        	int position = 0;
			String extension = "";	//后缀名
        	String newfileName;		//新文件名
        	String url;				//上传文件路径
        	String reStr = "";		//文件存放目录-return
        	String url2 = "";		//数据库存储路径
        	String dp = "/"+DateTime.getCurDateStr("yyyy")+"/"+DateTime.getCurDateStr("yyyyMM")+"/"+DateTime.getCurDateStr("yyyyMMdd");
        	url = path + dp;
        	url2 = savePath + dp;
   		 	
            File savedir = new File(url);//按url成本地目录
            if(!savedir.getParentFile().exists()){//没有就创建一个目录
            	savedir.getParentFile().mkdirs();
            }
            
            for(int i=0;i<len;i++){
            	position = fileName[i].lastIndexOf(".");
				extension = fileName[i].substring(position);
				newfileName = newfileName(extension);
				
                File savefile = new File(savedir, newfileName);
                FileUtils.copyFile(file[i], savefile);//保存文件到本地

                if(i+1==len){
                	reStr = reStr + url2 + "/" + newfileName;
        		}else{
        			reStr = reStr + url2 + "/" + newfileName + ",";
        		}
               /*
                //删除文件
                File file = new File(path + "\\" + newfileName);
				if (file.isFile()) { // 判断是否为文件
					file.delete();
				}*/
            }
            return reStr;
        }
	}catch(Exception e){
		return null;
	}
	return null;
}

public String saveFile(File file,String fileName,String path,String savePath){
	try{
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        if (file != null) {
			String extension = "";	//后缀名
        	String newfileName;		//新文件名
        	String url;				//上传文件路径
        	String reStr = "";		//文件存放目录-return
        	String url2 = "";		//数据库存储路径
        	
        	String dp = "/"+DateTime.getCurDateStr("yyyy")+"/"+DateTime.getCurDateStr("yyyyMM")+"/"+DateTime.getCurDateStr("yyyyMMdd");
        	url = path + dp;
        	url2 = savePath + dp;
   		 	
            File savedir = new File(url);//按url成本地目录
            if(!savedir.getParentFile().exists()){//没有就创建一个目录
            	savedir.getParentFile().mkdirs();
            }
            
            int position = fileName.lastIndexOf(".");
			extension = fileName.substring(position);
			newfileName = newfileName(extension);
			
            File savefile = new File(savedir, newfileName);
            FileUtils.copyFile(file, savefile);//保存文件到本地

        	reStr = reStr + url2 + "/" + newfileName;
           /*
            //删除文件
            File file = new File(path + "\\" + newfileName);
			if (file.isFile()) { // 判断是否为文件
				file.delete();
			}*/
            return reStr;
        }
	}catch(Exception e){
		return null;
	}
	return null;
}

public void saveExcel(XSSFWorkbook workBook, String fileName, String path ) {
	if (workBook != null) {
		try {
			createDir(path);
			OutputStream out = new FileOutputStream(path+fileName);
			workBook.write(out);
			if (out != null) {
				out.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
}

public boolean createDir(String destDirName){
	File dir = new File(destDirName);
	if (dir.exists()) {// 判断目录是否存在
		System.out.println("创建目录失败,目标目录已存在!");
		return false;
	}
	if (!destDirName.endsWith(File.separator)) {// 结尾是否以"/"结束
		destDirName = destDirName + File.separator;
	}
	if (dir.mkdirs()) {// 创建目标目录
		System.out.println("创建目录成功!" + destDirName);
		return true;
	} else {
		System.out.println("创建目录失败!");
		return false;
	}
}

public String getOldFileName(String[] fileName){
	try{
		ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
        if (fileName != null) {
        	int len = fileName.length;
        	String reStr = "";		//文件存放目录-return
            
            for(int i=0;i<len;i++){
                if(i+1==len){
                	reStr = reStr + fileName[i];
        		}else{
        			reStr = reStr + fileName[i] + ",";
        		}
            }
            return reStr;
        }
	}catch(Exception e){
		return null;
	}
	return null;
    
}


/**
 * 上传Excel文件数据封装
 * @param excelObjects 封装后的数据
 * @param msg  返回 验证错误信息
 * @param file
 * @param fileName
 * @param path  上传的绝对路径   http://localhost:8080/cnr/upload/image
 * @param startRowIndex 从第几行开始读取数据(<=0从第0行读起)
 * @param cellNumber  读取多少列(<=0读取全部列)
 * @throws IOException
 */
public String uploadExcel(Vector<ExcelObject> excelObjects,StringBuilder msg,File file,
		String fileName,String path,int startRowIndex,int cellNumber){
	int position = 0;
	String extension = "";//后缀名
	String reStr = "";		//文件存放目录-return
	try {
		if(null !=file) {
			InputStream inputStream = new FileInputStream(file);
			Workbook workbook  = null;
			Sheet sheet = null;
			Row row = null;
			Cell cell = null;
			position = fileName.lastIndexOf(".");
			extension = fileName.substring(position);
			SimpleDateFormat scrq = new SimpleDateFormat("yyyy-MM-dd");//上传日期
			//DecimalFormat df = new DecimalFormat("0.00"); 
			if(".xlsx".equals(extension)){//excel-2007
				workbook = new XSSFWorkbook(inputStream);
				//sheet = workbook.getSheetAt(0);
			}else if(".xls".equals(extension)) {//excel97-2003
				workbook = new HSSFWorkbook(inputStream);
				//sheet = workbook.getSheetAt(0);
			}else {
	            throw new Exception("上传的文件非excel文件");
	        }
			int sheetNum = workbook.getNumberOfSheets();//总sheet个数
			for(int n=0;n<sheetNum;n++){
				sheet = workbook.getSheetAt(n);	
				if(sheet != null){
					ExcelObject excelObject = new ExcelObject();
					/**
					 * 获取工作表的名称
					 */
					excelObject.setSheetName(sheet.getSheetName());
					//System.out.println("sheet.getSheetName()="+sheet.getSheetName());
					//System.out.println("workbook.getSheetName(n)="+workbook.getSheetName(n));
					//Vector<String> title = new Vector<String>();
					
					//--表头信息  startY:excel有效行数   endX:excel有效列数
					int startY = sheet.getPhysicalNumberOfRows();
					Vector<ArrayList<String>> excelData = new Vector<ArrayList<String>>(startY);
					if (startRowIndex < 0) {
						startRowIndex = 0;
					}
					//--表体信息
					for (int i = startRowIndex ; i < startY; i++) {
						row = sheet.getRow(i);
						if (row == null) {
							msg.append("第" + (i + 1) + "行没有数据!");
							//throw new Exception("验证错误:第" + (i + 1) + "行 没有数据!");
						}else {
							int endX = row.getPhysicalNumberOfCells();
							if(cellNumber <= 0) {
								cellNumber = endX;
							}
							if(cellNumber > endX){
								//cellNumber = endX;
							}
							ArrayList<String> rowData = new ArrayList<String>();
							for (int j = 0 ; j < cellNumber; j++) {   //--startX:excel开始读取的单元格
								cell = row.getCell(j);
								if (cell == null) {
									msg.append("第" + (i + 1) + "行,第" + (j + 1) + "列没有数据!");
									rowData.add("");
									//throw new Exception("验证错误:第" + (i + 1) + "行 第" + (j + 1) + " 列没有数据!");
								} else{
									if (Cell.CELL_TYPE_BLANK == cell.getCellType()) {//为空
										msg.append("第" + (i + 1) + "行,第" + (j + 1) + "列不存在!");
										rowData.add("");
										//throw new Exception("验证错误:第" + (i + 1) + "行 第" + (j + 1) + " 列不存在!");
									}else if(Cell.CELL_TYPE_NUMERIC == cell.getCellType() || Cell.CELL_TYPE_FORMULA == cell.getCellType()){//数字
										if(isCellDateFormatted(cell)){
											rowData.add(scrq.format(cell.getDateCellValue()));//日期
										}else{
											
											cell.setCellType(Cell.CELL_TYPE_STRING);
											//System.out.println(cell.toString());
											//rowData.add(df.format(cell.getNumericCellValue()));
											rowData.add(cell.toString());
										}
									}else if(Cell.CELL_TYPE_STRING == cell.getCellType()){//字符
										if(StringUtils.isBlank(cell.getStringCellValue())){
											msg.append("第" + (i + 1) + "行,第" + (j + 1) + "列空格!");
										}
										rowData.add(cell.getStringCellValue());
									}else{
										msg.append("第" + (i + 1) + "行,第" + (j + 1) + "列空格!");
										rowData.add("");
									}
								}
							}
							excelData.add(rowData);
						}
					}
					//excelObject.setTitle(title);
					excelObject.setExcelData(excelData);
					excelObjects.add(excelObject);
				}
			}
			String url = path + "\\" + DateTime.getCurrentDate_YYYYMM();
			
			File savedir = new File(url);//按月生成本地目录
			if(!savedir.getParentFile().exists()){//没有就创建一个目录
				savedir.getParentFile().mkdirs();
			}
			String newFileName = newfileName(extension);
			File savefile = new File(savedir,  newFileName);
			FileUtils.copyFile(file, savefile);//保存文件到本地
			
			reStr = url + "/" + newFileName;
		}
	} catch (Exception e) {
		e.printStackTrace();
		msg.append("读取解析文件错误,请检查上传文件!");
	}
	return reStr;
}

/** 
 * 重新命名
 * @param extension
 * @return
 */
public static String newfileName(String extension){
	String name = Long.toString(new Date().getTime()) + (int)(Math.random()*10000) + extension;
	return name;
}

/**
 * 由于日期在Excel内是以double值存储的,所以一个cell如果是这种格式,我们可以推断它是一个日期。 
 * 是日期返回true 反之返回false
 */  
public static boolean isCellDateFormatted(Cell cell) {  
    if(cell == null){
    	return false;
    }  
    try{
    	boolean bDate = false;
		double d = cell.getNumericCellValue();
		if (DateUtil.isValidExcelDate(d)) {
			CellStyle style = cell.getCellStyle();
			if (style == null) {
				return false;
			}
			int i = style.getDataFormat();
			String f = style.getDataFormatString();
			bDate = DateUtil.isADateFormat(i, f);
		}
		return bDate;
	} catch (Exception e) {
		return false;
	}
} 

/**
 * 根据cell类型自动获取数据
 * 
 * @param cell
 *            单元格对象
 * @return 获取到的数据
 */
@SuppressWarnings("unused")
private static String getValueFromCell(Cell cell) {
	if (cell != null) {
		switch (cell.getCellType()) {
		case HSSFCell.CELL_TYPE_BLANK:
			return "";
		case HSSFCell.CELL_TYPE_BOOLEAN:
			return BooleanUtils.toStringTrueFalse(cell.getBooleanCellValue());
		case HSSFCell.CELL_TYPE_NUMERIC:
			java.text.DecimalFormat formatter = new java.text.DecimalFormat("########");
			String str = formatter.format(cell.getNumericCellValue());
			return str;
		case HSSFCell.CELL_TYPE_ERROR:
			return "#ERROR:" + cell.getErrorCellValue();
		case HSSFCell.CELL_TYPE_STRING:
			return String.valueOf(cell.getRichStringCellValue());
		default:
			return String.valueOf(cell.getRichStringCellValue());
		}
	} else {
		return "";
	}
}

/**
 * 弃用
 * @param file
 * @param fileName
 * @param path
 * @throws IOException
 */
public void uploadExcel1(File file,String fileName,String path) throws IOException{
	try {
		int position = 0;
		String extension = "";//后缀名
		StringBuilder msg = new StringBuilder("");//验证错误信息
		Vector<ExcelObject> excelObjects = new Vector<ExcelObject>();
		
		if(null !=file) {
			InputStream inputStream = new FileInputStream(file);
			Workbook workbook  = null;
			Sheet sheet = null;
			Row row = null;
			Cell cell = null;
			position = fileName.lastIndexOf(".");
			extension = fileName.substring(position);
			
			if(".xlsx".equals(extension)){//excel-2007
				workbook = new XSSFWorkbook(inputStream);
				sheet = workbook.getSheetAt(0);	
			 } else {//excel97-2003
				 workbook = new HSSFWorkbook(inputStream);
				 sheet = workbook.getSheetAt(0);
			 }
			if(sheet != null){
				ExcelObject excelObject = new ExcelObject();
				/**
				 * 获取工作表的名称
				 */
				excelObject.setSheetName(workbook.getSheetName(0));
				Vector<String> title = new Vector<String>();
				
				 //--表头信息  startY:excel有效行数   endX:excel有效列数
				int startY = sheet.getPhysicalNumberOfRows();
				Vector<ArrayList<String>> excelData = new Vector<ArrayList<String>>(startY);
				 //--表体信息
				 for (int i = 0 ; i < startY; i++) {
					 row = sheet.getRow(i);
					 if (row == null) {
						 msg.append("第" + (i + 1) + "行没有数据!");
						 //throw new Exception("验证错误:第" + (i + 1) + "行 没有数据!");
					 }else {
						 int endX = row.getPhysicalNumberOfCells();
						 ArrayList<String> rowData = new ArrayList<String>();
						 for (int j = 0 ; j < endX; j++) {   //--startX:excel开始读取的单元格
							 cell = row.getCell(j);
							 if (cell == null) {
								 msg.append("第" + (i + 1) + "行,第" + (j + 1) + " 列没有数据!");
								 //throw new Exception("验证错误:第" + (i + 1) + "行 第" + (j + 1) + " 列没有数据!");
							 } else{
								 if (Cell.CELL_TYPE_BLANK == cell.getCellType()) {//为空
									 msg.append("第" + (i + 1) + "行,第" + (j + 1) + " 列不存在!");
									 //throw new Exception("验证错误:第" + (i + 1) + "行 第" + (j + 1) + " 列不存在!");
								 }else if(Cell.CELL_TYPE_NUMERIC == cell.getCellType() || Cell.CELL_TYPE_FORMULA == cell.getCellType()){//数字
									 if(j==0){
										 title.add(String.valueOf(cell.getNumericCellValue()));
									 }else{
										 rowData.add(String.valueOf(cell.getNumericCellValue()));
									 }
									 //System.out.println(cell.getNumericCellValue()); 
								 }else if(Cell.CELL_TYPE_STRING == cell.getCellType()){//字符
									 if(j==0){
										 title.add(cell.getStringCellValue());
									 }else{
										 rowData.add(cell.getStringCellValue());
									 }
									 //System.out.println(cell.getStringCellValue()); 
								 }else{
									 msg.append("第" + (i + 1) + "行,第" + (j + 1) + " 列空格!");
								 }
							 }
						 }
						 excelData.add(rowData);
					 }
				 }
				 excelObject.setExcelData(excelData);
				 excelObjects.add(excelObject);

				File savedir = new File(path);//按月生成本地目录
				if(!savedir.getParentFile().exists()){//没有就创建一个目录
	            	savedir.getParentFile().mkdirs();
	            }
				
				File savefile = new File(savedir, "test"+extension);
	            FileUtils.copyFile(file, savefile);//保存文件到本地
			}
			
            
		}
	} catch (Exception e) {
		
	}
}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值