【Java】 导入本地excel文件并对比数据库差异数据


前言

在本次项目中,有一个需求,导入本地Excel文件,对比数据库差异数据,再将差异数据导出Excel
项目使用前后端分离,所有这里采用前后端分离思想

一、思路

  1. 读取本地Excel文件,获取其中的数据
  2. 通过获取的参数查询数据库数据
  3. 对比差异数据
  4. 导出差异数据Excel表格

二、使用步骤

1.引入库

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.17</version>
</dependency>

<!--如有需要处理大量数据则导入-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.17</version>
</dependency>

2.读取上传的Excel数据并对比差异数据接口

	/**
	* 	对比上传的Exccel的差异数据
	*/
    public JSONObject dataComparison(JSONObject jsonobject) {
        // 请求文件路径地址
        String url = jsonobject.getString("url");
        Assert.isBlank(url, "清选择文件");
        
        String fullFileName = url;
        List<JSONObject> list;
        try {
            InputStream is = new FileInputStream(fullFileName);
            list = read2007Xlsx(is);
        } catch (Exception e) {
            e.getMessage();
            throw new BaseException(400, "读取文件错误");
        }

        // 匹配数据库数据
        JSONObject params = new JSONObject();
        params.put("list", list);

        JSONObject objectList = matchDatabaseData(params);
        return objectList ;
    }

    /**
     * 读取excel文件
     * XSSF -- 提供读写Microsoft Excel OOXML格式档案的功能
     * XSSFWorkbook:是操作Excel2007(以上)的版本,扩展名是.xlsx
     * @param in
     * @return
     * @throws IOException
     */
    public static List<JSONObject> read2007Xlsx(InputStream in) throws IOException {

        List<JSONObject> list = new ArrayList<>();
        XSSFWorkbook xWorkbook = new XSSFWorkbook(in);
        // Read the Sheet
        XSSFSheet xssfSheet = xWorkbook.getSheetAt(0);

        // Read the Row
        for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
            XSSFRow xssfRow = xssfSheet.getRow(rowNum);
            if (xssfRow != null) {
                // 设置读取格式
                xssfRow.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
                xssfRow.getCell(1).setCellType(Cell.CELL_TYPE_STRING);
                xssfRow.getCell(2).setCellType(Cell.CELL_TYPE_STRING);
                xssfRow.getCell(3).setCellType(Cell.CELL_TYPE_STRING);

                JSONObject params = new JSONObject();
                params.put("receivedLinkman", xssfRow.getCell(0).getStringCellValue());
                params.put("receivedTelephone", xssfRow.getCell(1).getStringCellValue());
                // 开始时间

                String _startTime = xssfRow.getCell(2).getStringCellValue();
                Date startTime = HSSFDateUtil.getJavaDate(Double.valueOf(_startTime));
                params.put("startTime", testTime(startTime));

                String _endTime = xssfRow.getCell(3).getStringCellValue();
                Date endTime = HSSFDateUtil.getJavaDate(Double.valueOf(_endTime));

                params.put("endTime", testTime(endTime));
                list.add(params);
            }
        }

        xWorkbook.close();
        return list;
    }

    /**
     * 匹配数据库数据
     * key = "list"
     *
     * @param params
     */
    private BasePageInfo<JSONObject> matchDatabaseData(JSONObject params) {
        if (params == null && params.getString("list") == null && params.getJSONArray("list").isEmpty()) {
            return null;
        }

        JSONArray array = params.getJSONArray("list");
        JSONObject jsonObject = new JSONObject();
        if (array != null && array.size() > 0) {
            jsonObject = array.getJSONObject(0);
            jsonObject.put("page", params.getString("page"));
            jsonObject.put("rows", params.getString("rows"));
        }

        // 查询相关订单数据
        BasePageInfo<JSONObject> objectList = iOrderDao.queryOrderByExcel(jsonObject);

        JSONArray list = params.getJSONArray("list");

        // 处理差异数据
        List<JSONObject> returnList = processingDifferenceData(list, objectList.getList());
        objectList.setList(returnList);
        return objectList;
    }

3.获取差异数据并导出Excel

