如何动态地从Java导入Excel中的数据?

时间:2017-05-04 07:02:11

标签: java angularjs excel spring-boot apache-poi

我希望我的用户可以在各种页面中从Excel导入数据,例如用户创建等等。

我尝试过以下代码(Apache POI),但无法动态读取它。

它询问我文件位置的URL。如果它是从本地读取,我可以指定它。但我动态地想要这个。如何指定URL?

还有其他方式或库来处理这个吗?

 public class ApachePOIExcelRead {

//private static final String FILE_NAME = "/Users/apple/Desktop/Import.xlsx";

public List<User> readExcel(Import imports) {
  System.out.println(imports.getFile().toString());
String FILE_NAME = "data:" + imports.getFileContentType()+";base64,"+imports.getData().toString();
  List<User> userList = new ArrayList<User>();
    try {
      System.out.println("Import file content type is " + imports.getFileContentType());
      if("application/vnd.ms-excel".equalsIgnoreCase(imports.getFileContentType()) || "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".equalsIgnoreCase(imports.getFileContentType())){
        System.out.println("Content type is as exepcted");
        byte[] file = imports.getFile();
        FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
        excelFile.read(file);
        Workbook workbook = new XSSFWorkbook(excelFile);
        Sheet datatypeSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = datatypeSheet.iterator();
        List<TestPOJO> pojoList = new ArrayList<TestPOJO>();

        while (iterator.hasNext()) {
          System.out.println("Iterator has next row");
            Row currentRow = iterator.next();

            if(currentRow.getRowNum() != 0) {
                //Exit the first row since its not needed.

            Iterator<Cell> cellIterator = currentRow.iterator();
                TestPOJO testPOJO = new TestPOJO();
            while (cellIterator.hasNext()) {

  System.out.println("cell iterator has next value");
                Cell currentCell = cellIterator.next();

                switch (currentCell.getColumnIndex())
                {
                    case 0 :
                        String idData = currentCell.getStringCellValue();
                        if (DataValidator.isDataNumber(idData) ) {
                            testPOJO.setId(Integer.parseInt(idData));
                            System.out.println("Id is" +testPOJO.getId());

                        }
                        else {
                            throw new Exception("Data not correct");
                        }
                        break;

                    case 1:
                        String passwordData = currentCell.getStringCellValue();
                        if(!DataValidator.isDataInvalid(passwordData)) {
                        testPOJO.setPassword(currentCell.getStringCellValue());
                      System.out.println("password is" +testPOJO.getPassword());

                    }
                        else {
                            throw new Exception("Data not correct");
                        }
                        break;
                    case 2 :
                        String firstName = currentCell.getStringCellValue();
                        if(DataValidator.isDataContainingOnlyString(firstName)) {
                            testPOJO.setFirstName(firstName);
                            System.out.println("First name  is" +testPOJO.getFirstName());
                        }
                        else {
                            throw new Exception("Data not correct");
                        }
                         break;
                    case 3:
                        String lastName = currentCell.getStringCellValue();
                        if(DataValidator.isDataContainingOnlyString(lastName)) {
                            testPOJO.setLastName(lastName);
                            System.out.println("Last Name is" +testPOJO.getLastName());
                        }
                        else {
                            throw new Exception("Data not correct");
                        }
                        break;

                    case 4 :
                        String emailId = currentCell.getStringCellValue();
                        if(DataValidator.isDataInCorrectEmailFormat(emailId)) {

                            testPOJO.setEmailId(currentCell.getStringCellValue());
                            System.out.println("Email Id is" +testPOJO.getEmailId());

                        }

                        else {
                            throw new Exception("Data not correct");
                        }
                        break;
                }

            }
                pojoList.add(testPOJO);
            }
        }

        System.out.println("LIST SIZE" +pojoList.size());
      }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
  return userList;
}
}

2 个答案:

答案 0 :(得分:0)

你可以在调用jar时将它作为参数之一传递给它吗?或者,您可以创建属性文件,您可以在其中指定文件的位置。您不必对该值进行硬编码。我不确定这是否能回答你的问题。 您必须提供有关动态数据的含义的更多信息。

答案 1 :(得分:0)

我也遇到类似的问题。

我所做的是我使用这样的请求正文从前端接收到的文件作为多部分文件

public String uploadAttribute(@RequestBody MultipartFile file){

//然后我通过获取如下所示的multipartfile的名称创建了一个与multipartfile相同的文件名

File convFile = new File(file.getOriginalFilename());

//然后为上述文件创建一个输出流,并将多部分文件的数据通过如下转换为字节数组写入其中:

FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();

然后为新创建的文件创建了输入流,并将该输入流传递给我的工作簿。

FileInputStream fis =new FileInputStream(convFile);
Workbook workbook = new HSSFWorkbook(fis);
}

之后,我能够从工作簿中获取数据。希望它对你有用。

//正义代码。...

public String uploadAttribute(@RequestBody MultipartFile file){
File convFile = new File(file.getOriginalFilename());
                FileOutputStream fos = new FileOutputStream(convFile);
                fos.write(file.getBytes());
                fos.close();

                FileInputStream fis =new FileInputStream(convFile);
                Workbook workbook = new HSSFWorkbook(fis);
                return workbook.getSheetName(0);
}