/**
   * Import the model according to reversed dependency order among model objects: book, sheet,
   * defined name, cells, chart, pictures, validation.
   */
  @Override
  public SBook imports(InputStream is, String bookName) throws IOException {

    // clear cache for reuse
    importedStyle.clear();
    importedFont.clear();

    workbook = createPoiBook(is);
    book = SBooks.createBook(bookName);
    //		book.setDefaultCellStyle(importCellStyle(workbook.getCellStyleAt((short) 0), false));
    // //ZSS-780
    // ZSS-854
    importDefaultCellStyles();
    importNamedStyles();
    // ZSS-1140
    importExtraStyles();
    setBookType(book);

    // ZSS-715: Enforce internal Locale.US Locale so formula is in consistent internal format
    Locale old = Locales.setThreadLocal(Locale.US);
    SBookSeries bookSeries = book.getBookSeries();
    boolean isCacheClean = bookSeries.isAutoFormulaCacheClean();
    try {
      bookSeries.setAutoFormulaCacheClean(false); // disable it to avoid
      // unnecessary clean up
      // during importing

      importExternalBookLinks();
      int numberOfSheet = workbook.getNumberOfSheets();
      for (int i = 0; i < numberOfSheet; i++) {
        Sheet poiSheet = workbook.getSheetAt(i);
        importSheet(poiSheet, i);
        SSheet sheet = book.getSheet(i);
        importTables(poiSheet, sheet); // ZSS-855, ZSS-1011
      }
      importNamedRange();
      for (int i = 0; i < numberOfSheet; i++) {
        SSheet sheet = book.getSheet(i);
        Sheet poiSheet = workbook.getSheetAt(i);
        for (Row poiRow : poiSheet) {
          importRow(poiRow, sheet);
        }
        importColumn(poiSheet, sheet);
        importMergedRegions(poiSheet, sheet);
        importDrawings(poiSheet, sheet);
        importValidation(poiSheet, sheet);
        importAutoFilter(poiSheet, sheet);
        importSheetProtection(poiSheet, sheet); // ZSS-576
      }
    } finally {
      book.getBookSeries().setAutoFormulaCacheClean(isCacheClean);
      Locales.setThreadLocal(old);
    }

    return book;
  }
Example #2
0
 /**
  * 导出对象到Excel,不是基于模板的,直接新建一个Excel完成导出,基于流
  *
  * @param os 输出流
  * @param objs 对象列表
  * @param clz 对象类型
  * @param isXssf 是否是2007版本
  */
 public void exportExcelByPath(
     OutputStream os, List objs, Class clz, boolean isXssf, String message) {
   try {
     Workbook wb = handleExcel(objs, clz, isXssf, message);
     wb.write(os);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IOException e) {
     e.printStackTrace();
     logger.error(e);
   }
 }
  protected org.zkoss.poi.ss.usermodel.Font getPoiFontFromRichText(
      Workbook book, Cell cell, RichTextString rstr, int run) {
    if (run < 0) return null; // ZSS-1138

    org.zkoss.poi.ss.usermodel.Font font =
        rstr instanceof HSSFRichTextString
            ? book.getFontAt(((HSSFRichTextString) rstr).getFontOfFormattingRun(run))
            : ((XSSFRichTextString) rstr).getFontOfFormattingRun((XSSFWorkbook) book, run);
    if (font == null) {
      CellStyle style = cell.getCellStyle();
      short fontIndex = style != null ? style.getFontIndex() : (short) 0;
      return book.getFontAt(fontIndex);
    }
    return font;
  }
 /**
  * Name should be created after sheets created. A special defined name, _xlnm._FilterDatabase
  * (xlsx) or _FilterDatabase (xls), stores the selected cells for auto-filter
  */
 protected void importNamedRange() {
   for (int i = 0; i < workbook.getNumberOfNames(); i++) {
     Name definedName = workbook.getNameAt(i);
     if (skipName(definedName)) {
       continue;
     }
     SName namedRange = null;
     if (definedName.getSheetIndex() == -1) { // workbook scope
       namedRange = book.createName(definedName.getNameName());
     } else {
       namedRange = book.createName(definedName.getNameName(), definedName.getSheetName());
     }
     namedRange.setRefersToFormula(definedName.getRefersToFormula());
   }
 }
