Here I will provide solution for common situation, when you need to export some kind of Excel doc (e.g. report) from web application built on Spring MVC framework. It's made with help of Apache POI library, which generates spreadsheet.
In Spring config spring-excel-views.xml it should be declared like that:
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.springframework.web.servlet.view.document.AbstractExcelView;
/**
* @author Maxim Baev
*/
public class ExcelRecipeWishListView extends AbstractExcelView {
@Override
protected void buildExcelDocument(Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map productMap = (Map) model.get("productMap");
//create a wordsheet
HSSFSheet sheet = workbook.createSheet("Product list");
HSSFRow header = sheet.createRow(0);
CellStyle cellStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
cellStyle.setFont(font);
Cell headerCell1 = header.createCell(0);
headerCell1.setCellStyle(cellStyle);
headerCell1.setCellValue("Product");
Cell headerCell2 = header.createCell(1);
headerCell2.setCellStyle(cellStyle);
headerCell2.setCellValue("Quantity");
int rowNum = 1;
for (Map.Entry entry : productMap.entrySet()) {
//create the row data
HSSFRow row = sheet.createRow(rowNum++);
row.createCell(0).setCellValue(entry.getKey());
row.createCell(1).setCellValue(entry.getValue());
}
response.setHeader("Content-Disposition", "attachment; filename=\"product_list.xls\"");
}
}
In Spring config spring-excel-views.xml it should be declared like that:
Then used in main config:
And finally on your controller:
@RequestMapping(value = "/xls_wish_list")
public ModelAndView exportWishListToExcel(HttpSession session) {
List recipes = null;
Map productMap = null;
if (session.getAttribute("recipeIds") != null) {
Set recipeIdSet = (Set) session.getAttribute("recipeIds");
List recipeIds = new ArrayList(recipeIdSet);
List searchCriteria = new ArrayList(1);
searchCriteria.add(new IdSearchCriterion(recipeIds));
recipes = recipeService.getRecipes(searchCriteria);
productMap = makeProductMap(recipes);
}
//return excel view
Map model = new HashMap(1);
model.put("productMap", productMap);
return new ModelAndView(new ExcelRecipeWishListView(), model);
}
Комментариев нет:
Отправить комментарий