Spring Boot Web應用程式下載Excel檔案 - simplesolution

banq發表於2019-12-20

在本文中,我們將逐步建立Spring Boot Web應用程式並實現下載Excel檔案功能。我使用Spring Tool Suite 4建立用於演示的應用程式和程式碼編輯器。點選標題見原文圖示。

如果您正在使用Maven,則在xml下面新增:

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

實現ExcelFileExporter類:

public class ExcelFileExporter {
    
    public static ByteArrayInputStream contactListToExcelFile(List<Customer> customers) {
        try(Workbook workbook = new XSSFWorkbook()){
            Sheet sheet = workbook.createSheet("Customers");
            
            Row row = sheet.createRow(0);
            CellStyle headerCellStyle = workbook.createCellStyle();
            headerCellStyle.setFillForegroundColor(IndexedColors.AQUA.getIndex());
            headerCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            // Creating header
            Cell cell = row.createCell(0);
            cell.setCellValue("First Name");
            cell.setCellStyle(headerCellStyle);
            
            cell = row.createCell(1);
            cell.setCellValue("Last Name");
            cell.setCellStyle(headerCellStyle);
    
            cell = row.createCell(2);
            cell.setCellValue("Mobile");
            cell.setCellStyle(headerCellStyle);
    
            cell = row.createCell(3);
            cell.setCellValue("Email");
            cell.setCellStyle(headerCellStyle);
            
            // Creating data rows for each customer
            for(int i = 0; i < customers.size(); i++) {
                Row dataRow = sheet.createRow(i + 1);
                dataRow.createCell(0).setCellValue(customers.get(i).getFirstName());
                dataRow.createCell(1).setCellValue(customers.get(i).getLastName());
                dataRow.createCell(2).setCellValue(customers.get(i).getMobileNumber());
                dataRow.createCell(3).setCellValue(customers.get(i).getEmail());
            }
    
            // Making size of column auto resize to fit with data
            sheet.autoSizeColumn(0);
            sheet.autoSizeColumn(1);
            sheet.autoSizeColumn(2);
            sheet.autoSizeColumn(3);
            
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            workbook.write(outputStream);
            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
    }
}

對外控制類:

@Controller
public class DownloadExcelController {
    
    @RequestMapping("/")
    public String index() {
        return "index";
    }
    
    @GetMapping("/download/customers.xlsx")
    public void downloadCsv(HttpServletResponse response) throws IOException {
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=customers.xlsx");
        ByteArrayInputStream stream = ExcelFileExporter.contactListToExcelFile(createTestData());
        IOUtils.copy(stream, response.getOutputStream());
    }

    private List<Customer> createTestData(){
        List<Customer> customers = new ArrayList<Customer>();
        customers.add(new Customer("Vernon", "Barlow", "0123456789", "test1@simplesolution.dev"));
        customers.add(new Customer("Maud", "Brock", "0123456788", "test2@simplesolution.dev"));
        customers.add(new Customer("Chyna", "Cowan", "0123456787", "test3@simplesolution.dev"));
        customers.add(new Customer("Krisha", "Tierney", "0123456786", "test4@simplesolution.dev"));
        customers.add(new Customer("Sherry", "Rosas", "0123456785", "test5@simplesolution.dev"));
        return customers;
    }
}

訪問:http://localhost:8080/download/customers.xlsx

Spring Boot Web應用程式下載Excel檔案 - simplesolution

原始碼下載

相關文章