Java版将Excel表格数据导入数据库

将Excel中的数据存入数据库与在系统中操作的唯一不同就是数据源不同,其中从Excel中导入数据的关键在于从Excel中读取每行数据。
如何从excel中读取数据?下面代码是简单的导入过程,具体需要根据自己的数据来改。

  • 读取该文件
  • 获取该excel中所需sheet表格内容
  • 根据表格中数据,将需要的字段存入数据库
public void Inform() throws Exception
{
	private FileItem file;
	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	String filename = file.getName();
	String fileType = filename.subString(filename.lastIndexOf(".")+1,filename.length());
	InputStream stream = file.getInputStream();
	Workbook wb = null;
	if (fileType.equals("xls")){
		wb = new HSSFWorkbook(stream);
	}else if(fileType.equals("xlsx")){
		wb = new HSSFWorkbook(stream);
	}else{
		throw new CssException("导入文件格式有误");
	}
	int sheetNum = wb.getNumberOfSheet();//获取sheet数目
	if(sheetNum > 0){
		Sheet sheet = wb.getSheetAt(0);//获取第一个sheet表
		if(sheet != null){
			int rowNum = sheet.getLastRowNum();
			if(rowNum >= 1){
			//用到了缓存
				TransactionCache tx = null;
				int errorRow = 0;
				try{
					tx = new TransactionCache();
					List<Student>list = new ArrayList<>();
					String uuid = Uuid.getUuid();//获取uuid,如果不需要可以不加
					Row rowTitle = sheet.getRow(0);//第一行数据为行标,不存入数据库
					if(rowTitle.getLastCellNum()==_列数此处用3_){
						for(int i=1;i<rowNum+1;i++){
							Row row = sheet.getRow(i);
							//获取每行每列的数据,以3列为例 以姓名(字符串类型)、生日(日期类型)、年龄(double类型)
							String name = getCellStrValue(row.getCell(0));
							Date bir = getCellDateValue(row.getCell(1));
							String ageStr= getCellStrValue(row.getCell(2));
							Double age = Double.valueOf(ageStr);
							Student stu = new Student();
							stu.setName(name);
							stu.setBir(bir);
							stu.setAge(age);
							list.add(stu);
						}
						tx.save(list);
						tx.commit();
					}
				}
			}
		}
	}
}
private Date getCellDateValue(Cell cell){
	if(cell == null){
		return null;
	}
	Date date = null;
	try{
		date = cell.getDateCellValue();
	}catch(Exception e){
		try{
			String dateStr = cell.getStringCellValue();
			date = sdf.parse(dateStr);
		}catch(ParseException parseException){
			parseException.printStackTrace();
		}
	}
	return date;
}

private String getCellStrValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        String str = null;
        int cellType = cell.getCellType();
        switch (cellType) {
            case 0:
                str = Math.round(cell.getNumericCellValue()) + "";
                break;
            case 1:
                str = cell.getStringCellValue();
                break;
            case 2:
                str = "";
                break;
            case 3:
                str = null;
                break;
            case 4:
                str = cell.getBooleanCellValue() + "";
                break;
            case 5:
                str = "错误" + cell.getErrorCellValue() + "";
        }
        return str;
    }
  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Apache POI库来读取Excel文件,然后使用JDBC连接数据库,将数据插入到数据库中。以下是一个简单的示例代码: ```java import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelToDatabase { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; String excelFilePath = "data.xlsx"; try (Connection connection = DriverManager.getConnection(jdbcUrl, username, password); FileInputStream inputStream = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); String sql = "INSERT INTO mytable (column1, column2, column3) VALUES (?, ?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); int rowNumber = 0; for (Row row : sheet) { if (rowNumber == 0) { rowNumber++; continue; } Cell cell1 = row.getCell(0); String column1 = cell1.getStringCellValue(); Cell cell2 = row.getCell(1); int column2 = (int) cell2.getNumericCellValue(); Cell cell3 = row.getCell(2); double column3 = cell3.getNumericCellValue(); statement.setString(1, column1); statement.setInt(2, column2); statement.setDouble(3, column3); statement.addBatch(); if (rowNumber % 100 == 0) { statement.executeBatch(); } } workbook.close(); statement.executeBatch(); System.out.println("Data imported successfully."); } catch (Exception e) { System.out.println("Error: " + e.getMessage()); } } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

不想当个程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值