73 lines
2.8 KiB
Java
73 lines
2.8 KiB
Java
package com.ruoyi.system.controller;
|
||
|
||
import org.apache.poi.ss.usermodel.*;
|
||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||
import org.junit.Test;
|
||
import org.springframework.boot.test.context.SpringBootTest;
|
||
|
||
import java.io.*;
|
||
import java.util.HashMap;
|
||
import java.util.Map;
|
||
|
||
@SpringBootTest
|
||
public class test {
|
||
@Test
|
||
public void Adfff() {
|
||
// excel 比较sheet1 和sheet2 表格的第一列和第二列 如果相同 就将sheet1 的第五列对应的值,写入给sheet2
|
||
String inputFilePath = "C:\\Users\\Administrator\\Desktop\\test\\采购订单.xlsx";
|
||
String outputFilePath = "C:\\Users\\Administrator\\Desktop\\test\\匹配价格.xlsx";
|
||
String logFilePath = "C:\\Users\\Administrator\\Desktop\\test\\logfile.txt"; // 日志文件路径
|
||
try (FileInputStream fis = new FileInputStream(inputFilePath);
|
||
Workbook workbook = new XSSFWorkbook(fis);
|
||
FileWriter fw = new FileWriter(logFilePath);
|
||
PrintWriter logWriter = new PrintWriter(fw)) {
|
||
|
||
Sheet sheet1 = workbook.getSheet("Sheet1");
|
||
Sheet sheet2 = workbook.getSheet("Sheet2");
|
||
|
||
Map<String, String> sheet1Data = new HashMap<>();
|
||
|
||
// 读取Sheet1的数据
|
||
for (Row row : sheet1) {
|
||
Cell keyCell1 = row.getCell(0);
|
||
Cell keyCell2 = row.getCell(1);
|
||
Cell valueCell = row.getCell(4);
|
||
|
||
if (keyCell1 != null && keyCell2 != null && valueCell != null) {
|
||
String key = keyCell1.toString() + "-" + keyCell2.toString();
|
||
String value = valueCell.toString();
|
||
sheet1Data.put(key, value);
|
||
}
|
||
}
|
||
|
||
// 比较Sheet2的数据并更新
|
||
for (Row row : sheet2) {
|
||
Cell keyCell1 = row.getCell(0);
|
||
Cell keyCell2 = row.getCell(1);
|
||
|
||
if (keyCell1 != null && keyCell2 != null) {
|
||
String key = keyCell1.toString() + "-" + keyCell2.toString();
|
||
if (sheet1Data.containsKey(key)) {
|
||
Cell newValueCell = row.createCell(4, CellType.STRING);
|
||
String newValue = sheet1Data.get(key);
|
||
newValueCell.setCellValue(newValue);
|
||
|
||
// 写入日志
|
||
logWriter.println("更新Sheet2: 第" + (row.getRowNum() + 1) + "行,第5列的新值为:" + newValue);
|
||
}
|
||
}
|
||
}
|
||
|
||
// 将更新后的工作簿写入到输出文件
|
||
try (FileOutputStream fos = new FileOutputStream(outputFilePath)) {
|
||
workbook.write(fos);
|
||
}
|
||
|
||
System.out.println("比较和更新已成功完成。");
|
||
|
||
} catch (IOException e) {
|
||
e.printStackTrace();
|
||
}
|
||
}
|
||
}
|