
前兩天學習了兩種java操作excel的方法,對於網站需要創建、修改、導出excel文件,可以使用這兩種方法,第一種方法是使用JExcel,第二種方法是使用poi中的HSSF,前一種方法比較簡單。這裡做個總結。
只讀文件
Workbook wb=Workbook.getWorkbook(File path)
可讀寫文件,創建一個新文件
WritableWrokbook wwb=Wrokbook.createWorkbook(String filePath)
主要的層次關系如下

重要的方法:
//設置字體樣式
WritableFont font=new WritableFont(WritableFont.TIMES, 15, WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat fmt=new WritableCellFormat(font);
fmt.setAlignment(Alignment.CENTRE);
Label label1=new Label(0, 0, "軟件工程一班名單", fmt);
sheet.mergeCells(0, 0, 4, 0);//合並單元格
sheet.setRowView(0, 500);//設置第一行的寬度
//都是在sheet中實現的
for(int i=1;i<rsheet.getRows();i++)//循環獲取sheet中的內容
for(int j=0;j<rsheet.getColumns();j++){
Label label=new Label(j, i,rsheet.getCell(j, i).getContents());
sheet.addCell(label);
}
DateFormat df=new DateFormat("yyyy-MM-dd");//指定時間的顯示方式
WritableCellFormat wcfDF=new WritableCellFormat(df);
DateTime tm=new DateTime(0,rsheet.getRows()+1, new Date(),wcfDF);
sheet.addCell(tm);
wbook.write();
HSSFWorkbook-(createSheet)>HSSFSheet-(createRow)>HSSFRow-(createCell)>HSSFCell,與JExcel不同的是HSSFWorkbook最後才導入到文件流中,而且沒有列的對象,由行定位列。
重要的修飾方法:
font.setColor(HSSFFont.COLOR_RED);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
HSSFCellStyle cellStyle=book.createCellStyle();//樣式添加
cellStyle.setDataFormat(book.createDataFormat().getFormat("yyyy-MM-dd"));//設置時間表示方式
cellStyle.setFont(font);
cell.setCellStyle(cellStyle);
更多方法參照其api文檔
2016-04-06 13:23:25