您的位置:首页 > 其它

将数据导出到excel与日期格式的设置

2009-09-01 11:54 537 查看
//将数据导出到excel

private HSSFWorkbook createExcel(List<Logs> list){

HSSFWorkbook wb = new HSSFWorkbook();

HSSFSheet sheet = wb.createSheet("Audit Logs");

//head style

HSSFCellStyle headingCellStyle = wb.createCellStyle();

headingCellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

//head font

HSSFFont headingCellFont = wb.createFont();

headingCellFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

headingCellStyle.setFont(headingCellFont);

// head

HSSFRow row;

row = sheet.createRow((short) 0);

String names[] = { "User Type", "User Name", "IP Address", "Action", "Details", "Date" };

//set list head

for (int i = 0; i < 6; i++) {

HSSFCell cell = row.createCell((short) (i));

cell.setCellValue(names[i]);

cell.setCellStyle(headingCellStyle);

}

//设置日期格式

HSSFCellStyle dateCellStyle = wb.createCellStyle();

HSSFDataFormat format = wb.createDataFormat();

short fmt = format.getFormat("yyyy/MM/dd HH:mm:ss");

dateCellStyle.setDataFormat(fmt);

short rowCount = 1;

for (int j = 0; j < list.size(); j++) {

row = sheet.createRow(rowCount);

Logs logs = list.get(j);

int column = 0;

HSSFCell cell = row.createCell((short) (column++));

cell.setCellValue(logs.getUsertype());

cell = row.createCell((short) (column++));

cell.setCellValue(logs.getUsername());

cell = row.createCell((short) (column++));

cell.setCellValue(this.getIp(logs));

cell = row.createCell((short) (column++));

cell.setCellValue(logs.getAction());

cell = row.createCell((short) (column++));

cell.setCellValue(getDetails(logs));

cell = row.createCell((short) (column));

cell.setCellStyle(dateCellStyle);

cell.setCellValue(DateUtil.format(logs.getDate(), "yyyy/MM/dd HH:mm:ss"));

rowCount++;

}

FileOutputStream fos;

StringBuffer filePath = new StringBuffer().append(Glob.tempdir());

if(filePath.charAt(filePath.length()-1) != File.separatorChar)

filePath.append(File.separator);

filePath.append("export");

File file = new File(filePath.toString());

if (!file.exists()) {

file.mkdirs();

}

filePath.append(File.separator);

filePath.append(System.currentTimeMillis() + "_auditLogs.xls");

try {

fos = new FileOutputStream(filePath.toString());

wb.write(fos);

fos.flush();

fos.close();

} catch (IOException e) {

e.printStackTrace();

}

return wb;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: