java excel自动保存_Java 读取Excel内容并保存进数据库

该博客详细介绍了如何使用Java读取Excel文件内容,然后将这些内容存储到数据库中。首先,建立数据库连接,接着加载驱动并连接MySQL数据库。然后,利用Apache POI库读取Excel文件,获取每行每列的数据。最后,构造SQL语句并将数据插入到数据库中。代码示例中还包含了处理日期格式和关闭连接的方法。
摘要由CSDN通过智能技术生成

读取Excel中内容,并保存进数据库

步骤

建立数据库连接

读取文件内容 (fileInputStream 放进POI的对应Excel读取接口,实现Excel文件读取)

获取文件各种内容(总列数,总行数,各个单元格的内容)

执行SQL语句,存进数据库

public static void main(String[] args) {

Connection con = null;

//驱动程序名

String driver = "";

//URL指向要访问的数据库名mydata

String url = "";

//MySQL配置时的用户名

String user = "";

//MySQL配置时的密码

String password = "";

try {

//加载驱动程序

Class.forName(driver);

//1.getConnection()方法,连接MySQL数据库!!

con = DriverManager.getConnection(url,user,password);

if(!con.isClosed())

System.out.println("Succeeded connecting to the Database!");

//2.创建statement类对象,用来执行SQL语句!!

Statement statement = con.createStatement();

Workbook wb =null;

Sheet sheet = null;

Row row = null;

List> list = null;

//文件路径

String filePath = "";

wb = readExcel(filePath);

if(wb != null){

//用来存放表中数据

list = new ArrayList>();

//获取第一个sheet

sheet = wb.getSheetAt(0);

//获取最大行数

int rownum = sheet.getPhysicalNumberOfRows();

//获取第一行

row = sheet.getRow(0);

//获取最大列数

int colnum = row.getPhysicalNumberOfCells();

//格式化日期 dateFormat.format

SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");

//循环读取所有内容

for (int i = 1; i

Row row1=sheet.getRow(i);

//sql语句生成并执行

String sql="";

statement.execute(sql);

}

}

//遍历解析出来的list

for (Map map : list) {

for (Entry entry : map.entrySet()) {

System.out.print(entry.getKey()+":"+entry.getValue()+",");

}

System.out.println();

}

}catch(Exception e) {

System.out.println(e.getMessage());

}finally {

try {

con.close();

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

//读取excel

public static Workbook readExcel(String filePath){

Workbook wb = null;

if(filePath==null){

return null;

}

String extString = filePath.substring(filePath.lastIndexOf("."));

InputStream is = null;

try {

is = new FileInputStream(filePath);

if(".xls".equals(extString)){

return wb = new HSSFWorkbook(is);

}else if(".xlsx".equals(extString)){

return wb = new XSSFWorkbook(is);

}else{

return wb = null;

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return wb;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值