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

时间:2013-05-03 03:32:12

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

我一直在创建一个可以将上传的文件转换为xml文件的应用。上传的文件是xls文件。 我用xache-poi把xls转换器变成了xml。 我也做了上传和下载功能。 当上传xls文件时,它应该由控制器转换为xml并保存在数据库(Mysql)中,但它失败了。 该应用程序返回一个异常:

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

这是控制器:

@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";
}

}

也许我有一些与控制器有关的事情。 任何想法,解决方案或建议都受到了极大的欢迎和赞赏。

最诚挚的问候,

努斯

1 个答案:

答案 0 :(得分:2)

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

InputStream input = (InputStream) file;

您无法将MultipartFile对象file直接投射到InputStream。您需要使用getInputStream()的{​​{1}}方法,如下所示: -

MultipartFile