Example usage for org.apache.poi.ss.usermodel WorkbookFactory create

List of usage examples for org.apache.poi.ss.usermodel WorkbookFactory create

Introduction

In this page you can find the example usage for org.apache.poi.ss.usermodel WorkbookFactory create.

Prototype

public static Workbook create(File file) throws IOException, EncryptedDocumentException 

Source Link

Document

Creates the appropriate HSSFWorkbook / XSSFWorkbook from the given File, which must exist and be readable.

Usage

From source file:cn.lhfei.fu.service.impl.ThesisDataBuildFactory.java

License:Apache License

@Override
public boolean importDataByExcel(String filePath, Map<String, Object> params) throws Exception {

    Date currentDate = new Date();
    List<ThesisBase> thesisList = new ArrayList<ThesisBase>();

    InputStream inp = new FileInputStream(filePath);
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(0);/*from w  w  w. ja  v  a 2s  . c o  m*/

    int totalRows = sheet.getPhysicalNumberOfRows();

    Cell classCell = null;
    Cell studentNameCell = null;
    Cell studentIdCell = null;

    String className = "";
    String studentId = "";
    String studentName = "";

    String desc = "?";
    Integer degree = (Integer) params.get("degree");

    for (int i = 1; i < totalRows; i++) {
        Row row = sheet.getRow(i);

        classCell = row.getCell(0);
        studentNameCell = row.getCell(1);
        studentIdCell = row.getCell(2);

        className = classCell.getStringCellValue();
        studentName = studentNameCell.getStringCellValue();
        studentId = studentIdCell.getStringCellValue();

        ThesisBase model = new ThesisBase();
        model.setClassName(className);
        model.setStudentName(studentName);
        model.setStudentId(studentId);
        model.setDegree(degree);
        model.setDesc(desc);
        model.setActionType("" + OperationTypeEnum.PLSC.getCode());

        model.setOperationTime(currentDate);
        model.setCreateTime(currentDate);
        model.setModifyTime(currentDate);

        thesisList.add(model);
    }

    log.info("Batch size: ", thesisList.size());

    for (ThesisBase thesis : thesisList) {

        thesisBaseService.save(thesis);
    }

    return false;
}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * ??ExcelTitle//from w  w  w. ja va 2s  . c o m
 *
 * @param excelFile
 * @param sheetName sheet???
 * @return
 */
public static List<String> scanExcelTitles(File excelFile, String... sheetName) {
    List<String> titles = new ArrayList<>();
    try {
        Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFile));

        Sheet sheet;
        if (sheetName.length == 0) {
            sheet = workbook.getSheetAt(0);
        } else {
            sheet = workbook.getSheet(sheetName[0]);
        }
        Row row = sheet.getRow(0);
        if (row != null) {
            int i = 0;
            while (true) {
                Cell cell = row.getCell(i);
                if (cell == null) {
                    break;
                }
                titles.add(cell.getStringCellValue());
                i++;
            }
        }
    } catch (Exception e) {
        logger.debug("Scan Excel [" + excelFile.getPath() + excelFile.getName() + "] Error");
        throw new RuntimeException(e);
    }
    return titles;
}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * ?Excel List<Map<String K,String V>>?
 *
 * @param excelFile  Excel/*from   w  w w .j  a v  a 2  s. c o m*/
 * @param fieldNames MapKeyValuesheet?
 * @param sheetName  ??
 * @return
 */
public static List<Map<String, String>> readExcelToMap(File excelFile, String fieldNames, String... sheetName) {
    List<Map<String, String>> list = Collections.EMPTY_LIST;

    try {
        Workbook workbook = WorkbookFactory.create(new FileInputStream(excelFile));
        list = execRead(workbook, fieldNames, sheetName);
    } catch (Exception e) {
        logger.error("?:" + e);
    }

    return list;
}

From source file:cn.mypandora.util.MyExcelUtil.java

License:Apache License