前面通过上一个接口获取到差异数据,将差异数据写入Excel表格

    public JSONObject exportExcel(JSONObject jsonObject) {
        // 导出差异数据
        JSONArray list = jsonObject.getJsonArray("list");
        if (list == null) {
            throw new BaseException(400, "缺少导出数据");
        }

        // 获取桌面路径
        String path = getDesktopPath();

        // 填充导出内容
        fillExportContent(path, list);

        return Output.out(Message.OK, Message.EXPORT_EXCEL);
    }

	 /**
     * 获取桌面路径
     *
     * @return
     */
    private static String getDesktopPath() {
        // 获取桌面
        FileSystemView view = FileSystemView.getFileSystemView();
        File file = view.getHomeDirectory();
        String path = file.getPath();
        path.replace("\\", "/");
        return file.getPath();
    }

    /**
     * 填充导出内容
     *
     * @param path 导出路径
     * @param list 导出内容
     */
    private void fillExportContent(String path, JSONArray list) {

        if (list == null && list.size() <= 0) {
            return;
        }

        //创建工作薄对象
        HSSFWorkbook workbook = new HSSFWorkbook();//这里也可以设置sheet的Name
        //创建工作表对象
        HSSFSheet sheet = workbook.createSheet();
        //创建工作表的行
        HSSFRow row = sheet.createRow(0);//设置第一行,从零开始
        //第一行第一列
        row.createCell(0).setCellValue("订单号");
        //第一行第二列
        row.createCell(1).setCellValue("收货人");
        //第一行第三列
        row.createCell(2).setCellValue("收货人电话");
        //第一行第四列 settledAmount
        row.createCell(3).setCellValue("订单结算金额");
        row.createCell(4).setCellValue("送货人");
        row.createCell(5).setCellValue("送货人电话");
        row.createCell(6).setCellValue("送货地址");
        // (1wap移动 2pc  3微信小程序 4百度小程序 5第三方平台)
        row.createCell(7).setCellValue("订单来源");
        // 转单平台(0未转 1花娃 2花大侠 3无需转单 4转单宝)
        row.createCell(8).setCellValue("转单平台");
        row.createCell(9).setCellValue("创建时间");
        row.createCell(10).setCellValue("支付类型");

        // 设置表体内容
        for (int i = 0; i < list.size(); i++) {
            JSONObject listJSONObject = list.getJSONObject(i);
            row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(listJSONObject.getString("orderCode"));
            row.createCell(1).setCellValue(listJSONObject.getString("receivedLinkman"));
            row.createCell(2).setCellValue(listJSONObject.getString("receivedTelephone"));
            row.createCell(3).setCellValue(listJSONObject.getString("settledAmount"));
            row.createCell(4).setCellValue(listJSONObject.getString("sendLinkman"));
            row.createCell(5).setCellValue(listJSONObject.getString("sendTelephone"));
            row.createCell(6).setCellValue(listJSONObject.getString("address"));
            String platform = listJSONObject.getString("platform");
            switch (platform) {
                case "1":
                    platform = "移动端";
                    break;
                case "2":
                    platform = "pc端";
                    break;
                case "3":
                    platform = "微信小程序";
                    break;
                case "4":
                    platform = "百度小程序";
                    break;
                case "5":
                    platform = "第三方平台";
                    break;
            }
            row.createCell(7).setCellValue(platform);
            String deferentPlatform = listJSONObject.getString("deferentPlatform");
            switch (deferentPlatform) {
                case "0":
                    deferentPlatform = "未转";
                    break;
                case "1":
                    deferentPlatform = "花娃";
                    break;
                case "2":
                    deferentPlatform = "花大侠";
                    break;
                case "3":
                    deferentPlatform = "无需转单";
                    break;
                case "4":
                    deferentPlatform = "转单宝";
                    break;
            }
            row.createCell(8).setCellValue(deferentPlatform);
            row.createCell(9).setCellValue(listJSONObject.getString("createTime"));
            row.createCell(10).setCellValue(listJSONObject.getString("payName"));
        }
        // workbook.setSheetName(0,"sheet的Name");//设置sheet的Name

        //文档输出
        try {
            FileOutputStream out = new FileOutputStream(path + "/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() + ".xls");
            workbook.write(out);
            out.close();
        } catch (Exception e) {
            e.getMessage();
            throw new BaseException(400, "导出错误");
        }

    }



总结

  1. 导入导出注意文件格式
  2. 获取路径的时候使用 “/”
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用 Apache POI 库来读取本地 Excel 文件,然后使用 JDBC 连接数据库并将数据插入到数据库中。以下是一个示例代码: ```java import java.io.FileInputStream; import java.sql.Connection; 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 ExcelImport { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "root"; String excelFilePath = "path/to/excel/file.xlsx"; try (Connection conn = DriverManager.getConnection(url, 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 = conn.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); String column2 = cell2.getStringCellValue(); Cell cell3 = row.getCell(2); double column3 = cell3.getNumericCellValue(); statement.setString(1, column1); statement.setString(2, column2); statement.setDouble(3, column3); statement.executeUpdate(); } System.out.println("Data imported successfully!"); } catch (SQLException | IOException e) { e.printStackTrace(); } } } ``` 在这个示例代码中,我们首先建立了数据库连接,并使用 `FileInputStream` 读取了本地 Excel 文件。然后我们使用 `XSSFWorkbook` 类来解析 Excel 文件,并获取第一个工作表。接着,我们使用 `PreparedStatement` 来执行插入数据的 SQL 语句,并遍历 Excel 文件中的每一行,将数据插入到数据库中。最后,我们关闭了所有的资源,并在控制台输出了导入数据成功的信息。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值