简体   繁体   中英

How to read excel file from client using JSP and process data without storing

I have a JSP form containing text fields as well as file input. I want to know ways to handle the validation/processing of the form. Since the form has file input, it is multipart form so I am then checking separately for file as in

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getName(item.getName());
                InputStream filecontent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}

(Taken from here ).

But, my question is how can I process the file (say excel file), without storing it and just directly processing the spreadsheet data into map using POI XSSF(since FileInput looks for stored file path)? Also, how can I pass the local variables/maps from above servlet back to the jsp page?

Basically, I want to allow users to fill a form and select an excel file to process, and I want to display the results after validation in servlet on the same jsp without refreshing the jsp (like showing results below the form?

You can read a spreadsheet in directly from an InputStream like this

InputStream filecontent = item.getInputStream();
XSSFWorkbook wb = new XSSFWorkbook(filecontent);
// get first worksheet
XSSFSheet sheet = wb.getSheetAt(0);
// get cell at top left
System.out.println(sheet.getRow(0).getCell(0).getStringCellValue());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM