簡體   English   中英

如何使用 Angular 2 在 Spring Boot 中導出 excel 文件?

[英]How to export a excel file in Spring boot using Angular 2?

在我的項目中,我需要將客戶數據導出到 excel 文件中。 我正在使用使用 Hybernate 構建的表結構。

我的控制器是:

 @RequestMapping(value="exporttoexcel", method= RequestMethod.GET, produces={ MediaType.APPLICATION_JSON_VALUE })
    public void  getMyData(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Course> listCourses = new ArrayList<Course>();
        listCourses.add(new Course(1, "Polarfrosch100", new Date()));
        listCourses.add(new Course(2, "Polarfrosch101", new Date()));
        listCourses.add(new Course(3, "Polarfrosch102", new Date()));
        HashMap<String, Object> model = new HashMap<>();
        model.put("courses", listCourses);
        new ExcelUtilsHelper().renderMergedOutputModel(model, request, response);
    }

我的幫助文件如下:

public class ExcelUtilsHelper {


    private static final DateFormat DATE_FORMAT = DateFormat.getDateInstance(DateFormat.SHORT);

    private String contentType;

    public ExcelUtilsHelper() {
        this.setContentType("application/vnd.ms-excel");
    }

    public final void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Workbook workbook = this.createWorkbook(model, request);
        this.buildExcelDocument(model, workbook, request, response);
        response.setContentType(this.getContentType());
        this.renderWorkbook(workbook, response);
    }

    protected Workbook createWorkbook(Map<String, Object> model, HttpServletRequest request) {
        return new HSSFWorkbook();
    }

    protected void renderWorkbook(Workbook workbook, HttpServletResponse response) throws IOException {
        ServletOutputStream out = response.getOutputStream();
        workbook.write(out);
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType() {
        return contentType;
    }

    protected void buildExcelDocument(Map<String, Object> model,
                                      Workbook workbook,
                                      HttpServletRequest request,
                                      HttpServletResponse response) throws Exception {

        // change the file name
        response.setHeader("Content-Disposition", "attachment; filename=\"my-xls-file.xls\"");

        @SuppressWarnings("unchecked")
        List<Course> courses = (List<Course>) model.get("courses");

        // create excel xls sheet
        Sheet sheet = workbook.createSheet("Spring MVC AbstractXlsView");

        // create header row
        Row header = sheet.createRow(0);
        header.createCell(0).setCellValue("ID");
        header.createCell(1).setCellValue("Name");
        header.createCell(2).setCellValue("Date");

        // Create data cells
        int rowCount = 1;
        for (Course course : courses){
            Row courseRow = sheet.createRow(rowCount++);
            courseRow.createCell(0).setCellValue(course.getId());
            courseRow.createCell(1).setCellValue(course.getName());
            courseRow.createCell(2).setCellValue(DATE_FORMAT.format(course.getDate()));
        }
    }
}

並且Cource是:

public class Course {
    int Id;
    String Name;
    Date Date;
// Getter and setter 
}

我在 UI 部分的列表如下:

<div class="panel-heading">
    <h6 class="panel-title">All Customers</h6>
    <button (click)="addCustomer()" class="btn btn-xs  bg-primary" title="Add"><i class="glyphicon glyphicon-edit"></i></button>
    <button (click)="exportToExcel()" class="btn btn-xs  bg-danger" title="Add"><i class="glyphicon glyphicon-edit"></i></button>
  </div>

服務代碼如下:

  exportToExcel(){
    console.log("in exportToExcel");
    this.customerService.getCustomersExcelData().subscribe(result => {
        console.log("DataResult");
        console.log(result)
      },
      error => {
        console.log(error);
      });
  }

  getCustomersExcelData(){
    return this.http.get(ApiConfig.apiRoot+ApiConfig.excelDataCustomer)
      .map((response: Response) => {
        this.downloadFile(response),
          error => console.log("Error downloading the file."),
          () => console.info("OK");
      }).catch(this.commonMethods.handleError);
  }

當我運行它時,它給出了以下輸出:

Response with status: 200 OK for URL: http://localhost:9966/api/customer/exporttoexcel

問題是,我無法以 excel 格式導出給定的數據。

在您的控制器聲明中,只需刪除producesHttpServletRequest request Controller 的簡單示例如下所示:

@RequestMapping(value = "/export", method = RequestMethod.POST)
public void export(HttpServletResponse response) {
    List<Person> persons = personRepository.findAll();
    List<String> headers = Arrays.asList("First Name", "Last Name");
    try {
        response.addHeader("Content-disposition", "attachment; filename=People.xlsx");
        response.setContentType("application/vnd.ms-excel");
        new SimpleExporter().gridExport(headers, persons, "firstName, lastName, ", response.getOutputStream());
        response.flushBuffer();
    } catch (IOException e) {
        log.warn(e.getMessage(), e);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM