java读取 xls 文件 存入数据库

本文介绍了一个Java程序,该程序能够从Excel文件中读取数据,并将这些数据批量插入到指定的数据库表中。通过使用jxl库来操作Excel文件及JDBC进行数据库交互,实现了自动化数据迁移。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.accp.function;

 import java.io.FileInputStream;

 import java.io.InputStream;

 import java.sql.Connection;

 import java.sql.PreparedStatement;

 import java.sql.ResultSet;

 import java.sql.SQLException;

 import java.util.ArrayList;

 import java.util.List;

 import jxl.Cell;

 import jxl.Sheet;

 import jxl.Workbook;

 import com.accp.util.ConnectionManager;

 

/** * 读取Excel,存入数据库

  * * @author zhusujian

  * */

public class ReadExcel {

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

 

public ReadExcel() { 

     Workbook workBook = null;

     conn = ConnectionManager.getConnection();

     List list = new ArrayList();

   

    // 直接从本地文件创建Workbook

    // 从输入流创建Workbook

   try {

        InputStream is = new FileInputStream("assrow.xls");

        workBook = Workbook.getWorkbook(is);

      

       // 从0开始,第一张工作表

       Sheet sheet = workBook.getSheet(0);

     

      // 拿到列,行

      int column = sheet.getColumns();

      int row = sheet.getRows();

     

      // 拿到每一行,每列的值

      for (int i = 1; i < row; i++) {

           for (int j = 0; j < column; j++) {

                Cell cell = sheet.getCell(j, i);

                list.add(cell.getContents());

           }

      }

     String sql = "insert into assrow values(?, ?, ?, ?, ?, ?)";

          for (int i = 0; i < list.size() / 6; i++) {

pstmt = (PreparedStatement) conn.prepareStatement(sql);

pstmt.setString(1, (String) list.get(i * 6));

pstmt.setString(2, (String) list.get(i * 6 + 1));

pstmt.setString(3, (String) list.get(i * 6 + 2));

pstmt.setString(4, (String) list.get(i * 6 + 3));

pstmt.setString(5, (String) list.get(i * 6 + 4));

pstmt.setString(6, (String) list.get(i * 6 + 5));

pstmt.executeUpdate(); pstmt.close();

}

} catch (Exception e) {

e.printStackTrace(); 

} finally {

workBook.close();

} } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值