日期:2014-05-17 浏览次数:20975 次
public static void writeCsvFile(List<FileTestCaseValidateLog> logs, File outputCvsFilePath){
WritableWorkbook book = null;
try {
book = Workbook.createWorkbook(outputCvsFilePath);
//创建sheet.
WritableSheet sheet = book.createSheet("Sheet_1", 0);
for(int i = 0; i < logs.size(); i++){
FileTestCaseValidateLog log = logs.get(i);
Label testCaseLabel = new Label(0, i, log.getTestCaseName());
Label moduleLabel = new Label(1, i, log.getModuleName());
Number number = new Number(2, i, 2);
sheet.addCell(moduleLabel);
sheet.addCell(testCaseLabel);
sheet.addCell(number);
}
book.write();
} catch (RowsExceededException e) {
e.printStackTrace();
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(book != null){
book.close();
}
} catch (WriteException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
------解决方案--------------------
一段完整的代码。 运用到struts.
public static void createExcel(HttpServletRequest request, HttpServletResponse response,
String title,String[] headers,List<String[]> dataList) {
// create a new workbook
HSSFWorkbook wb = new HSSFWorkbook();
// create a new sheet
HSSFSheet s = wb.createSheet(title);
//font
HSSFFont titleFont = wb.createFont();
titleFont.setFontHeightInPoints( (short) 16);
titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
titleFont.setItalic(false);
HSSFFont headFont = wb.createFont();
headFont.setFontHeightInPoints( (short) 12);
headFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//headFont.setColor(HSSFFont.COLOR_RED);
HSSFFont bodyFont = wb.createFont();
bodyFont.setFontHeightInPoints( (short) 10);
//CellStyle
HSSFCellStyle csTitle = wb.createCellStyle();
csTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
csTitle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
csTitle.setBorderTop(HSSFCellStyle.BORDER_THIN);
csTitle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
csTitle.setBorderRight(HSSFCellStyle.BORDER_THIN);
csTitle.setFont(titleFont);
HSSFCellStyle csHeader = wb.createCellStyle();
csHeader.setFont(headFont);
csHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
csHeader.setBorderBottom(HSSFCellStyle.BORDER_THIN);
csHeader.setBorderTop(HSSFCellStyle.BORDER_THIN);
csHeader.setBorderLeft(HSSFCellStyle.BORDER_THIN);
csHeader.setBorderRight(HSSFCellStyle.BORDER_THIN);
//csHeader.setFillBackgroundColor(HSSFColor.YELLOW.index);
// csHeader.setFillForegroundColor(HSSFColor.WHITE.index);
// csHeader.setFillPattern(HSSFCellStyle.ALIGN_CENTER);
csHeader.setLocked(false);
//列数
int columnNum = headers.length;
short rowNum = 0;
//添加导出excel标题
HSSFRow row = s.createRow(rowNum++);
row.setHeight( (short) 500);
HSSFCell cell = row.createCell(0);
s.addMergedRegion(new CellRangeAddress(0, 0, 0,(columnNum - 1)));
//cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(title);
cell.setCel