我想使用Apache POI创建一个受密码保护的excel文件,然后将其下载到Servlet.getOutputStream()

时间:2016-12-28 02:08:06

标签: java apache-poi

我无权将文件保存到文件系统。我在网上找到的所有例子都使用文件系统。

我想在内存中创建工作簿,如下所示:

HSSFWorkbook workbook = new HSSFWorkbook();

将数据写入工作簿...... 使工作簿密码受到保护。?

然后将工作簿写入输出流,如下所示:

workbook.write(servlet.getOutputStream());

1 个答案:

答案 0 :(得分:0)

我能够使用HttpServlet和HSSFWorkbook .xls文件 - WorkbookServlet.java:

package com.joshden;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

@WebServlet("/workbook")
public class WorkbookServlet extends HttpServlet {
    private static final long serialVersionUID = 4087954595439224462L;
    private static final String password = "foobar1";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment; filename=password_protected.xls");
        createAndWriteEncryptedWorkbook(response.getOutputStream());
    }

    private void createAndWriteEncryptedWorkbook(OutputStream requestOutputStream) throws IOException {
        HSSFWorkbook workbook = new HSSFWorkbook();
        populateWorkbook(workbook);
        Biff8EncryptionKey.setCurrentUserPassword(password);
        workbook.write(requestOutputStream);
        workbook.close();
    }

    private void populateWorkbook(Workbook workbook) {
        workbook.createSheet("TestSheet");
        // TODO create other sheets, populate cell values
    }

}

对于/ workbook的请求,servlet使用名为TestSheet的工作表在内存中创建HSSF工作簿。密码设置为“foobar1”。它会提示浏览器将其下载为名为password_protected.xls的文件。

另见Apache POI - Encryption support。自Apache POI 3.16起,二进制格式(HSSF)的加密才可用。在撰写本文时,3.16还没有发布,我在我的例子中使用了3.16-beta1。

encyprtion支持指南还提供了创建加密(密码保护).xlsx(XSSF)文件的信息。这是我创建的一个示例,它将提示文件名为password_protected.xlsx:

package com.joshden;

import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.crypt.EncryptionInfo;
import org.apache.poi.poifs.crypt.EncryptionMode;
import org.apache.poi.poifs.crypt.Encryptor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

@WebServlet("/workbook")
public class WorkbookServlet extends HttpServlet {
    private static final long serialVersionUID = 4087954595439224462L;
    private static final String password = "foobar1";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.addHeader("Content-Disposition", "attachment; filename=password_protected.xlsx");
        createAndWriteEncryptedWorkbook(response.getOutputStream());
    }

    private void createAndWriteEncryptedWorkbook(OutputStream requestOutputStream) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        OPCPackage opc = workbook.getPackage();
        populateWorkbook(workbook);

        try {
            POIFSFileSystem fileSystem = new POIFSFileSystem();
            opc.save(getEncryptingOutputStream(fileSystem, password));
            fileSystem.writeFilesystem(requestOutputStream);
        }
        finally {
            workbook.close();
        }
    }

    private void populateWorkbook(Workbook workbook) {
        workbook.createSheet("TestSheet");
        // TODO create other sheets, populate cell values
    }

    private OutputStream getEncryptingOutputStream(POIFSFileSystem fileSystem, String password) throws IOException {
        EncryptionInfo encryptionInfo = new EncryptionInfo(EncryptionMode.agile);
        Encryptor encryptor = encryptionInfo.getEncryptor();
        encryptor.confirmPassword(password);

        try {
            return encryptor.getDataStream(fileSystem);
        } 
        catch (GeneralSecurityException e) {
            // TODO handle this better
            throw new RuntimeException(e);
        }
    }

}