下载使用Apache Poi生成的excel文件

时间:2016-04-27 18:06:44

标签: java apache-poi export-to-excel

我正在使用Apache Poi创建一个Excel文件,然后下载它。我的问题是,当我尝试打开文件时,我收到错误:

  

您尝试打开的文件' workbook.xls',有所不同   格式比文件扩展名指定的格式。验证文件是否正确   没有损坏,并且在打开文件之前来自受信任的来源。做   你想现在打开文件吗?

当我单击是时,下载的文件有奇怪的字符,格式不正确。

如果我保存文件而不是下载文件,则会正确生成。

这是我的代码:

从angular:

调用servlet
NetWorkModel.sendRequestOpiniumServlet("review", metodoPeticion, dataEntrada, "EXCEL", function (response) {
            if (response.Status === 'KO') {
                NotificacionModel.mostrarNotificacion({
                    title: 'Opinium',
                    message: 'Error. No se ha podido exportar a Excel.',
                    size: 'large',//small,large
                    type: 'error',//error,notice,warning
                    duration: '2000'
                });  
            }
            callback();
        }); 
netWorkModel.js中的

sendRequestOpiniumServlet方法:

this.sendRequestOpiniumServlet = function (servicioPeticion, metodoPeticion, dataEntrada, tipoPeticion, callback, $files) {

        //Reset de la request y ponemos los valores del ususario
        self.resetValue();
        //Ponemos datos de la peticion
        self.request.Servicio = servicioPeticion;
        self.request.Metodo = metodoPeticion;
        self.request.Entrada = dataEntrada;

        var tipo = "";
        if (tipoPeticion === "JSON") {
            tipo = "";
            self.request.Tipo = tipo;
            self.sendHttpJSON(self.servers.urlOpinium, function (data) {
                callback(data);
            });
        } else if (tipoPeticion === "EXCEL") {
            tipo = "EXCEL";
            self.request.Tipo = tipo;
            self.sendHttpExcel(self.servers.urlOpinium, function (data) {
                callback(data);
            });                
        } else if (tipoPeticion === "CSV") {
            tipo = "CSV";
            self.request.Tipo = tipo;
            var nombreCSV = servicioPeticion;
            self.sendHttpCSV(nombreCSV, self.servers.urlOpinium, function (data) {
                callback(data);
            });
        } else if (tipoPeticion === "IMG") {
            tipo = "IMG";
            self.request.Tipo = tipo;
            self.sendHttpIMG(self.servers.urlOpinium, $files, function (data) {
                callback(data);
            });
        }


    };

netWorkModel.js中的sendHttpExcel方法:

 this.sendHttpExcel = function (urlService, callback) {

    $http({
        method: self.servers.method, url: urlService,
        data: JSON.stringify(self.request),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, cfg) {


        if (DescargaExcelModel.createExcel('bookwork', data)) {
            NotificacionModel.mostrarNotificacion({
                title: 'Intranet: Exportación',
                message: 'Fichero exportado correctamente',
                size: 'large', //small,large
                type: 'notice', //error,notice,warning
                duration: '5000'
            });
            callback(true);
        } else {
            NotificacionModel.mostrarNotificacion({
                title: 'Intranet: Exportación',
                message: 'Error en el contenido del fichero',
                size: 'large', //small,large
                type: 'error', //error,notice,warning
                duration: '5000'
            });
            callback(false);
        }


    }).error(function (data, status, headers, cfg) {
        NotificacionModel.mostrarNotificacion({
            title: 'Servidor: ' + urlService,
            message: 'Error en la conexión con el servidor',
            size: 'xlarge', //small,large,xlarge
            type: 'error', //error,notice,warning
            duration: '5000'
        });
        callback(false);

    });         

};

DescargaExcelModel.js中的createExcel方法:

angular.module("app.utils").service("DescargaExcelModel", ['$timeout', function($timeout) {
        var self = this;

        this.element = angular.element(  '#link_exportar_file_csv_temp'  );

        this.setElement = function(elem) {
            self.element = elem;
        };


        this.excelToURL = function(content) {
            var blob;
            blob = new Blob(["\ufeff",content], {type: 'application/vnd.ms-excel;charset=UTF-8',encoding:"UTF-8"});
            return (window.URL || window.webkitURL).createObjectURL(blob);
        };

        this.sanitizeExcelName = function(name) {
            if (/^[A-Za-z0-9]+\.xls$/.test(name)) {
                return name;
            }
            if (/^[A-Za-z0-9]+/.test(name)) {
                return name + ".xls";
            } else {
                return "file.xls";
            }
        };
        this.revoke = function(url) {
            return (window.URL || window.webkitURL).revokeObjectURL(url);
        };
        this.on = function(ele) {
            var e = document.createEvent("MouseEvent");
            e.initMouseEvent("click", false, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            ele.dispatchEvent(e);
        };

        this.createExcel = function(titleFile, dataExcel) {

            var a_href, content, title, url;
            content = dataExcel;
            title = titleFile;


            if (!(content !== null) && !(title !== null)) {
                return false;
            }

            title = self.sanitizeExcelName(title);
            url = self.excelToURL(content);

            self.element.append("<a download=\"" + title + "\" href=\"" + url + "\"></a>");
            a_href = self.element.find('a')[0];

            self.on(a_href);
//            $timeout(function() {
//                self.revoke(url);
//            });
//
            self.element[0].removeChild(a_href);
//            angular.element("#link_exportar_file_csv_temp").removeChild(a_href);
            return true;
        };

    }]);

我的servlet代码:

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

                      .
                      .
                      .

                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=bookwork.xls");
                ExportUtils.convertToWorkBook(request, response, respuesta.getDatos());

                      .
                      .
                      .
}

ExportUtils.java中的convertToWorkBook方法:

public static void convertToWorkBook(HttpServletRequest request, HttpServletResponse response, List<Object> data) {


    OutputStream out = response.getOutputStream();

    Workbook workbook = new HSSFWorkbook();


    // ... Here i create my excel workbook

    workbook.write(out); 
    workbook.close();
    out.flush();
    out.close();

}

我做错了什么?

0 个答案:

没有答案