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) { } }
}