1 回答
TA贡献1798条经验 获得超3个赞
尝试这个:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ExcelWriter excelWriter = new ExcelWriter();
List<Book> listBook = excelWriter.getListBook();
excelWriter.writeExcel(listBook, excelFilePath);
System.out.println("Excel file written successfully");
String excelFilePath = "C:\\Users\\A7369241\\Desktop\\Temp.xls";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=temp.xls");
OutputStream out = response.getOutputStream();
try (FileInputStream in = new FileInputStream(file)) {
byte[] buffer = new byte[4096];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
out.flush();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
如果您只想创建 excel,则无需使用响应。并且文件名应该是 xlsx 类型。这就是您收到兼容模式消息的原因。
try {
String excelFilePath = "C:\\Users\\A7369241\\Desktop\\Temp.xlsx";
ExcelWriter excelWriter = new ExcelWriter();
List<Book> listBook = excelWriter.getListBook();
excelWriter.writeExcel(listBook, excelFilePath);
System.out.println("Excel file written successfully");
} catch (Exception e) {
System.out.println(e.getMessage());
}
如果您仍然有问题,则意味着您的 servlet 无法正常工作。只需尝试使用 main 方法和 main 方法类型创建类:
String excelFilePath = "D:\\Temp.xls";
Test excelWriter = new Test();
List<Book> listBook = excelWriter.getListBook();
try {
excelWriter.writeExcel(listBook, excelFilePath);
System.out.println("Excel file written successfully");
} catch (IOException e) {
e.printStackTrace();
}
添加回答
举报