1. 程式人生 > >java怎麼把資料庫的內容匯出到excel表裡面

java怎麼把資料庫的內容匯出到excel表裡面

1、首先建立一個普通的類,這個類包含你要匯出的欄位。(不建立也沒有什麼)

2、再把所有的內容都放入這個類的list集合中。

3、把類寫入excel中

public static void corDownLownExcel(String sql, String path) {
try {
WritableWorkbook wwb = null;
// 建立可寫入的Excel工作簿
String fileName = path;
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
// 以fileName為檔名來建立一個Workbook
wwb = Workbook.createWorkbook(file);
// 建立工作表
WritableSheet ws = wwb.createSheet("Corporation Shee 1", 0);
// 查詢資料庫中所有的資料
List<CorporationFinacialForm> list = JXLExportExcel.getAllByDb(sql);
// 要插入到的Excel表格的行號,預設從0開始
Label labelCompanyName = new Label(0, 0, "公司名稱");
Label labelName = new Label(1, 0, "聯絡人姓名");// 表示第
Label labelEmail = new Label(2, 0, "聯絡人郵箱");
Label labelPhone = new Label(3, 0, "聯絡人電話");
Label labelCompanyMoney = new Label(4, 0, "去年資產總額");
Label labelCompanyShouru = new Label(5, 0, "主營業務收入");
ws.addCell(labelName);
ws.addCell(labelEmail);
ws.addCell(labelPhone);
ws.addCell(labelCompanyName);
ws.addCell(labelCompanyMoney);
ws.addCell(labelCompanyShouru);
for (int i = 0; i < list.size(); i++) {
Label labelCompanyName_i = new Label(0, i + 1, list.get(i).getCompanyName());
Label labelName_i = new Label(1, i + 1, list.get(i).getApplyPerson());
Label labelEmail_i = new Label(2, i + 1, list.get(i).getEmail());
Label labelPhone_i = new Label(3, i + 1, list.get(i).getContactsMobilePhone());
Label labellabelCompanyMoney_i = new Label(4, i + 1, list.get(i).getYyMoney());
Label labelCompanyShouru_i = new Label(5, i + 1, list.get(i).getYyshouru());
ws.addCell(labelName_i);
ws.addCell(labelEmail_i);
ws.addCell(labelPhone_i);
ws.addCell(labelCompanyName_i);
ws.addCell(labellabelCompanyMoney_i);
ws.addCell(labelCompanyShouru_i);
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
}
}