推薦POI的用戶使用手冊:http://poi.apache.org/spreadsheet/quick-guide.html#NewWorkbook
HSSFCellStyle (POI API Documentation)
/**
* 將對應的數據寫入excel文件
* @param head 文件的名稱(同時也是文件的頭)
* @param colName 文件各列的解釋說明,與content的內容對應
* @param content 需要被輸入到文件的內容
* @return String 返回創建的文件的名稱
*/
public String inputContentToExcel(String head,String[] colName,List<List> content) throws IOException {
String path = getExportDir();
File file = new File(path);
if(!file.exists()){
file.mkdirs();
}
path += "/" + head + ".xls";
File currentFile = new File(path);
if(!currentFile.exists()){
file.mkdir();
}
int colCount = colName.length;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(head);
//創建第一行爲標題行
HSSFRow row1 = sheet.createRow(0);
HSSFCell cell1 = row1.createCell((short)0);
cell1.setCellValue(head);
//創建第二行爲每列的標題
HSSFRow row2 = sheet.createRow(1);
for(short col=0;col<colCount;col++){
HSSFCell cell = row2.createCell(col);
String val = colName[col];
cell.setCellValue(Validator.isNULL(val) ? "" : val);
}
//創建輸入內容的各行
int rowInd = 2;
for (List list : content){
HSSFRow row = sheet.createRow(rowInd);
for(short j=0;j<colCount;j++){
HSSFCell cell = row.createCell(j);
String val = list.get(j).toString();
cell.setCellValue(val);
}
rowInd++;
}
//合併標題行
sheet.addMergedRegion(new Region(0,(short)0,0,(short)(colCount-1)));
//標題的樣式
HSSFFont font = wb.createFont();
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); //加粗
font.setFontHeightInPoints((short)18); //設置字號大小
font.setFontName("宋體"); //設置字體
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); //居中方式
style.setFont(font);
cell1.setCellStyle(style);
//根據內容自動調整寬度
for(short k=0;k<colCount;k++){
sheet.autoSizeColumn(k);
}
//開始寫入數據
FileOutputStream stream = new FileOutputStream(path);
wb.write(stream);
stream.close();
return head + ".xls";
}
獲取路徑的方法
public String getExportDir(){
String dir = "";
dir = configService.getFileRealPath() + "export/";
//獲取當前的年月日,創建文件目錄
Calendar calendar = Calendar.getInstance();
dir += calendar.get(Calendar.YEAR) + "/" + (calendar.get(Calendar.MONTH)+1) + "/" + calendar.get(Calendar.DATE) ;
System.out.println("當前的文件路徑爲:"+dir);
return dir;
}
效果圖如附件