// returns the data from a cell public String getCellData(String sheetName, int colNum, int rowNum) { try { if (rowNum <= 0) return ""; int index = workBook.getSheetIndex(sheetName); if (index == -1) return ""; sheet = workBook.getSheetAt(index); row = sheet.getRow(rowNum - 1); if (row == null) return ""; cell = row.getCell(colNum); if (cell == null) return ""; if (cell.getCellType() == Cell.CELL_TYPE_STRING) return cell.getStringCellValue(); else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC || cell.getCellType() == Cell.CELL_TYPE_FORMULA) { String cellText = String.valueOf(cell.getNumericCellValue()); if (HSSFDateUtil.isCellDateFormatted(cell)) { // format in form of M/D/YY double d = cell.getNumericCellValue(); Calendar cal = Calendar.getInstance(); cal.setTime(HSSFDateUtil.getJavaDate(d)); cellText = (String.valueOf(cal.get(Calendar.YEAR))).substring(2); cellText = cal.get(Calendar.MONTH) + 1 + "/" + cal.get(Calendar.DAY_OF_MONTH) + "/" + cellText; // System.out.println(cellText); } return cellText; } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) return ""; else return String.valueOf(cell.getBooleanCellValue()); } catch (Exception e) { e.printStackTrace(); return "row " + rowNum + " or column " + colNum + " does not exist in xls"; } }
private void processCell(Element tr, XSSFCell cell) { int num = cell.getSheet().getNumMergedRegions(); // System.out.println(cell.getCTCell()); for (int i = 0; i < num; i++) { CellRangeAddress c = cell.getSheet().getMergedRegion(i); System.out.println(c.getFirstColumn()); ; System.out.println(c.getLastColumn()); System.out.println(c.getFirstRow()); System.out.println(c.getLastRow()); System.out.println(); System.out.println(cell.getRowIndex()); System.out.println(cell.getColumnIndex()); System.out.println("\n\n\n"); // System.out.println(cra); } // System.exit(0); Element td = htmlDocumentFacade.createTableCell(); Object value; switch (cell.getCellType()) { case Cell.CELL_TYPE_BLANK: value = "\u00a0"; break; case Cell.CELL_TYPE_NUMERIC: value = cell.getNumericCellValue(); break; case Cell.CELL_TYPE_BOOLEAN: value = cell.getBooleanCellValue(); break; case Cell.CELL_TYPE_FORMULA: value = cell.getNumericCellValue(); break; default: value = cell.getRichStringCellValue(); break; } if (value instanceof XSSFRichTextString) { processCellStyle(td, cell.getCellStyle(), (XSSFRichTextString) value); td.setTextContent(value.toString()); } else { processCellStyle(td, cell.getCellStyle(), null); td.setTextContent(value.toString()); } // System.err.println(value); tr.appendChild(td); }
public static void copyCell(XSSFCell oldCell, XSSFCell newCell) { try { switch (oldCell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getStringCellValue()); break; case XSSFCell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case XSSFCell.CELL_TYPE_BLANK: newCell.setCellType(XSSFCell.CELL_TYPE_BLANK); break; case XSSFCell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case XSSFCell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case XSSFCell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; default: break; } } catch (Exception ex) { System.out.println("Error in writing Cell in reject excel file :: " + ex.getMessage()); ex.printStackTrace(); } }
public static String getCellIntData(int RowNum, int ColNum) throws Exception { try { Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum); String CellData = String.valueOf(Cell.getNumericCellValue()); CellData = CellData.substring(0, CellData.indexOf(".")); return CellData; } catch (Exception e) { // System.out.println("1--->"+e.getMessage()); return ""; } }
/** * セルの値を取得する * * @param row 行データ * @param nColumn 列番号 * @return セルの値 */ public static Object getData(XSSFRow row, int nColumn) { if (row != null) { XSSFCell cell = row.getCell(nColumn); if (cell != null) { if (XSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) { return cell.getNumericCellValue(); } else if (XSSFCell.CELL_TYPE_STRING == cell.getCellType()) { return cell.getStringCellValue(); } } } return null; }
/** * 列方向のセルの値を合算する * * @param sheet 編集対象シート * @param nColumn 行番号 * @param nStartRow 開始列番号 * @param nEndRow 終了列番号 * @return 合算値 */ public static int sumColumn(XSSFSheet sheet, int nColumn, int nStartRow, int nEndRow) { int sum = 0; for (int nIndex = nStartRow; nIndex <= nEndRow; nIndex++) { XSSFRow row = sheet.getRow(nIndex); assert row != null; XSSFCell cell = row.getCell(nColumn); assert cell != null; if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { sum += cell.getNumericCellValue(); } } return sum; }
/** * 获取每个cell的数据 * * @param cell * @return object */ public Object getXssCellData(Object cell) { Object cellData = ""; if (cell != null) { XSSFCell xssCell = (XSSFCell) cell; if (xssCell != null) { switch (xssCell.getCellType()) { case XSSFCell.CELL_TYPE_STRING: cellData = xssCell.getStringCellValue(); if (cellData != null) { cellData = String.valueOf(cellData).trim(); } break; case XSSFCell.CELL_TYPE_NUMERIC: if (DateUtil.isCellDateFormatted(xssCell)) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); cellData = df.format(xssCell.getDateCellValue()); df = null; } else { DecimalFormat df = new DecimalFormat("0"); cellData = df.format(xssCell.getNumericCellValue()); df = null; } break; case XSSFCell.CELL_TYPE_BLANK: cellData = ""; break; case XSSFCell.CELL_TYPE_BOOLEAN: cellData = String.valueOf(xssCell.getBooleanCellValue()); break; case XSSFCell.CELL_TYPE_ERROR: break; default: break; } } xssCell = null; } return cellData; }
/** * @param oldCell * @param newCell * @param styleMap */ public static void copyCell( XSSFCell oldCell, XSSFCell newCell, Map<Integer, XSSFCellStyle> styleMap) { if (styleMap != null) { if (oldCell.getSheet().getWorkbook() == newCell.getSheet().getWorkbook()) { newCell.setCellStyle(oldCell.getCellStyle()); } else { int stHashCode = oldCell.getCellStyle().hashCode(); XSSFCellStyle newCellStyle = styleMap.get(stHashCode); if (newCellStyle == null) { newCellStyle = newCell.getSheet().getWorkbook().createCellStyle(); newCellStyle.cloneStyleFrom(oldCell.getCellStyle()); styleMap.put(stHashCode, newCellStyle); } newCell.setCellStyle(newCellStyle); } } switch (oldCell.getCellType()) { case HSSFCell.CELL_TYPE_STRING: newCell.setCellValue(oldCell.getStringCellValue()); break; case HSSFCell.CELL_TYPE_NUMERIC: newCell.setCellValue(oldCell.getNumericCellValue()); break; case HSSFCell.CELL_TYPE_BLANK: newCell.setCellType(HSSFCell.CELL_TYPE_BLANK); break; case HSSFCell.CELL_TYPE_BOOLEAN: newCell.setCellValue(oldCell.getBooleanCellValue()); break; case HSSFCell.CELL_TYPE_ERROR: newCell.setCellErrorValue(oldCell.getErrorCellValue()); break; case HSSFCell.CELL_TYPE_FORMULA: newCell.setCellFormula(oldCell.getCellFormula()); break; default: break; } }
/** * 读取2007-2013格式 * * @param filePath 文件路径 * @return * @throws java.io.IOException */ @SuppressWarnings("rawtypes") public static List<Map> readExcel2007(String filePath) throws IOException { List<Map> valueList = new ArrayList<Map>(); FileInputStream fis = null; try { fis = new FileInputStream(filePath); XSSFWorkbook xwb = new XSSFWorkbook(fis); // 构造 XSSFWorkbook 对象,strPath 传入文件路径 XSSFSheet sheet = xwb.getSheetAt(0); // 读取第一章表格内容 // 定义 row、cell XSSFRow row; // 循环输出表格中的第一行内容 表头 Map<Integer, String> keys = new HashMap<Integer, String>(); row = sheet.getRow(0); if (row != null) { // System.out.println("j = row.getFirstCellNum()::"+row.getFirstCellNum()); // System.out.println("row.getPhysicalNumberOfCells()::"+row.getPhysicalNumberOfCells()); for (int j = row.getFirstCellNum(); j <= row.getPhysicalNumberOfCells(); j++) { // 通过 row.getCell(j).toString() 获取单元格内容, if (row.getCell(j) != null) { if (!row.getCell(j).toString().isEmpty()) { keys.put(j, row.getCell(j).toString()); } } else { keys.put(j, "K-R1C" + j + "E"); } } } // 循环输出表格中的从第二行开始内容 for (int i = sheet.getFirstRowNum() + 1; i <= sheet.getPhysicalNumberOfRows(); i++) { row = sheet.getRow(i); if (row != null) { boolean isValidRow = false; Map<String, Object> val = new HashMap<String, Object>(); for (int j = row.getFirstCellNum(); j <= row.getPhysicalNumberOfCells(); j++) { XSSFCell cell = row.getCell(j); if (cell != null) { String cellValue = null; if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { if (DateUtil.isCellDateFormatted(cell)) { cellValue = new DataFormatter() .formatRawCellContents( cell.getNumericCellValue(), 0, "yyyy-MM-dd HH:mm:ss"); } else { cellValue = String.valueOf(cell.getNumericCellValue()); } } else { cellValue = cell.toString(); } if (cellValue != null && cellValue.trim().length() <= 0) { cellValue = null; } val.put(keys.get(j), cellValue); if (!isValidRow && cellValue != null && cellValue.trim().length() > 0) { isValidRow = true; } } } // 第I行所有的列数据读取完毕,放入valuelist if (isValidRow) { valueList.add(val); } } } } catch (IOException e) { e.printStackTrace(); } finally { fis.close(); } return valueList; }
public void readSNPs() { boolean done = false; int rownum = 1; while (!done) { XSSFRow row = sheet.getRow(rownum); if (row == null) { done = true; } else { String gene = row.getCell(0).getRichStringCellValue().getString(); String strongestallele = row.getCell(1).getRichStringCellValue().getString(); String snp = row.getCell(2).getRichStringCellValue().getString(); String riskfrequency = null; XSSFCell risk = row.getCell(3); switch (risk.getCellType()) { case Cell.CELL_TYPE_STRING: riskfrequency = risk.getRichStringCellValue().getString(); break; case Cell.CELL_TYPE_NUMERIC: riskfrequency = Double.toString(risk.getNumericCellValue()); break; } int pvalue_mantissa = (int) row.getCell(4).getNumericCellValue(); int pvalue_exponent = (int) row.getCell(5).getNumericCellValue(); float pval_float = (float) (pvalue_mantissa * Math.pow(10, pvalue_exponent)); String pval_num = setpvalnum(pvalue_mantissa, pvalue_exponent); String pvaluetxt; if (row.getCell(6, row.RETURN_BLANK_AS_NULL) != null) { pvaluetxt = row.getCell(6).getRichStringCellValue().getString(); } else { pvaluetxt = null; } Double orpercopynum; if (row.getCell(7, row.RETURN_BLANK_AS_NULL) != null) { orpercopynum = row.getCell(7).getNumericCellValue(); } else { orpercopynum = null; } Double orpercopyrecip; if (row.getCell(8, row.RETURN_BLANK_AS_NULL) != null) { orpercopyrecip = row.getCell(8).getNumericCellValue(); if (orpercopyrecip == 0) { orpercopyrecip = null; } } else { orpercopyrecip = null; } if (orpercopyrecip != null) { orpercopynum = ((100 / orpercopyrecip) / 100); } char ortype = row.getCell(9).getRichStringCellValue().getString().charAt(0); String orpercopyrange; if (row.getCell(10, row.RETURN_BLANK_AS_NULL) != null) { orpercopyrange = row.getCell(10).getRichStringCellValue().getString(); } else { orpercopyrange = null; } String orpercopyunitdescr; if (row.getCell(11, row.RETURN_BLANK_AS_NULL) != null) { orpercopyunitdescr = row.getCell(11).getRichStringCellValue().getString(); } else { orpercopyunitdescr = null; } Double orpercopystderror; if (row.getCell(12, row.RETURN_BLANK_AS_NULL) != null) { orpercopystderror = row.getCell(12).getNumericCellValue(); } else { orpercopystderror = null; } if ((orpercopyrange == null) && (orpercopystderror != null)) { orpercopyrange = setRange(orpercopystderror, orpercopynum); } if ((orpercopyrecip != null) && (orpercopyrange != null) && (orpercopystderror == null)) { orpercopyrange = reverseCI(orpercopyrange); } String snptype = row.getCell(13).getRichStringCellValue().getString(); SNPentry thisSNP = new SNPentry( gene, strongestallele, snp, riskfrequency, pvalue_mantissa, pvalue_exponent, pval_float, pval_num, pvaluetxt, orpercopynum, orpercopyrecip, ortype, orpercopyrange, orpercopyunitdescr, orpercopystderror, snptype); allSNPs.add(thisSNP); } rownum++; } }
/** 导入Excel表格 */ @SuppressWarnings("unused") public String intoDB() throws IOException { String uploadPath = ServletActionContext.getServletContext().getRealPath("/upload"); isImpSuccess = false; // 判断数据导入是否成功 errCount = 0; // 判断导入数据模板是否对应 // 基于myFile创建一个文件输入流 InputStream is = new FileInputStream(myFile); // 设置目标文件 File toFile = new File(uploadPath, this.getMyFileFileName()); String caseName = null; // 活动名称 String caseDesc = null; // 活动描述 Timestamp caseSt = null; // 活动开始时间 Timestamp caseEt = null; // 活动结束时间 String sysUserId = null; // 创建/修改用户ID Timestamp sysDt = null; // 修改时间 Integer status = null; // 活动状态 String caseCode = null; // 活动编码 Double ratioNew = null; // 新款占比 Integer num = null; // 参与款数 Date date = new Date(); // 创建一个时间对象,获取到当前的时间 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 设置时间显示格式 String str = sdf.format(date); // 将当前时间格式化为需要的类型 sysDt = Timestamp.valueOf(str); sysUserId = ParaCasePAction.getCurrentUserName(); /** 2007版的读取方法 */ int k = 0; int flag = 0; // 指示指针所访问的位置 if (myFile != null) { try { Workbook workbook = WorkbookFactory.create(toFile); intolist.clear(); // Workbook workbook = new XSSFWorkbook(is);//初始化workbook对象 for (int numSheets = 0; numSheets < workbook.getNumberOfSheets(); numSheets++) { // 读取每一个sheet if (null != workbook.getSheetAt(numSheets)) { XSSFSheet aSheet = (XSSFSheet) workbook.getSheetAt(numSheets); // 定义Sheet对象 for (int rowNumOfSheet = 1; rowNumOfSheet <= aSheet.getLastRowNum(); rowNumOfSheet++) { // 进入当前sheet的行的循环 if (null != aSheet.getRow(rowNumOfSheet)) { XSSFRow aRow = aSheet.getRow(rowNumOfSheet); // 定义行,并赋值 for (int cellNumOfRow = 0; cellNumOfRow <= aRow.getLastCellNum(); cellNumOfRow++) { // 读取rowNumOfSheet值所对应行的数据 XSSFCell xCell = aRow.getCell(cellNumOfRow); // 获得行的列数 // //获得列值 // System.out.println("type="+xCell.getCellType()); if (null != aRow.getCell(cellNumOfRow)) { // 如果rowNumOfSheet的值为0,则读取表头,判断excel的格式和预定格式是否相符 if (rowNumOfSheet == 1) { if (xCell.getCellType() == XSSFCell.CELL_TYPE_STRING) { /** * 一下根据从Excel的各列命名是否符合要求:如下面匹配: 活动名称,活动描述,活动开始时间, 活动结束时间,操作用户, * 修改时间,活动状态,活动编码,新款占比 ,参与款数,备注开始时间,备注结束时间 */ if (cellNumOfRow == 0) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动名称")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 1) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动描述")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 2) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动开始时间")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 3) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动结束时间")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 4) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动状态")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 5) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("活动编码")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 6) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("新款占比")) { flag++; } else { errCount++; } } else if (cellNumOfRow == 7) { if (xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim() .equals("参与款数")) { flag++; } else { errCount++; } } } } else { // rowNumOfSheet != 0 即开始打印内容 // 获取excel中每列的值,并赋予相应的变量,如下的赋值的ID,name,sex, // Dormitory,sept; if (xCell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) { // 为数值型 System.out.println( "===============进入XSSFCell .CELL_TYPE_NUMERIC模块============"); switch (cellNumOfRow) { case 2: Date St = (Date) xCell.getDateCellValue(); // 对日期处理 caseSt = new Timestamp(St.getTime()); break; case 3: Date Et = (Date) xCell.getDateCellValue(); // 对日期处理 caseEt = new Timestamp(Et.getTime()); break; case 4: status = (int) xCell.getNumericCellValue(); break; case 6: ratioNew = xCell.getNumericCellValue(); break; case 7: num = (int) xCell.getNumericCellValue(); break; } } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_STRING) { // 为字符串型 System.out.println( "===============进入XSSFCell .CELL_TYPE_STRING模块============"); switch (cellNumOfRow) { case 0: caseName = xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim(); break; case 1: caseDesc = xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim(); break; case 5: caseCode = xCell .getStringCellValue() .replace('\t', ' ') .replace('\n', ' ') .replace('\r', ' ') .trim(); break; } } else if (xCell.getCellType() == XSSFCell.CELL_TYPE_BLANK) { System.out.println( "提示:在Sheet" + (numSheets + 1) + "中的第" + (rowNumOfSheet + 1) + "行的第" + (cellNumOfRow + 1) + "列的值为空,请查看核对是否符合约定要求"); switch (cellNumOfRow) { case 0: caseName = ""; break; case 1: caseDesc = ""; break; case 2: caseSt = null; break; case 3: caseEt = null; break; case 4: status = null; break; case 5: caseCode = ""; break; } } } } } // 判断各个元素被赋值,如果放入数据库,就直接使用数据的插入的函数就可以了。 if (aRow.getRowNum() > 1) { ParaDt pd = new ParaDt(); pd.setCaseName(caseName); pd.setCaseDesc(caseDesc); pd.setCaseEt(caseEt); pd.setCaseSt(caseSt); pd.setSysUserId(sysUserId); pd.setSysDt(sysDt); pd.setStatus(status); pd.setCaseCode(caseCode); pd.setRatioNew(ratioNew); pd.setNum(num); pd.setCaseCode(caseCode); intolist.add(pd); } } // 获得一行,即读取每一行 } // 读取每一个sheet } } refreshList = "paraCaseDtgetParaDtAll"; titleName = "营销活动实例"; if (errCount > 0) { msg = "导入数据与模板不符,导入失败!"; } else { // 调用sever方法 isImpSuccess = paraDtService.addOneBoat(intolist, 500); if (isImpSuccess) { msg = "营销活动实例导入成功!"; } else { msg = "营销活动实例导入失败!"; } } } catch (Exception e) { e.printStackTrace(); } } return "importExcel"; }