标签:数据库查询 get str filesyste ring cell 账户 分享 catch
本次使用到的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(); } } }
标签:数据库查询 get str filesyste ring cell 账户 分享 catch
原文地址:https://www.cnblogs.com/dhome/p/9737342.html