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());
}
因此,在 ExcelWriter 文件中,按照指定文件应下载到指定的文件路径。浏览器中会生成一个弹出窗口,但打开的 Excel 文件已损坏,并且未存储硬编码数据。另一方面,数据位于指定位置的 Excel 文件中,不会出现在弹出窗口中,并且 EXCEL 文件处于兼容模式。
呼如林
相关分类