Example #5
0
  public static void main(String args[]) {
    try {
      // 构建Workbook对象, 只读Workbook对象
      // 直接从本地文件创建Workbook
      // 从输入流创建Workbook

      System.out.println("start load file-------------------------");
      InputStream is = new FileInputStream("E:/account.xls"); // 创建输入

      jxl.Workbook rwb = Workbook.getWorkbook(is);
      Sheet rs = rwb.getSheet(0); // 读取第一个sheet
      int colNum = rs.getColumns(); // 列数
      int rowNum = rs.getRows(); // 行数
      // System.out.println(colNum+" "+rowNum);
      // 创建account  bean
      ApplicationContext ctx =
          new ClassPathXmlApplicationContext(
              new String[] {
                "spring/applicationContext-model-account.xml", "spring/applicationContext.xml"
              });
      AccountService g = (AccountService) ctx.getBean("accountService");
      for (int i = 1; i < rowNum; i++) {
        String no = rs.getCell(0, i).getContents();
        String pass = rs.getCell(1, i).getContents();
        String name = rs.getCell(2, i).getContents();
        String maj = rs.getCell(3, i).getContents();
        String grade = rs.getCell(4, i).getContents();
        String cla = rs.getCell(5, i).getContents();
        String idn = rs.getCell(6, i).getContents();
        String email = rs.getCell(7, i).getContents();
        String phone = rs.getCell(8, i).getContents();
        String status = rs.getCell(9, i).getContents();
        String role = rs.getCell(10, i).getContents();

        ModelAccount ma = new ModelAccount();
        ma.setAccountNo(no);
        ma.setAccountPassword(pass);
        ma.setAccountRealName(name);
        ma.setAccountMajority(maj);
        ma.setAccountGrade(grade);
        ma.setAccountClass(cla);
        ma.setAccountIdentification(idn);
        ma.setAccountEmail(email);
        ma.setAccountMobilePhone(phone);
        ma.setAccountStatus(0);
        ModelRoles ac = new ModelRoles();
        ac.setRole_id(role);
        ma.setAccountRole(ac);
        g.saveOrUpdate(ma);
        // ma.setAccount_role(account_role)
        // System.out.println(no);
      }

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 // ZSS-854
 protected void importDefaultCellStyles() {
   ((AbstractBookAdv) book).clearDefaultCellStyles();
   for (CellStyle poiStyle : workbook.getDefaultCellStyles()) {
     book.addDefaultCellStyle(importCellStyle(poiStyle, false));
   }
   // in case of XLS files which we have not support defaultCellStyles
   if (book.getDefaultCellStyles().isEmpty()) {
     ((AbstractBookAdv) book).initDefaultCellStyles();
   }
   // ZSS-1132: setup default font
   ((AbstractBookAdv) book).initDefaultFont();
 }
  protected SFont importFont(CellStyle poiCellStyle) {
    SFont font = null;

    final short fontIndex = poiCellStyle.getFontIndex();
    if (importedFont.containsKey(fontIndex)) {
      font = importedFont.get(fontIndex);
    } else {
      Font poiFont = workbook.getFontAt(fontIndex);
      font = createZssFont(poiFont);
      importedFont.put(fontIndex, font); // ZSS-677
    }
    return font;
  }
 // ZSS-854
 protected void importNamedStyles() {
   ((AbstractBookAdv) book).clearNamedStyles();
   for (NamedStyle poiStyle : workbook.getNamedStyles()) {
     SNamedStyle namedStyle =
         new NamedStyleImpl(
             poiStyle.getName(),
             poiStyle.isCustomBuiltin(),
             poiStyle.getBuiltinId(),
             book,
             poiStyle.getIndex());
     book.addNamedCellstyle(namedStyle);
   }
 }
Example #9
0
 /**
  * 导出对象到Excel,直接新建一个Excel完成导出,基于路径的导出,不基于模板
  *
  * @param outPath 导出路径
  * @param objs 对象列表
  * @param clz 对象类型
  * @param isXssf 是否是2007版本
  */
 public void exportExcelByPath(
     String outPath, List objs, Class clz, boolean isXssf, String message) {
   Workbook wb = handleExcel(objs, clz, isXssf, message);
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(outPath);
     wb.toString().getBytes("GB2312");
     wb.write(fos);
   } catch (FileNotFoundException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IOException e) {
     e.printStackTrace();
     logger.error(e);
   } finally {
     try {
       if (fos != null) fos.close();
     } catch (IOException e) {
       e.printStackTrace();
       logger.error(e);
     }
   }
 }
Example #10
0
 public List<Object> readExcel(Workbook wb, Class clz, int readLine, int tailLine) {
   Sheet sheet = wb.getSheetAt(0); // 取第一张表
   List<Object> objs = null;
   try {
     Row row = sheet.getRow(readLine); // 开始行,主题栏
     objs = new ArrayList<Object>();
     Map<Integer, String> maps = getHeaderMap(row, clz); // 设定对应的字段顺序与方法名
     if (maps == null || maps.size() <= 0)
       throw new RuntimeException("要读取的Excel的格式不正确,检查是否设定了合适的行"); // 与order顺序不符
     for (int i = readLine + 1; i <= sheet.getLastRowNum() - tailLine; i++) { // 取数据
       row = sheet.getRow(i);
       Object obj = clz.newInstance(); //   调用无参结构
       for (Cell c : row) {
         int ci = c.getColumnIndex();
         String mn = maps.get(ci).substring(3); // 消除get
         mn = mn.substring(0, 1).toLowerCase() + mn.substring(1);
         Map<String, Object> params = new HashMap<String, Object>();
         if (!"enterDate".equals(mn)) c.setCellType(Cell.CELL_TYPE_STRING); // 设置单元格格式
         else c.setCellType(Cell.CELL_TYPE_NUMERIC);
         if (this.getCellValue(c).trim().equals("是")) {
           BeanUtils.copyProperty(obj, mn, 1);
         } else if (this.getCellValue(c).trim().equals("否")) {
           BeanUtils.copyProperty(obj, mn, 0);
         } else BeanUtils.copyProperty(obj, mn, this.getCellValue(c));
       }
       objs.add(obj);
     }
   } catch (InstantiationException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (IllegalAccessException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (InvocationTargetException e) {
     e.printStackTrace();
     logger.error(e);
   } catch (NumberFormatException e) {
     e.printStackTrace();
     logger.error(e);
   }
   return objs;
 }
Example #11
0
  private void saveExcelPoject(File file) throws IOException {
    Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("timeplan");
    // Заголовок в 0 строке
    Row row = sheet.createRow(0);
    Cell cell = row.createCell(0);
    cell.setCellValue("Филиал");
    cell = row.createCell(1);
    cell.setCellValue("Город");
    Calendar cal = Calendar.getInstance();
    cal.set(2017, 0, 5); // Начальная дата проекта
    SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yy");
    for (int i = 0; i < 3 * 52; i++) { // Счетчик по неделям
      cell = row.createCell(i + 2);
      cell.setCellValue(sdf.format(cal.getTime()));
      cal.add(Calendar.WEEK_OF_YEAR, 1); // Следующая неделя
    }

    // sheet.setColumnWidth(0, 256);

    // Цвета ячеек
    CellStyle[] styles = new CellStyle[6];
    styles[0] = wb.createCellStyle();
    styles[0].setFillForegroundColor(HSSFColor.RED.index);
    styles[0].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[1] = wb.createCellStyle();
    styles[1].setFillForegroundColor(HSSFColor.GREEN.index);
    styles[1].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[2] = wb.createCellStyle();
    styles[2].setFillForegroundColor(HSSFColor.BLUE.index);
    styles[2].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[3] = wb.createCellStyle();
    styles[3].setFillForegroundColor(HSSFColor.ROSE.index);
    styles[3].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[4] = wb.createCellStyle();
    styles[4].setFillForegroundColor(HSSFColor.LIGHT_BLUE.index);
    styles[4].setFillPattern(FillPatternType.SOLID_FOREGROUND);
    styles[5] = wb.createCellStyle();
    styles[5].setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
    styles[5].setFillPattern(FillPatternType.SOLID_FOREGROUND);

    short rowIdx = 0;
    for (Region region : this.regions) {
      row = sheet.createRow(++rowIdx);
      cell = row.createCell(0);
      cell.setCellValue(region.filial);
      cell = row.createCell(1);
      cell.setCellValue(region.name);

      cal = Calendar.getInstance();
      cal.set(2017, 0, 5); // Начальная дата проекта
      for (int i = 0; i < 3 * 52; i++) { // Счетчик по неделям
        short color = region.getDateColorIndex(cal.getTime());
        if (color >= 0) {
          cell = row.createCell(i + 2);
          cell.setCellStyle(styles[color]);
        }

        cal.add(Calendar.WEEK_OF_YEAR, 1); // Следующая неделя
      }
    }

    try (FileOutputStream fileOut = new FileOutputStream(file)) {
      wb.write(fileOut);
    }
  }
  public void readProcessSpreadSheet() {
    processSpreadSheet = System.getProperty("processSpreadSheet");
    System.out.println("processSpreadSheet: " + processSpreadSheet);
    if (processCodesList.size() == 0) {
      if (processSpreadSheet != null && !processSpreadSheet.equals("")) {
        Workbook wb1 = null;
        try {
          wb1 = new XSSFWorkbook(processSpreadSheet);
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        Sheet sheet = wb1.getSheetAt(0);
        Row row;
        Cell cell;

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        // This trick ensures that we get the data properly even if it
        // doesn't start from first few rows
        for (int i = 0; i < 10 || i < rows; i++) {
          row = sheet.getRow(i);
          if (row != null) {
            tmp = sheet.getRow(i).getPhysicalNumberOfCells();
            // out.println("tmp value"+tmp);
            if (tmp > cols) {
              cols = tmp;
            }
          }
        }

        ProcessDefinition tempProcessCode;
        for (int r1 = 0; r1 < rows; r1++) {
          tempProcessCode = new ProcessDefinition();

          row = sheet.getRow(r1);
          if (row != null) {
            if (row.getCell(0) != null) {
              for (int counter = 0; counter < cols; counter++) {
                cell = row.getCell((short) counter);
                // cell = row.getCell(1);
                if (counter == 0) {
                  if (cell != null) {
                    tempProcessCode.setProcessName(cell.getStringCellValue());
                  } else {
                    tempProcessCode.setProcessName("");
                  }
                } else if (counter == 1) {
                  if (cell != null) {
                    tempProcessCode.setProcessCode(cell.getStringCellValue());
                  } else {
                    tempProcessCode.setProcessCode("");
                  }
                } else if (counter == 2) {
                  if (cell != null) {
                    tempProcessCode.setIaeaCode(cell.getStringCellValue());
                  } else {
                    tempProcessCode.setIaeaCode("");
                  }
                } else if (counter == 3) {
                  if (cell != null) {
                    tempProcessCode.setProcessDescription(cell.getStringCellValue());
                    // System.out.println(tempProcessCode.getProcessDescription());
                  } else {
                    tempProcessCode.setProcessDescription("");
                    // System.out.println("Process Description EMpty");
                  }
                }
              }
            }

          } else {
            rows++;
          }
          processCodesList.add(tempProcessCode);
        }
      }
    }
    System.out.println(processCodesList.size());
  }
  /*
   * import sheet scope content from POI Sheet.
   */
  protected SSheet importSheet(Sheet poiSheet, int poiSheetIndex) {
    SSheet sheet = book.createSheet(poiSheet.getSheetName());
    sheet.setDefaultRowHeight(UnitUtil.twipToPx(poiSheet.getDefaultRowHeight()));
    // ZSS-952
    importSheetDefaultColumnWidth(poiSheet, sheet);
    // reference FreezeInfoLoaderImpl.getRowFreeze()
    sheet.getViewInfo().setNumOfRowFreeze(BookHelper.getRowFreeze(poiSheet));
    sheet.getViewInfo().setNumOfColumnFreeze(BookHelper.getColumnFreeze(poiSheet));
    sheet
        .getViewInfo()
        .setDisplayGridlines(
            poiSheet
                .isDisplayGridlines()); // Note isDisplayGridlines() and isPrintGridlines() are
                                        // different
    sheet.getViewInfo().setColumnBreaks(poiSheet.getColumnBreaks());
    sheet.getViewInfo().setRowBreaks(poiSheet.getRowBreaks());

    SPrintSetup sps = sheet.getPrintSetup();

    SHeader header = sheet.getViewInfo().getHeader();
    if (header != null) {
      header.setCenterText(poiSheet.getHeader().getCenter());
      header.setLeftText(poiSheet.getHeader().getLeft());
      header.setRightText(poiSheet.getHeader().getRight());
      sps.setHeader(header);
    }

    SFooter footer = sheet.getViewInfo().getFooter();
    if (footer != null) {
      footer.setCenterText(poiSheet.getFooter().getCenter());
      footer.setLeftText(poiSheet.getFooter().getLeft());
      footer.setRightText(poiSheet.getFooter().getRight());
      sps.setFooter(footer);
    }

    if (poiSheet.isDiffOddEven()) {
      Header poiEvenHeader = poiSheet.getEvenHeader();
      if (poiEvenHeader != null) {
        SHeader evenHeader = new HeaderFooterImpl();
        evenHeader.setCenterText(poiEvenHeader.getCenter());
        evenHeader.setLeftText(poiEvenHeader.getLeft());
        evenHeader.setRightText(poiEvenHeader.getRight());
        sps.setEvenHeader(evenHeader);
      }
      Footer poiEvenFooter = poiSheet.getEvenFooter();
      if (poiEvenFooter != null) {
        SFooter evenFooter = new HeaderFooterImpl();
        evenFooter.setCenterText(poiEvenFooter.getCenter());
        evenFooter.setLeftText(poiEvenFooter.getLeft());
        evenFooter.setRightText(poiEvenFooter.getRight());
        sps.setEvenFooter(evenFooter);
      }
    }

    if (poiSheet.isDiffFirst()) {
      Header poiFirstHeader = poiSheet.getFirstHeader();
      if (poiFirstHeader != null) {
        SHeader firstHeader = new HeaderFooterImpl();
        firstHeader.setCenterText(poiFirstHeader.getCenter());
        firstHeader.setLeftText(poiFirstHeader.getLeft());
        firstHeader.setRightText(poiFirstHeader.getRight());
        sps.setFirstHeader(firstHeader);
      }
      Footer poiFirstFooter = poiSheet.getFirstFooter();
      if (poiFirstFooter != null) {
        SFooter firstFooter = new HeaderFooterImpl();
        firstFooter.setCenterText(poiFirstFooter.getCenter());
        firstFooter.setLeftText(poiFirstFooter.getLeft());
        firstFooter.setRightText(poiFirstFooter.getRight());
        sps.setFirstFooter(firstFooter);
      }
    }

    PrintSetup poips = poiSheet.getPrintSetup();

    sps.setBottomMargin(poiSheet.getMargin(Sheet.BottomMargin));
    sps.setTopMargin(poiSheet.getMargin(Sheet.TopMargin));
    sps.setLeftMargin(poiSheet.getMargin(Sheet.LeftMargin));
    sps.setRightMargin(poiSheet.getMargin(Sheet.RightMargin));
    sps.setHeaderMargin(poiSheet.getMargin(Sheet.HeaderMargin));
    sps.setFooterMargin(poiSheet.getMargin(Sheet.FooterMargin));

    sps.setAlignWithMargins(poiSheet.isAlignMargins());
    sps.setErrorPrintMode(poips.getErrorsMode());
    sps.setFitHeight(poips.getFitHeight());
    sps.setFitWidth(poips.getFitWidth());
    sps.setHCenter(poiSheet.getHorizontallyCenter());
    sps.setLandscape(poips.getLandscape());
    sps.setLeftToRight(poips.getLeftToRight());
    sps.setPageStart(poips.getUsePage() ? poips.getPageStart() : 0);
    sps.setPaperSize(PoiEnumConversion.toPaperSize(poips.getPaperSize()));
    sps.setCommentsMode(poips.getCommentsMode());
    sps.setPrintGridlines(poiSheet.isPrintGridlines());
    sps.setPrintHeadings(poiSheet.isPrintHeadings());

    sps.setScale(poips.getScale());
    sps.setScaleWithDoc(poiSheet.isScaleWithDoc());
    sps.setDifferentOddEvenPage(poiSheet.isDiffOddEven());
    sps.setDifferentFirstPage(poiSheet.isDiffFirst());
    sps.setVCenter(poiSheet.getVerticallyCenter());

    Workbook poiBook = poiSheet.getWorkbook();
    String area = poiBook.getPrintArea(poiSheetIndex);
    if (area != null) {
      sps.setPrintArea(area);
    }

    CellRangeAddress rowrng = poiSheet.getRepeatingRows();
    if (rowrng != null) {
      sps.setRepeatingRowsTitle(rowrng.getFirstRow(), rowrng.getLastRow());
    }

    CellRangeAddress colrng = poiSheet.getRepeatingColumns();
    if (colrng != null) {
      sps.setRepeatingColumnsTitle(colrng.getFirstColumn(), colrng.getLastColumn());
    }

    sheet.setPassword(poiSheet.getProtect() ? "" : null);

    // import hashed password directly
    importPassword(poiSheet, sheet);

    // ZSS-832
    // import sheet visible
    if (poiBook.isSheetHidden(poiSheetIndex)) {
      sheet.setSheetVisible(SheetVisible.HIDDEN);
    } else if (poiBook.isSheetVeryHidden(poiSheetIndex)) {
      sheet.setSheetVisible(SheetVisible.VERY_HIDDEN);
    } else {
      sheet.setSheetVisible(SheetVisible.VISIBLE);
    }

    // ZSS-1130
    // import conditionalFormatting
    importConditionalFormatting(sheet, poiSheet);
    return sheet;
  }