题目
编写两个线程分别读取x1和x2两个Excel表,并且将读取的数据写入表x3,要求线程一直执行,每隔2秒写入一次x3。
x1表:
x2表:
代码
public class ThreadMain {
//记录x3表在第几行
private static int value = 0;
public static void main(String[] args) {
//x3表的工作簿和工资表
XSSFWorkbook setExcel = new XSSFWorkbook();
XSSFSheet sheet1 = setExcel.createSheet("x3.xlsx");
File file1 = new File("x3.xlsx");
File file2 = new File("x1.xlsx");
File file3 = new File("x2.xlsx");
test(setExcel, sheet1, file2,file1);
test(setExcel, sheet1, file3,file1);
}
/**
* test方法创建一个线程,执行读表和写表操作
* @param setExcel 写入表的工作簿
* @param sheet1 写入表的工作表
* @param getExcel 读取表文件名
* @param toExcel 写入表文件名
*/
public static void test(XSSFWorkbook setExcel, XSSFSheet sheet1, File getExcel, File toExcel) {
Thread t1 = new Thread(() -> {
try (FileInputStream in = new FileInputStream(getExcel);
XSSFWorkbook excel = new XSSFWorkbook(in)) {
XSSFSheet sheet = excel.getSheetAt(0);
int lastRow = sheet.getLastRowNum();
User user = new User(); //存储数据对象
for (int i = 1; i <= lastRow; i++) { //读取数据
XSSFRow row = sheet.getRow(i);
user.setName(row.getCell(0).getStringCellValue());
user.setYw((int) row.getCell(1).getNumericCellValue());
user.setSx((int) row.getCell(2).getNumericCellValue());
user.setYy((int) row.getCell(3).getNumericCellValue());
System.out.println(user);
}
int x = 1;
while(x <= 5) { //这里方便测试只测试5次
FileOutputStream out = new FileOutputStream(toExcel);
synchronized (Math.class) { //写入数据,这里需要使用synchronized锁,防止并非带来的问题
XSSFRow row = sheet1.createRow(value);
System.out.println(value);
row.createCell(0).setCellValue(user.getName());
row.createCell(1).setCellValue(user.getYw());
row.createCell(2).setCellValue(user.getSx());
row.createCell(3).setCellValue(user.getYy());
setExcel.write(out);
value++; //进入下一行
}
user.better(); //数据部分翻倍
x++;
System.out.println(Thread.currentThread().getName() + " : 写入一条数据");
Thread.sleep(1000); //休眠1秒
}
} catch (IOException e) {
System.out.println(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
t1.start();
}
}
//实体类
public class User {
private String name;
private Integer yw;
private Integer sx;
private Integer yy;
public void better() { //数据部分翻倍
yw *= 2;
sx *= 2;
yy *= 2;
}
}
输出:
注意
- 需要用到线程,因此应该熟悉java多线程,并发,锁等相关知识。
- 涉及Excel表的操作,因此需要掌握apache api框架,基本操作可以查看这篇文章:Apache POI(使用Java读写Excel表格数据)
- 由于需要用两个线程写入x3表,因此x3的工作簿和工作表应该是唯一的。