简体   繁体   English

如何使用JSP从客户端读取excel文件并处理数据而不进行存储

[英]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. 我有一个JSP表单,其中包含文本字段以及文件输入。 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)? 但是,我的问题是如何处理文件(例如excel文件)而不存储它,而只是使用POI XSSF直接将电子表格数据处理到地图中(因为FileInput查找存储的文件路径)? Also, how can I pass the local variables/maps from above servlet back to the jsp page? 另外,如何将servlet上方的局部变量/映射传递回jsp页面?

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? 基本上,我希望允许用户填写表单并选择一个excel文件进​​行处理,并且希望在同一jsp上的servlet中进行验证后显示结果,而无需刷新jsp(例如在表单下方显示结果?

You can read a spreadsheet in directly from an InputStream like this 您可以像这样直接从InputStream中读取电子表格

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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