Java解析Excel并把数据保存到数据库中

Java解析Excel,采用的Apache的poi,其实不难,需求是把每一列的数据解析出来,因为每一列的数据不等,解析Excel是一行一行的解析的,其实根据列解析也不违背,只不过需要判断下数据是否为空,先获得某一列,然后一行行的解析下去。保存到数据库采用mybatis,因为参数是list,所以这边用批量插入。工程已经上传到GitHub上,传送门:https://github.com/loupXing/looper

解析Excel的代码

package com.ymm.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;
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.ss.usermodel.WorkbookFactory;

import com.ymm.dao.AreaDao;
import com.ymm.dao.impl.AreaDaoImpl;
import com.ymm.entity.CityDistrict;
import com.ymm.entity.DistrictStreet;
import com.ymm.entity.ProvinceCity;

public class ReadExcel
{
    private static final Logger LOGGER = Logger.getLogger(ReadExcel.class);

    private static List<ProvinceCity> provinceCities = new ArrayList<ProvinceCity>();

    private static List<CityDistrict> cityDistricts = new ArrayList<CityDistrict>();

    private static List<DistrictStreet> districtStreets = new ArrayList<DistrictStreet>();

    /**
     * 读取Excel
     *
     * @param filePath
     * @param sheetInex
     */
    public static void loadExcel(String filePath)
    {
        LOGGER.debug("enter loadExcel,filePath:" + filePath);
        InputStream in = null;
        Workbook workbook = null;
        Sheet sheet = null;
        try
        {
            in = new FileInputStream(filePath);
            workbook = WorkbookFactory.create(in);
            for (int i = 1; i < 4; i++)
            {
                sheet = workbook.getSheetAt(i);
                getSheetData(sheet, i);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.error("load excel failed,desc:::" + e, e);
        }
    }

    private static void getSheetData(Sheet sheet, int sheetInex)
    {
        AreaDao areaDao = new AreaDaoImpl();
        int rowNum = sheet.getLastRowNum();
        // 获取第一行
        Row rowFirst = sheet.getRow(0);
        Row row = null;
        Cell cell = null;
        String cellValue = null;
        int firstCellNum = rowFirst.getLastCellNum();
        String firstValue = null;
        String lastValue = null;
        
        for (int i = sheetInex == 1 ? 2 : 0; i <= firstCellNum; i++)
        {
            for (int j = 0; j <= rowNum; j++)
            {
                row = sheet.getRow(j);
                if (null != row)
                {
                    cell = row.getCell(i);
                    if (null != cell)
                    {
                        cellValue = cell.getStringCellValue();
                        if ((null != cellValue) && !"".equals(cellValue))
                        {
                            int indexN = cellValue.indexOf("N");
                            String subValue = cellValue.substring(0, indexN);
                            if (j == 0)
                            {
                                firstValue = subValue;
                                lastValue = cellValue;
                                continue;
                            }
                            if (sheetInex == 1)
                            {
                                ProvinceCity provinceCity = new ProvinceCity();
                                provinceCity.setProvince(firstValue);
                                provinceCity.setProvince_n(lastValue);
                                provinceCity.setCity(subValue);
                                provinceCity.setCity_n(cellValue);
                                provinceCities.add(provinceCity);
                            }
                            if (sheetInex == 2)
                            {
                                CityDistrict cityDistrict = new CityDistrict();
                                cityDistrict.setCity(firstValue);
                                cityDistrict.setCity_n(lastValue);
                                cityDistrict.setDistrict(subValue);
                                cityDistrict.setDistrict_n(cellValue);
                                cityDistricts.add(cityDistrict);
                            }
                            if (sheetInex == 3)
                            {
                                DistrictStreet districtStreet = new DistrictStreet();
                                districtStreet.setDistrict(firstValue);
                                districtStreet.setDistrict_n(lastValue);
                                districtStreet.setStreet(subValue);
                                districtStreet.setStreet_n(cellValue);
                                districtStreets.add(districtStreet);
                            }
                        }
                        
                    }
                }
            }
        }
        
        if (sheetInex == 1)
        {
            LOGGER.debug("provinceCities:" + provinceCities);
            areaDao.insertProvinceCity(provinceCities);
        }
        if (sheetInex == 2)
        {
            LOGGER.debug("cityDistricts:" + cityDistricts);
            areaDao.insertCityDistrict(cityDistricts);
        }
        if (sheetInex == 3)
        {
            LOGGER.debug("districtStreets:" + districtStreets);
            areaDao.insertDistrictStreet(districtStreets);
        }
        
    }
    
}



你可以使用 Apache POI 库来解析 Excel数据,并使用 JDBC 将数据导入数据库。是一个简单的 Java 代码示: 首先,确保你已经将 POI 和 JDBC 相关的 JAR 文件添加到你的项目。 ```java import java.FileInputStream; import java.sql; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; 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 ExcelImporter { public static void main(String[] args) { String excelFilePath = "path/to/your/excel/file.xlsx"; try (FileInputStream inputStream = new FileInputStream(excelFilePath); Workbook workbook = new XSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); int rowCount = 0; for (Row row : sheet) { if (rowCount == 0) { rowCount++; continue; } String column1 = row.getCell(0).getStringCellValue(); int column2 = (int) row.getCell(1).getNumericCellValue(); // 获取其他列的数据 // 将数据插入数据库 insertToDatabase(column1, column2); rowCount++; } System.out.println("数据导入成功!"); } catch (Exception e) { e.printStackTrace(); } } private static void insertToDatabase(String column1, int column2) { String url = "jdbc:mysql://localhost:3306/your_database"; String username = "your_username"; String password = "your_password"; try (Connection connection = DriverManager.getConnection(url, username, password)) { String sql = "INSERT INTO your_table (column1, column2) VALUES (?, ?)"; PreparedStatement statement = connection.prepareStatement(sql); statement.setString(1, column1); statement.setInt(2, column2); statement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } } ``` 在上面的示例,你需要将 `path/to/your/excel/file.xlsx` 替换为你实际的 Excel 文件路径。此外,你还需要根据你的数据库设置更新 `url`、`username`、`password`、`your_database` 和 `your_table`。 这个示例假设 Excel 表的第一行为标题,从第二行开始是数据。你可以根据需要调整代码以适应不同的表格结构。同时,你可以根据你的数据库表结构调整 `insertToDatabase()` 方法的 SQL 语句和参数设置。 请确保你已正确引入所需的库和驱动程序,并在执行代码之前设置好数据库连接信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值