效果:
使用时先把poi包导入工程的path,注意只需要导入poi包即可,下载后有三个jar包
核心代码:
连接数据库:dbconnection.java
e.printstacktrace();
}
}
if(ps!=null)
{
try {
ps.close() ;
} catch (sqlexception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
}
导入excel类:mysql2excel.java
package org.xg.db;
import java.io.fileoutputstream;
import java.io.outputstream;
import java.sql.connection;
import java.sql.resultset;
import org.apache.poi.hssf.usermodel.hssfcell;
import org.apache.poi.hssf.usermodel.hssfrichtextstring;
import org.apache.poi.hssf.usermodel.hssfrow;
import org.apache.poi.hssf.usermodel.hssfsheet;
import org.apache.poi.hssf.usermodel.hssfworkbook;
public class mysql2excel {
public mysql2excel() throws exception
{
connection con = null ;
dbconnection db = new dbconnection() ;
con = db.getdb() ;
string sql ="select * from students" ;
resultset rs = con.createstatement().executequery(sql) ;
// 获取总列数
int countcolumnnum = rs.getmetadata().getcolumncount() ;
int i =1 ;
// 创建excel文档
hssfworkbook wb = new hssfworkbook() ;
// sheet 对应一个工作页
hssfsheet sheet = wb.createsheet("student表中的数据") ;
hssfrow firstrow = sheet.createrow(0); //下标为0的行开始
hssfcell[] firstcell = new hssfcell[countcolumnnum];
string[] names = new string[countcolumnnum];
names[0] ="id";
names[1] ="学号";
names[2] ="姓名";
names[3] ="性别";
names[4] ="班级";
for(int j= 0 ;j<countcolumnnum; j++){
firstcell[j] = firstrow.createcell((short)j);
firstcell[j].setcellvalue(new hssfrichtextstring(names[j]));
}
while(rs.next())
{
// 创建电子表格的一行
hssfrow row = sheet.createrow(i) ; // 下标为1的行开始
for(int j=0;j<countcolumnnum;j++)
{
// 在一行内循环
hssfcell cell = row.createcell((short) j) ;
// 设置表格的编码集,使支持中文
//// 先判断数据库中的数据类型
// 将结果集里的值放入电子表格中
cell.setcellvalue(new hssfrichtextstring(rs.getstring(j+1))) ;
}
i++ ;
}
// 创建文件输出流,准备输出电子表格
outputstream out = new fileoutputstream("e:\\person.xls") ;
wb.write(out) ;
out.close() ;
system.out.println("数据库导出成功") ;
rs.close() ;
con.close() ;
}
public static void main(string[] args)
{
try {
@suppresswarnings("unused")
mysql2excel excel = new mysql2excel() ;
} catch (exception e) {
// todo auto-generated catch block
e.printstacktrace();
}
}
}
<a href="reportservlet" onclick="return confirm('确认数据导出到e:/下?');">导出数据到excel</a>
后台servlet写上上面的代码,注意最后需要response.sendredirect("") 返回前端
如对本文有疑问, 点击进行留言回复!!
tomcat9 下载安装和配置+整合到eclipse的教程详解
Android Retrofit2+rxjava2+Mvp基于okhttp3网络请求框架的使用 一 框架配置
android用Popup弹出窗(PopupWindow的使用方式)
网友评论