引用文章地址:https://www.cnblogs.com/caiba/p/9118259.html
先在pom.xml加上包
<!-- poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>RELEASE</version>
</dependency>
service代碼
public void exportExcel(HttpServletResponse response) throws Exception {
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("碳排放月報表(納入交易)");
createTitle(workbook,sheet);
HSSFRow row = sheet.createRow(2);
row.setHeightInPoints(18);
row.createCell(0).setCellValue("裝機容量");
row.createCell(1).setCellValue("MW");
row.createCell(2).setCellValue("11");
row.createCell(3).setCellValue("12");
row.createCell(4).setCellValue("23");
String fileName = "導出excel例子.xls";
//生成excel文件
buildExcelFile(fileName, workbook);
//瀏覽器下載excel
buildExcelDocument(fileName,workbook,response);
}
//創(chuàng)建表頭
private void createTitle(HSSFWorkbook workbook,HSSFSheet sheet){
//合并單元格
//參數(shù)1:起始行 參數(shù)2:終止行 參數(shù)3:起始列 參數(shù)4:終止列
CellRangeAddress region1 = new CellRangeAddress(0, 1, 0, 0);
sheet.addMergedRegion(region1);
HSSFRow row = sheet.createRow(0);
//設置行高
row.setHeightInPoints(18);
//設置列寬度
sheet.setColumnWidth(0,30*256);
//設置為居中加粗
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
HSSFCell cell;
cell = row.createCell(0);
cell.setCellValue("指標名稱");
cell.setCellStyle(style);
cell = row.createCell(1);
cell.setCellValue("單位");
cell.setCellStyle(style);
cell = row.createCell(2);
cell.setCellValue("本月實際");
cell.setCellStyle(style);
cell = row.createCell(5);
cell.setCellValue("全廠小計");
cell.setCellStyle(style);
}
//生成excel文件
public void buildExcelFile(String filename,HSSFWorkbook workbook) throws Exception{
FileOutputStream fos = new FileOutputStream(filename);
workbook.write(fos);
fos.flush();
fos.close();
}
//瀏覽器下載excel
public void buildExcelDocument(String filename,HSSFWorkbook workbook,HttpServletResponse response) throws Exception{
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename, "utf-8"));
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
}
最后編輯于 :
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者