import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWriter extends HttpServlet {
private void writeExcel(List<Book> listBook, String excelFilePath)
throws IOException {
Workbook workbook = getWorkbook(excelFilePath);
Sheet sheet = workbook.createSheet();
int rowCount = 0;
for (Book aBook : listBook) {
Row row = sheet.createRow(++rowCount);
writeBook(aBook, row);
}
try (FileOutputStream outputStream = new FileOutputStream(new File(
excelFilePath))) {
workbook.write(outputStream);
}
}
private void writeBook(Book aBook, Row row) {
Cell cell = row.createCell(1);
cell.setCellValue(aBook.getTitle());
cell = row.createCell(2);
cell.setCellValue(aBook.getAuthor());
cell = row.createCell(3);
cell.setCellValue(aBook.getPrice());
}
private List<Book> getListBook() {
Book book1 = new Book("Head Java", "Anot Serria", 79);
Book book2 = new Book("Effective Java 1", "Bnot Bloch", 36);
Book book3 = new Book("Clean Code 1", "Cnot Martin", 42);
Book book4 = new Book("Thinking in Java 2", "D Eckel", 35);
List<Book> listBook = Arrays.asList(book1, book2, book3, book4);
return listBook;
}
private Workbook getWorkbook(String excelFilePath) throws IOException {
Workbook workbook = null;
if (excelFilePath.endsWith("xlsx")) {
workbook = new XSSFWorkbook();
} else if (excelFilePath.endsWith("xls")) {
workbook = new HSSFWorkbook();
} else {
throw new IllegalArgumentException(
"The specified file is not Excel file");
}
return workbook;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String excelFilePath = "C:\\Users\\A7369241\\Desktop\\Temp.xls";
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
+ excelFilePath);
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());
}
}
}
public class Book {
private String title,author;
private float price;
public Book(String title, String author, float price) {
super();
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
Таким образом, в файле ExcelWriter, как указано, файл должен быть загружен по указанному пути к файлу.В браузере создается всплывающее окно, но открываемый файл Excel поврежден и не содержит жестко закодированных данных.С другой стороны, данные находятся в файле Excel в указанном месте, которое не отображается во всплывающем окне, и ФАЙЛ ОТПРАВЛЕНИЙ В РЕЖИМЕ СОВМЕСТИМОСТИ.
Может кто-нибудь, пожалуйста, помогите мне с этим.