Spring Excel Example
@RequestMapping(value = "/excel", method = RequestMethod.GET)
public void handleRequestInternal(HttpServletRequest request,
HttpServletResponse response,
OutputStream outputStream ) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=file.xls");
//ModelAndView model = new ModelAndView("excel");
// Creating an instance of HSSFWorkbook.
HSSFWorkbook workbook = new HSSFWorkbook();
// Create two sheets in the excel document and name it First Sheet and
// Second Sheet.
HSSFSheet firstSheet = workbook.createSheet("FIRST SHEET");
HSSFSheet secondSheet = workbook.createSheet("SECOND SHEET");
// Manipulate the firs sheet by creating an HSSFRow wich represent a
// single row in excel sheet, the first row started from 0 index. After
// the row is created we create a HSSFCell in this first cell of the row
// and set the cell value with an instance of HSSFRichTextString
// containing the words FIRST SHEET.
HSSFRow rowA = firstSheet.createRow(0);
HSSFCell cellA = rowA.createCell((short) 0);
cellA.setCellValue(new HSSFRichTextString("FIRST SHEET"));
HSSFRow rowB = secondSheet.createRow(0);
HSSFCell cellB = rowB.createCell((short) 0);
cellB.setCellValue(new HSSFRichTextString("SECOND SHEET"));
// To write out the workbook into a file we need to create an output
// stream where the workbook content will be written to.
FileOutputStream fos = null;
try {
workbook.write(outputStream);
outputStream.flush();
fos = new FileOutputStream(new File("c:/CreateExcelDemo.xls"));
workbook.write(fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
댓글
댓글 쓰기
질문이나 의견은 요기에 남겨주세요 ^^,,