在Java中,可以使用Apache POI库来生成Excel文件并返回其内容作为字节流。 Apache POI是一个开源的Java库,可以读写Microsoft Office格式的文档。
首先,您需要下载Apache POI库并将其引入您的项目。 然后,您可以使用以下代码示例来生成一个简单的Excel文件:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelGenerator {
public static byte[] generateExcelFile() throws IOException {
try (XSSFWorkbook workbook = new XSSFWorkbook(); ByteArrayOutputStream out = new ByteArrayOutputStream();) {
XSSFSheet sheet = workbook.createSheet("Sheet1");
Object[][] data = {
{"Name", "Age", "Gender"},
{"John", 25, "Male"},
{"Jane", 30, "Female"},
{"Jim", 35, "Male"}
int rowNum = 0;
for (Object[] datatype : data) {
Row row = sheet.createRow(rowNum++);
int colNum = 0;
for (Object field : datatype) {
Cell cell = row.createCell(colNum++);
if (field instanceof String) {
cell.setCellValue((String) field);
} else if (field instanceof Integer) {
cell.setCellValue((Integer) field);
workbook.write(out);
return out.toByteArray();
最后,您可以使用以下代码将生成的Excel文件流返回给客户端:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExcelDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
byte[] excelContent = ExcelGenerator.generateExcelFile();
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setHeader("Content-Disposition", "attachment; filename=example.xlsx");
response.setContentLength(excelContent.length);
try (ServletOutputStream out = response.getOutputStream();) {
out.write(excelContent);