1. 程式人生 > >王昕的 java 下Excel的匯入和匯出,資料校驗

王昕的 java 下Excel的匯入和匯出,資料校驗

複製程式碼
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.poifs.filesystem.POIFSFileSystem; import org.apache.struts.upload.FormFile; public class POIImport { // 匯入並驗證檔案File_Import.xls public static void main(String[] args) {
// 用Struts匯入檔案: // FormFile formFile = batchChangeAGForm.getXlsfile(); // // if (0 == formFile.getFileSize()) { // this.setPromptMessage(request, "選擇的檔案有誤!"); // return mapping.findForward("batchChangeAGImport"); // } // InputStream is = formFile.getInputStream();
// 直接讀取檔案: String filePath = "D:\\File_Import.xls"; File file = new File(filePath); InputStream is; HSSFSheet sheetMain; try { is = new FileInputStream(file); POIFSFileSystem fs = new POIFSFileSystem(is); HSSFWorkbook wb = new HSSFWorkbook(fs); // 讀取第一個Sheet sheetMain = wb.getSheetAt(0); is.close(); // 總共的行數 int rowLens = sheetMain.getLastRowNum(); int colLens = 8; int errCnt = 0; HSSFRow row = null; HSSFCell cell = null; String content = ""; for (int rowCount = 1; rowCount <= rowLens; rowCount++) { System.out.println("讀取行:" + rowCount); row = sheetMain.getRow(rowCount); if (row != null) { for (int colCount = 0; colCount < colLens; colCount++) { System.out.print("行 :" + rowCount + ";列 :" + colCount + "的內容:"); cell = row.getCell((short) colCount); content = getCellValue(cell).trim(); if (content == "") { System.out.println("### 發現空異常 ###"); } else { System.out.println(content); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static String getCellValue(HSSFCell cell) { if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_BLANK: return ""; case HSSFCell.CELL_TYPE_NUMERIC: String strValue = String.valueOf(cell.getNumericCellValue()); if (strValue != null && strValue.indexOf(".") != -1 && strValue.indexOf("E") != -1) { try { return new DecimalFormat().parse(strValue).toString(); } catch (ParseException e) { e.printStackTrace(); } } else { if (strValue.endsWith(".0")) { return strValue.substring(0, strValue.indexOf(".0")); } else { return strValue; } } case HSSFCell.CELL_TYPE_STRING: return (cell.getStringCellValue() + "").trim(); case HSSFCell.CELL_TYPE_FORMULA: return (cell.getCellFormula() + "").trim(); case HSSFCell.CELL_TYPE_BOOLEAN: return cell.getBooleanCellValue() + ""; case HSSFCell.CELL_TYPE_ERROR: return cell.getErrorCellValue() + ""; } } return ""; } }
複製程式碼