gpt4 book ai didi

java - 在 Spring MVC 中使用 Java 从 Web Explorer 创建和下载 Excel

转载 作者:行者123 更新时间:2023-11-30 08:09:04 24 4
gpt4 key购买 nike

我想从 Java 中的方法创建一个 Excel 文件并在浏览器中下载它。

我在 this post 上找到了一个例子您在其中创建 Excel 文件,但我想创建 .xls 文件并从 Web 浏览器下载它。

我该怎么做?

最佳答案

我终于找到了解决问题的方法...!!

这对我有用:

       @RequestMapping("/downloadFile")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) {

try {

String fileName = "C:/excelFile.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("firstSheet");

HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("No.");
rowhead.createCell(1).setCellValue("Name");
rowhead.createCell(2).setCellValue("Address");
rowhead.createCell(3).setCellValue("Email");

HSSFRow row = sheet.createRow((short) 1);
row.createCell(0).setCellValue("1");
row.createCell(1).setCellValue("Carlos");
row.createCell(2).setCellValue("Costa Rica");
row.createCell(3).setCellValue("myNameh@gmail.com");

FileOutputStream fileOut = new FileOutputStream(fileName);
workbook.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");

//Code to download
File fileToDownload = new File(fileName);
InputStream in = new FileInputStream(fileToDownload);

// Gets MIME type of the file
String mimeType = new MimetypesFileTypeMap().getContentType(fileName);

if (mimeType == null) {
// Set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
System.out.println("MIME type: " + mimeType);

// Modifies response
response.setContentType(mimeType);
response.setContentLength((int) fileToDownload.length());

// Forces download
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileToDownload.getName());
response.setHeader(headerKey, headerValue);

// obtains response's output stream
OutputStream outStream = response.getOutputStream();

byte[] buffer = new byte[4096];
int bytesRead = -1;

while ((bytesRead = in.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}

in.close();
outStream.close();

System.out.println("File downloaded at client successfully");


} catch (Exception ex) {
System.out.println(ex);
}
}

关于java - 在 Spring MVC 中使用 Java 从 Web Explorer 创建和下载 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32744166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com