Как экспортировать файл Excel при загрузке Spring с помощью Angular 2?JAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Как экспортировать файл Excel при загрузке Spring с помощью Angular 2?

Сообщение Anonymous »

В моем проекте мне нужно экспортировать данные о клиентах в файл Excel. Я использую структуру таблицы с помощью сборки Hybernate.

мой контроллер такой:

Код: Выделить всё

 @RequestMapping(value="exporttoexcel", method= RequestMethod.GET, produces={ MediaType.APPLICATION_JSON_VALUE })
public void  getMyData(HttpServletRequest request, HttpServletResponse response) throws Exception {
List listCourses = new ArrayList();
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 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 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 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 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 courses = (List) 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()));
}
}
}
И Курс такой:

Код: Выделить всё

public class Course {
int Id;
String Name;
Date Date;
// Getter and setter
}
Мой список по части пользовательского интерфейса выглядит следующим образом:

Код: Выделить всё

All Customers
[i][/i]
[i][/i]

код службы следующий:

Код: Выделить всё

  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.

Подробнее здесь: https://stackoverflow.com/questions/414 ... -angular-2
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»