/**
 * ?Excel List<Map<String K,String V>>?
 *
 * @param excelFile  ?//  www.j  a  va2 s . com
 * @param fieldNames Key
 * @param sheetName  sheet??
 * @return
 */
public static List<Map<String, String>> readExcelToMap(InputStream excelFile, String fieldNames,
        String... sheetName) {
    List<Map<String, String>> list = Collections.EMPTY_LIST;
    try {
        Workbook workbook = WorkbookFactory.create(excelFile);
        list = execRead(workbook, fieldNames, sheetName);
    } catch (Exception e) {
        logger.error("?:" + e);
    }
    return list;
}

From source file:cn.poi.api.example.ExcelExample.java

License:Open Source License

public static void ReadExcel(String excel, String brandcode)
        throws EncryptedDocumentException, InvalidFormatException, IOException {
    List<BrandConfigCommand> list = new ArrayList<>();
    InputStream inp = resourceLoader.getResource(excel).getInputStream();
    Workbook wb = WorkbookFactory.create(inp);
    Sheet sheet = wb.getSheetAt(4);/*from  w w  w  .  j a  v  a2  s  . c  o  m*/
    Row tempRow = null;
    for (int i = 1; i < sheet.getLastRowNum(); i++) {
        BrandConfigCommand brandConfigCommand = new BrandConfigCommand();
        String[] array = new String[5];
        Row row = sheet.getRow(i);
        if (StringUtils.isEmpty(row.getCell(4).toString())) {
            continue;
        }
        for (int j = 0; j < row.getLastCellNum(); j++) {
            if (j == 0 && StringUtils.isEmpty(row.getCell(j).toString())) {
                System.out.print(tempRow.getCell(j).getStringCellValue() + "    ");
                array[j] = tempRow.getCell(0).getStringCellValue();
                continue;
            } else if (j == 0) {
                tempRow = row;
            }
            if (j == 1 && StringUtils.isEmpty(row.getCell(j).toString())) {
                System.out.print(tempRow.getCell(j).getStringCellValue() + "    ");
                array[j] = tempRow.getCell(j).getStringCellValue();
                continue;
            }
            array[j] = row.getCell(j).getStringCellValue();
            System.out.print(row.getCell(j).toString() + "    ");

        }

        brandConfigCommand.setStoreCode(array[0]);
        brandConfigCommand.setStoreDate(array[1]);
        brandConfigCommand.setProvice(array[2]);
        brandConfigCommand.setCity(array[3]);
        brandConfigCommand.setArea(array[4]);
        brandConfigCommand.setArea_name(array[2] + array[3] + array[4]);
        list.add(brandConfigCommand);
        System.out.println();
    }

    List<String> listStr = new ArrayList<>();
    for (BrandConfigCommand brandConfigCommand : list) {
        String str = sqlStart + brandConfigCommand.getArea_name() + sqlEnd + provice
                + brandConfigCommand.getProvice() + city + brandConfigCommand.getCity() + area
                + brandConfigCommand.getArea() + code + brandConfigCommand.getStoreCode() + brand_code
                + brandcode + "'";
        listStr.add(str);
    }
    System.out.println(JSON.toJSONString(listStr));

}

From source file:cn.study.innerclass.PoiUtil.java

License:Open Source License

public static Workbook createWorkbook(FileInputStream fis)
        throws EncryptedDocumentException, InvalidFormatException, IOException {
    return WorkbookFactory.create(fis);
}

From source file:cn.study.innerclass.Test.java

License:Open Source License

public static void main(String[] args) throws EncryptedDocumentException, InvalidFormatException, IOException {
    /*Exsample ex = new Exsample();
    Exsample.PublicInnerClass pub = ex.new PublicInnerClass();
    pub.setPuAge(111);/* w w  w.j  a  v  a2  s.  c  o  m*/
    pub.test();*/

    /*Workbook book = new HSSFWorkbook();
    Cell cell = book.createSheet().createRow(1).createCell(1);
    cell.setCellValue(5l);
    System.out.println(cell.getCellType());*/

    FileInputStream fin = new FileInputStream("E:/test.xlsx");
    Workbook book = WorkbookFactory.create(fin);
    Sheet sheet = book.getSheetAt(0);
    ;
    PoiUtil.getCellData(sheet.getRow(0).getCell(0), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(0).getCell(1), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(0).getCell(2), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(1).getCell(0), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(1).getCell(1), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(1).getCell(2), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(2).getCell(0), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(2).getCell(1), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(2).getCell(2), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(3).getCell(0), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(3).getCell(1), new XSSFFormulaEvaluator((XSSFWorkbook) book));
    PoiUtil.getCellData(sheet.getRow(3).getCell(2), new XSSFFormulaEvaluator((XSSFWorkbook) book));
}

From source file:CODIGOS.EditaPlanilha.java

public static void edita(String diretorio, String arquivo, int linha, int coluna, String texto) {
    try {//from  w w  w  . j  a  v a  2 s.c om
        File dir = new File(diretorio);
        File file = new File(dir, arquivo + ".xlsx");
        InputStream inp = new FileInputStream(file);
        try {
            Workbook wb = WorkbookFactory.create(inp);
            Sheet sheet = wb.getSheetAt(0);
            Row row = sheet.getRow(linha);//LINHA
            Cell cell = row.getCell(0);
            cell = row.createCell(coluna);//COLUNA
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(texto);
            try (FileOutputStream fileOut = new FileOutputStream(file)) {
                wb.write(fileOut);
            }
        } catch (IOException | InvalidFormatException ex) {
            Logger.getLogger(EditaPlanilha.class.getName()).log(Level.SEVERE, null, ex);
        }
    } catch (FileNotFoundException ex) {
        Logger.getLogger(EditaPlanilha.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.adobe.acs.commons.mcp.impl.TestGenericReportExcelServlet.java

License:Apache License

@Test
public void testReport() throws Exception {
    int numRows = 10;
    String reportPath = "/var/acs-commons/mcp/instances/junit/jcr:content/report";
    ResourceBuilder rb = slingContext.build()
            .resource(reportPath, "columns", new String[] { "ColumnA", "ColumnB" }, "name", "report",
                    "sling:resourceType",
                    "acs-commons/components/utilities/process-instance/process-generic-report")
            .resource("rows");
    rb.siblingsMode();/*from  ww w  .  ja  v a2  s  . co m*/
    for (int i = 1; i <= numRows; i++) {
        rb.resource("row-" + i, "ColumnA", "abcdef-" + i, "ColumnB", "qwerty-" + i);
    }
    MockSlingHttpServletRequest request = slingContext.request();
    request.setResource(slingContext.resourceResolver().getResource(reportPath));
    MockSlingHttpServletResponse response = slingContext.response();

    slingContext.addModelsForClasses(GenericReport.class);

    GenericReportExcelServlet servlet = new GenericReportExcelServlet();

    servlet.doGet(request, response);

    assertEquals("application/vnd.ms-excel", response.getContentType());

    Workbook wb = WorkbookFactory.create(new ByteArrayInputStream(response.getOutput()));
    Sheet sh = wb.getSheetAt(0);
    assertEquals(numRows, sh.getLastRowNum());
    Row header = sh.getRow(0);
    assertEquals("Column A", header.getCell(0).getStringCellValue());
    assertEquals("Column B", header.getCell(1).getStringCellValue());
    for (int i = 1; i <= numRows; i++) {
        Row row = sh.getRow(i);
        assertEquals("abcdef-" + i, row.getCell(0).getStringCellValue());
        assertEquals("qwerty-" + i, row.getCell(1).getStringCellValue());
    }

}

From source file:com.alibaba.ims.platform.util.ExcelUtil.java

License:Open Source License

private static Workbook createWorkbook(File file) {
    try {//  w  w  w .j a  v a 2 s. c  o  m
        return WorkbookFactory.create(file);
    } catch (Exception e) {
        logger.error("Read workbook from file error, file:" + file.getPath(), e);
    }
    return null;
}