工具类
/**
* 导出excel
* @param title
* @param rowTitles
* @param dataArray
* @param response
*/
public static void exportExcelByResource(String title,String[] rowTitles,JSONArray dataArray,ResourceResponse response) {
HSSFWorkbook workbook = new HSSFWorkbook();// 创建一个Excel文件
HSSFSheet sheet = workbook.createSheet();// 创建一个Excel的Sheet
sheet.setDefaultColumnWidth(13);
// 生成一个标题样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
titleStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
// 生成一个字体
HSSFFont titleFont = workbook.createFont();
titleFont.setFontHeightInPoints((short) 12);
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
// 把字体应用到当前的样式
titleStyle.setFont(titleFont);
// 生成一个普通样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);// 水平居中
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);// 垂直居中
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 创建标题行
HSSFRow titleRow = sheet.createRow(0);
for (int i = 0; i < rowTitles.length; i++) {
HSSFCell cell = titleRow.createCell(i);
cell.setCellStyle(titleStyle);
HSSFRichTextString text = new HSSFRichTextString(rowTitles[i]);
cell.setCellValue(text);
}
if (dataArray != null && dataArray.length() > 0) {
for (int i = 0; i < dataArray.length(); i++) {
HSSFRow row = sheet.createRow(i + 1);
JSONObject json = dataArray.getJSONObject(i);
for (int j = 0; j < rowTitles.length; j++) {
HSSFCell cell = row.createCell(j);
cell.setCellStyle(style);
String jsonStr = json.getString(rowTitles[j]);
HSSFRichTextString text = new HSSFRichTextString(jsonStr);
cell.setCellValue(text);
}
}
}
try {
OutputStream output = new BufferedOutputStream(
response.getPortletOutputStream());
response.reset();
String fileName = new String(title.getBytes("GBK"), "ISO8859-1")
.replaceAll("/", "");
response.addProperty(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename="+fileName);
response.setContentType("application/vnd.ms-excel");
workbook.write(output);
output.flush();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
调用示例
JSONArray dataArray = null;
try {
dataArray = IctOrderPlanLocalServiceUtil
.getIctPlanJsonArray(request);
} catch (PortalException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
String[] rowTitles = { "周期", "周数", "项目名称", "本周工作", "下步计划", "项目经理",
"创建时间" };
String title = "周报报表.xls";
ExcelUtil.exportExcelByResource(title, rowTitles, dataArray, response);
super.serveResource(request, response);