1. 程式人生 > >簡單地從數據庫查詢數據使用poi插入創建Excel

簡單地從數據庫查詢數據使用poi插入創建Excel

null cto leo trac int 返回 acc ade put

本次使用到的jar包

  技術分享圖片

代碼

public class CreateExcel01 {

    // 數據庫查詢
    public static List<Account> query() {
        String sql = "select * from tb_account";
        List<Account> list = BaseDao.findRows(sql, null, Account.class);
        return list;
    }

    // 創建Excel
    public static void createExcel(){
        
try { // 獲取桌面路徑 FileSystemView fsv = FileSystemView.getFileSystemView(); String desktop = fsv.getHomeDirectory().getPath(); String filePath = desktop + "/account.xls"; File file = new File(filePath); OutputStream outputStream = new
FileOutputStream(file); HSSFWorkbook workbook = new HSSFWorkbook(); // 創建一個工作表 HSSFSheet sheet = workbook.createSheet("Sheet1"); // 創建首行/頭(第0行開始) HSSFRow head = sheet.createRow(0); String[] header = new String[]{"賬戶id","賬戶名稱","賬戶類型","賬戶金額","賬戶備註","創建時間","用戶id","更新時間"};
for (int i=0;i<header.length;i++){ // 設置首行信息 head.createCell(i).setCellValue(header[i]); } head.setHeightInPoints(20); // 設置行的高度 // 從數據查詢返回的集合 List<Account> accounts=query(); // 日期格式化 HSSFCellStyle cellStyle2 = workbook.createCellStyle(); HSSFCreationHelper creationHelper = workbook.getCreationHelper(); // 設置日期格式 cellStyle2.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss")); sheet.setColumnWidth(3, 15 * 256); sheet.setColumnWidth(5, 20 * 256); sheet.setColumnWidth(7, 20 * 256);// 設置列的寬度 // 保留兩位小數 HSSFCellStyle cellStyle3 = workbook.createCellStyle(); cellStyle3.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00")); for(int i=0;i<accounts.size();i++) { // 創建行(從第一行開始) HSSFRow row1 = sheet.createRow(i + 1); // id row1.createCell(0).setCellValue(accounts.get(i).getId()); // 賬戶名稱 row1.createCell(1).setCellValue(accounts.get(i).getAccountName()); // 賬戶類型 row1.createCell(2).setCellValue(accounts.get(i).getAccountType()); // 賬戶金額(保留兩位小數) HSSFCell money = row1.createCell(3); money.setCellStyle(cellStyle3); money.setCellValue(accounts.get(i).getMoney()); // 賬戶備註 row1.createCell(4).setCellValue(accounts.get(i).getRemark()); // 創建時間(格式化時間) HSSFCell date1 = row1.createCell(5); date1.setCellStyle(cellStyle2); date1.setCellValue(accounts.get(i).getCreateTime()); // 用戶id row1.createCell(6).setCellValue(accounts.get(i).getUid()); // 更新時間 HSSFCell date2 = row1.createCell(7); date2.setCellStyle(cellStyle2); date2.setCellValue(accounts.get(i).getUpdateTime()); } workbook.setActiveSheet(0); workbook.write(outputStream); outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } }

簡單地從數據庫查詢數據使用poi插入創建Excel