關於Java Web 使用 POI 將 資料庫表 匯出 Excel 的完整例項
阿新 • • 發佈:2019-01-04
//匯出Excel
public void exportExcel() throws InterruptedException, IOException{
HSSFWorkbook hwb = new HSSFWorkbook();//第一步,建立一個workbook(一個excel檔案)
HSSFSheet hs = hwb.createSheet("圖書詳情資訊");//第二步,在workbook中新增一個sheet,對應excel檔案中sheet
HSSFRow hr = hs.createRow((int)0);//第三部,在sheet中新增表頭第0行(相當於解釋欄位)
HSSFCellStyle hcs = hwb.createCellStyle();//第四步,設定第0行(表頭)居中
hcs.setAlignment(HSSFCellStyle.ALIGN_CENTER);//建立居中格式
//將表頭的欄位放入陣列當中
String [] excelHeader = {"-編號-","-書名-","-作者-","-價格-","-總量-"};
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell hc = hr.createCell(i);//順序建立
hc.setCellValue(excelHeader[i]);//順序塞入
hc.setCellStyle(hcs);//居中
hs.autoSizeColumn(i);//設定 i 這一列為自動調整列寬
}
List<ThefuzzyBook> Blist = iThefuzzyBookService.findAll();//查詢全部實體屬性欄位
for (int i = 0; i < Blist.size(); i++) {
hr = hs.createRow(i+1);//在sheet中自動隨 i+1 增加一行(i 是表頭)
ThefuzzyBook thefuzzyBook = Blist.get(i);
hr.createCell(0).setCellValue(thefuzzyBook.getBookNumber());
hr.createCell(1).setCellValue(thefuzzyBook.getBookName());
hr.createCell(2).setCellValue(thefuzzyBook.getBookAuthor());
hr.createCell(3).setCellValue((double)thefuzzyBook.getBookPrice());
hr.createCell(4).setCellValue(thefuzzyBook.getBookCount());
}
FileOutputStream fos = new FileOutputStream("F:/BookInformation.xls");//先 new 出文件存放的位置
hwb.write(fos);;//寫入
fos.close();//關閉資源
System.out.println("匯出成功! 無任何異常。");
}
public void exportExcel() throws InterruptedException, IOException{
HSSFWorkbook hwb = new HSSFWorkbook();//第一步,建立一個workbook(一個excel檔案)
HSSFSheet hs = hwb.createSheet("圖書詳情資訊");//第二步,在workbook中新增一個sheet,對應excel檔案中sheet
HSSFRow hr = hs.createRow((int)0);//第三部,在sheet中新增表頭第0行(相當於解釋欄位)
HSSFCellStyle hcs = hwb.createCellStyle();//第四步,設定第0行(表頭)居中
hcs.setAlignment(HSSFCellStyle.ALIGN_CENTER);//建立居中格式
//將表頭的欄位放入陣列當中
String [] excelHeader = {"-編號-","-書名-","-作者-","-價格-","-總量-"};
for (int i = 0; i < excelHeader.length; i++) {
HSSFCell hc = hr.createCell(i);//順序建立
hc.setCellValue(excelHeader[i]);//順序塞入
hc.setCellStyle(hcs);//居中
hs.autoSizeColumn(i);//設定 i 這一列為自動調整列寬
}
List<ThefuzzyBook> Blist = iThefuzzyBookService.findAll();//查詢全部實體屬性欄位
for (int i = 0; i < Blist.size(); i++) {
hr = hs.createRow(i+1);//在sheet中自動隨 i+1 增加一行(i 是表頭)
ThefuzzyBook thefuzzyBook = Blist.get(i);
hr.createCell(0).setCellValue(thefuzzyBook.getBookNumber());
hr.createCell(1).setCellValue(thefuzzyBook.getBookName());
hr.createCell(2).setCellValue(thefuzzyBook.getBookAuthor());
hr.createCell(3).setCellValue((double)thefuzzyBook.getBookPrice());
hr.createCell(4).setCellValue(thefuzzyBook.getBookCount());
}
FileOutputStream fos = new FileOutputStream("F:/BookInformation.xls");//先 new 出文件存放的位置
hwb.write(fos);;//寫入
fos.close();//關閉資源
System.out.println("匯出成功! 無任何異常。");
}