公司用到了Jfinal框架,关于框架的使用和说明,可以访问:www.jfinal.com。最近老大要我学一下jfinal+poi导出excel,之前没有用过一些和Excel相关的第三方组件,后来了解到操作excel的组件有:JXL和POI。我就使用了后者来操作Excel
用jfinal操作数据库特别爽,因为它不需要像JDBC活在Ibatis一样重复很多配置,它只需要一个数据源的插件就可以把数据的配置搞定(当然为了后期扩展,建议你把配置写到配置文件中,然后读取配置文件)。
具体代码如下体现:
public static void main(String[] args) throws Exception {
// Demo1();
Date d=new Date();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
String title=dateFormat.format(d);
System.out.println(title);
File file = new File(title+"_统计表"+".xls");
String sql="select id,weijia_role_id,login_name,password,create_date,modify_date,is_locked from weijia_user";
//ider:外部传入一个表头、SQL语句、
String s[] = new String[] { "id", "weijia_role_id", "login_name",
"password", "create_date", "modify_date", "is_locked " };
new test().saveFile(s,sql, file);
}
//新增一行就累加
private int count = 0;
public void saveFile(String[] s,String sql, File file) {
// 创建工作薄
HSSFWorkbook hssfWorkbook = new HSSFWorkbook();
// sheet:一张表的简称
// row:表里的行
// 创建工作薄中的工作表
HSSFSheet hssfSheet = hssfWorkbook.createSheet("test");
// 创建行
HSSFRow row = hssfSheet.createRow(0);
// 创建单元格,设置表头 创建列
HSSFCell cell = null;
//便利表头
for (int i = 0; i < s.length; i++) {
//创建传入进来的表头的个数
cell = row.createCell(i);
//表头的值就是传入进来的值
cell.setCellValue(s[i]);
}
//新增一个行就累加
row = hssfSheet.createRow(++count);
C3p0Plugin c3p0Plugin = new C3p0Plugin("jdbc:mysql://127.0.0.1/weijia",
"root", "123", "com.mysql.jdbc.Driver");
c3p0Plugin.start();
// 配置ActiveRecord插件
ActiveRecordPlugin arp = new ActiveRecordPlugin(c3p0Plugin);
arp.addMapping("weijia_user", User.class);
arp.start();
// 得到所有记录 行:列
List<Record> list = Db.find(sql);
Record record = null;
if (list != null) {
//获取所有的记录 有多少条记录就创建多少行
for (int i = 0; i < list.size(); i++) {
//row = hssfSheet.createRow(++count);
// 得到所有的行 一个record就代表 一行
record = list.get(i);
//在有所有的记录基础之上,便利传入进来的表头,再创建N行
for (int j = 0; j < s.length; j++) {
cell = row.createCell(j);
//把每一行的记录再次添加到表头下面 如果为空就为 "" 否则就为值
cell.setCellValue(record.get(s[j])==null?"":record.get(s[j]).toString());
}
}
}
try {
FileOutputStream fileOutputStreane = new FileOutputStream(file);
hssfWorkbook.write(fileOutputStreane);
fileOutputStreane.flush();
fileOutputStreane.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
本文介绍如何使用JFinal框架结合POI组件导出Excel的操作流程,包括配置数据库连接、执行SQL查询、生成Excel文件等关键步骤,并通过示例代码展示实现过程。

409

被折叠的 条评论
为什么被折叠?



