java後端匯出excel檔案
阿新 • • 發佈:2019-02-12
學習使用Apache的poi做下記錄
HSSFWorkbook workbook = new HSSFWorkbook();//建立一個工作簿
HSSFSheet sheet = workbook.createSheet();
//設定行寬度
sheet.setColumnWidth(0, 20* 256);
sheet.setColumnWidth(1, 20* 256);
sheet.setColumnWidth(2, 50* 256);
sheet.setColumnWidth(3, 20* 256 );
//凍結第一行
sheet.createFreezePane( 0, 1, 0, 1 );
//第一行標題格式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setVerticalAlignment(VerticalAlignment.CENTER);
titleStyle.setAlignment(HorizontalAlignment.CENTER);
Font fontTitle = workbook.createFont();
fontTitle.setBold(true );//加粗
fontTitle.setFontHeightInPoints(12);//設定字號
titleStyle.setFont(fontTitle);
//內容格式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
cellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
HSSFRow row = sheet.createRow(0);//建立一行
HSSFCell cell1 = row.createCell(0);//建立一列
HSSFCell cell2 = row.createCell(1);
HSSFCell cell3 = row.createCell(2);
HSSFCell cell4 = row.createCell(3);
cell1.setCellStyle(titleStyle);
cell2.setCellStyle(titleStyle);
cell3.setCellStyle(titleStyle);
cell4.setCellStyle(titleStyle);
cell1.setCellType(CellType.STRING);
cell2.setCellType(CellType.STRING);
cell3.setCellType(CellType.STRING);
cell4.setCellType(CellType.STRING);
cell1.setCellValue("姓名");
cell2.setCellValue("性別");
cell3.setCellValue("年齡");
cell4.setCellValue("部門");
String filename = "員工資訊.xls";//檔名字
try {
filename = new String( filename.getBytes("gb2312"), "ISO8859-1" );
response.setHeader("Content-Disposition", "attachment;filename="+filename);
response.setContentType("application/x-download");
OutputStream outputStream = response.getOutputStream();
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
}