java - 将上传的文件(xls)转换为xml

标签 java xml spring-mvc file-upload apache-poi

我一直在制作一个可以将上传的文件转换为xml文件的应用程序。上传的文件是xls文件。 我已经使用 apache-poi 将 xls 转换器制作为 xml。 我也做了上传和下载的功能。 当xls文件上传时,应该由 Controller 将其转换为xml并保存到数据库(Mysql)中,但失败。 应用程序返回异常:

java.lang.ClassCastException: org.springframework.web.multipart.commons.CommonsMultipartFile cannot be cast to java.io.InputStream

这是 Controller :

@Controller
public class FileController {

@Autowired
private FileDAO documentDao;

@RequestMapping("/index")
public String showDocument(Map<String, Object> map) {
    try {
        map.put("document", new File());
        map.put("documentList", documentDao.list());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "documents";
}

@SuppressWarnings("deprecation")
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ModelAttribute("document") File document,
        @RequestParam("file") MultipartFile file) throws IOException {

    System.out.println("Name:" + document.getName());
    System.out.println("Desc:" + document.getDescription());
    System.out.println("File:" + file.getName());
    System.out.println("ContentType:" + file.getContentType());

    /*
     * start to convert xls to xml
     * */
    try {
        InputStream input = (InputStream) file;
        HSSFWorkbook workbook = new HSSFWorkbook(input);
        HSSFSheet spreadsheet = workbook.getSheetAt(0);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.newDocument();
        doc.setXmlStandalone(true);

        Element spectraexchange = doc.createElementNS("http://www.lstelcom.com/Schema/SPECTRAexchange", "SPECTRAEXCHANGE");
        spectraexchange.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
        spectraexchange.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        spectraexchange.setAttribute("version", "2.4.28");
        doc.appendChild(spectraexchange);

        for(int i=1; i<=2; i++){

            HSSFRow row = spreadsheet.getRow(i);

            Element application = doc.createElement("APPLICATION");
            spectraexchange.appendChild(application);

            Element svid = doc.createElement("SV_SV_ID");
            application.appendChild(svid);
            svid.appendChild(doc.createTextNode("12"));

            Element ssid = doc.createElement("SS_SS_ID");
            application.appendChild(ssid);
            ssid.appendChild(doc.createTextNode("140"));

            Element address = doc.createElement("ADDRESS");//men-generate <ADDRESS>
            application.appendChild(address);//men-generate </ADDRESS>
            address.setAttribute("AD_TYPE", "L");

            Element adspplus = doc.createElement("AD_SPPLUS_TYPE");//men-generate <AD_SPPLUS_TYPE>
            address.appendChild(adspplus);//men-generate </AD_SPPLUS_TYPE>
            adspplus.appendChild(doc.createTextNode("L"));//<AD_SPPLUS_TYPE>L<AD_SPPLUS_TYPE>

            try {
                Element adcompany = doc.createElement("AD_COMPANY");
                address.appendChild(adcompany);
                adcompany.appendChild(doc.createTextNode(row.getCell((short) 33).getStringCellValue()));
                if(row.getCell((short) 33).getStringCellValue()==null){
                    continue;
                }
            } catch (Exception e) {
                e.getMessage();
            }

            try {
                Element adstreet = doc.createElement("AD_STREET");
                address.appendChild(adstreet);
                adstreet.appendChild(doc.createTextNode(row.getCell((short) 35).getStringCellValue()));
                if(row.getCell((short) 35).getStringCellValue()==null){
                    continue;
                }
            } catch (Exception e) {
                e.getMessage();
            }


            Element adcountry = doc.createElement("AD_COUNTRY");
            address.appendChild(adcountry);
            adcountry.appendChild(doc.createTextNode("INS"));

            try {
                Element adcity = doc.createElement("AD_CITY");
                address.appendChild(adcity);
                adcity.appendChild(doc.createTextNode(row.getCell((short) 36).getStringCellValue()));
                if(row.getCell((short) 36).getStringCellValue()==null) {
                    continue;
                }
            } catch (Exception e) {
                e.getMessage();
            }

            Element station = doc.createElement("STATION");
            application.appendChild(station);

            Element transmitter = doc.createElement("TRANSMITTER");
            station.appendChild(transmitter);

            try {
                Element eqpname = doc.createElement("EQP_EQUIP_NAME");
                transmitter.appendChild(eqpname);
                eqpname.appendChild(doc.createTextNode(row.getCell((short) 2).getStringCellValue()));
                if(row.getCell((short) 2).getStringCellValue()==null){
                    continue;
                }
            } catch (Exception e) {
                e.getMessage();
            }


            Element eqptype = doc.createElement("EQP_TYPE_IS_APPROVED");
            transmitter.appendChild(eqptype);
            eqptype.appendChild(doc.createTextNode("1"));

            try {
                Element eqpmodel = doc.createElement("EQP_EQUIP_MODEL");
                transmitter.appendChild(eqpmodel);
                eqpmodel.appendChild(doc.createTextNode(row.getCell((short) 4).getStringCellValue()));
                if(row.getCell((short) 4).getStringCellValue()==null){
                    continue;
                }

            } catch (Exception e) {
                e.getMessage();
            }

            try {
                Element eqpprod = doc.createElement("EQP_EQUIP_PROD");
                transmitter.appendChild(eqpprod);
                eqpprod.appendChild(doc.createTextNode(row.getCell((short) 6).getStringCellValue()));
                if(row.getCell((short) 6).getStringCellValue()==null){
                    continue;
                }
            } catch (Exception e) {
                e.getMessage();
            }


        }

        TransformerFactory tfactory = TransformerFactory.newInstance();
        Transformer transformer = tfactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty("{http:/xml.apache.org/xslt}indent-amount", "2");
        transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");

        DOMSource source = new DOMSource(doc);
        StreamResult result = new StreamResult(System.out);
        //StreamResult result = new StreamResult("E://XlsToXml/standard_query02.xml");
        transformer.transform(source, result);
        /*
         * end of convertion
         * */

        //----------------------------------//
        Blob blob = Hibernate.createBlob(((MultipartFile) doc).getInputStream());

        document.setFilename(((MultipartFile) doc).getOriginalFilename());
        document.setContent(blob);
        document.setContentType(((MultipartFile) doc).getContentType());

        documentDao.save(document);

    }catch (IOException e) {
        System.out.println("IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
         System.out.println("ParserConfigurationException " + e.getMessage());
    }  catch (TransformerConfigurationException e) {
         System.out.println("TransformerConfigurationException "+ e.getMessage());
    } catch (TransformerException e) {
         System.out.println("TransformerException " + e.getMessage());
    }catch (Exception e) {
        e.printStackTrace();
    }

    return "redirect:/index.html";
}

@RequestMapping("/download/{documentId}")
public String download(@PathVariable("documentId") Integer documentId,
        HttpServletResponse response) {

    File doc = documentDao.get(documentId);

    try {
        response.setHeader("Content-Disposition", "inline;filename=\""
                + doc.getFilename() + "\"");
        OutputStream out = response.getOutputStream();
        response.setContentType(doc.getContentType());
        IOUtils.copy(doc.getContent().getBinaryStream(), out);
        out.flush();
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return null;
}

@RequestMapping("/remove/{documentId}")
public String remove(@PathVariable("documentId") Integer documentId) {

    documentDao.remove(documentId);

    return "redirect:/index.html";
}

}

也许我需要与 Controller 做一些事情。 任何想法、解决方案或建议都非常受欢迎和赞赏。

最诚挚的问候,

尤努斯

最佳答案

我认为这是给出该错误的行。

InputStream input = (InputStream) file;

您无法将 MultipartFile 对象 file 直接转换为 InputStream。您需要使用 MultipartFilegetInputStream() 方法,如下所示:-

InputStream input = file.getInputStream();

关于java - 将上传的文件(xls)转换为xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16351142/

相关文章:

xml - 使用 xslt 将 xml 文档导入 open office

java - 请求范围的 ApplicationEventListener 无法接收事件

java - JVM 命令启动选项重复

java - 解码 UTF-8 字符串,然后将其编码为斯洛伐克字母表的 8859-2

java - Hash Map 的用法和思路

XML SOAP 消息的 Java HTTP post

javascript - 在 indesign 脚本中使用 xml 内容标记

java - 如何使用外部绑定(bind)覆盖 JAXB 中的默认名称?

Spring Boot 测试 MockMvc 执行后 - 不工作

Hibernate内存数据+数据库