I have problem when i want to export my data to excel using spring boot web.
I am using Thymeleaf as template engine (auto configured by spring boot). But when I add Xm
With Spring Boot you don't need any extra configuration to generate an excel file.
Create a controller returning a ModelAndView with an AbstractExcelView:
@Controller
public class MyController {
@RequestMapping(value="/myexcel", method=RequestMethod.GET)
public ModelAndView getMyData(HttpServletRequest request, HttpServletResponse response) throws SQLException{
Map model = new HashMap();
//Sheet Name
model.put("sheetname", "TestSheetName");
//Headers List
List headers = new ArrayList();
headers.add("Column1");
headers.add("Column2");
headers.add("Column3");
model.put("headers", headers);
//Results Table (List
Then build your AbstractExcelView like:
public class MyExcelView extends AbstractExcelView
{
@SuppressWarnings("unchecked")
protected void buildExcelDocument(Map model,
HSSFWorkbook workbook,
HttpServletRequest request,
HttpServletResponse response)
{
//VARIABLES REQUIRED IN MODEL
String sheetName = (String)model.get("sheetname");
List headers = (List)model.get("headers");
List> results = (List>)model.get("results");
List numericColumns = new ArrayList();
if (model.containsKey("numericcolumns"))
numericColumns = (List)model.get("numericcolumns");
//BUILD DOC
HSSFSheet sheet = workbook.createSheet(sheetName);
sheet.setDefaultColumnWidth((short) 12);
int currentRow = 0;
short currentColumn = 0;
//CREATE STYLE FOR HEADER
HSSFCellStyle headerStyle = workbook.createCellStyle();
HSSFFont headerFont = workbook.createFont();
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
headerStyle.setFont(headerFont);
//POPULATE HEADER COLUMNS
HSSFRow headerRow = sheet.createRow(currentRow);
for(String header:headers){
HSSFRichTextString text = new HSSFRichTextString(header);
HSSFCell cell = headerRow.createCell(currentColumn);
cell.setCellStyle(headerStyle);
cell.setCellValue(text);
currentColumn++;
}
//POPULATE VALUE ROWS/COLUMNS
currentRow++;//exclude header
for(List result: results){
currentColumn = 0;
HSSFRow row = sheet.createRow(currentRow);
for(String value : result){//used to count number of columns
HSSFCell cell = row.createCell(currentColumn);
if (numericColumns.contains(headers.get(currentColumn))){
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(NumUtils.extractDoubleOrZero(value));
} else {
HSSFRichTextString text = new HSSFRichTextString(value);
cell.setCellValue(text);
}
currentColumn++;
}
currentRow++;
}
}
}