Java Excel 时间日期数据间隔插入 - Apache POI 实现
可以使用 Apache POI 库来读取和写入 Excel 文件。下面是一个示例代码,可以实现你的需求:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class DateInsertion {
public static void main(String[] args) {
String inputFile = 'input.xlsx';
String outputFile = 'output.xlsx';
String sheetName = 'P1';
try {
FileInputStream fis = new FileInputStream(inputFile);
Workbook workbook = new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheet(sheetName);
List<Date> dates = getDates(sheet);
boolean hasGapGreaterThan10Days = true;
while (hasGapGreaterThan10Days) {
hasGapGreaterThan10Days = false;
List<Date> newDates = new ArrayList<>();
for (int i = 0; i < dates.size() - 1; i++) {
Date current = dates.get(i);
Date next = dates.get(i + 1);
long diffInDays = getDifferenceInDays(current, next);
if (diffInDays > 10) {
hasGapGreaterThan10Days = true;
newDates.add(current);
newDates.addAll(getIntermediateDates(current, next));
} else {
newDates.add(current);
}
}
newDates.add(dates.get(dates.size() - 1));
dates = newDates;
}
updateSheet(sheet, dates);
FileOutputStream fos = new FileOutputStream(outputFile);
workbook.write(fos);
workbook.close();
fos.close();
System.out.println('Dates insertion completed successfully.');
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<Date> getDates(Sheet sheet) {
List<Date> dates = new ArrayList<>();
for (Row row : sheet) {
Cell cell = row.getCell(0);
if (cell != null && cell.getCellType() == CellType.NUMERIC) {
Date date = cell.getDateCellValue();
dates.add(date);
}
}
return dates;
}
private static long getDifferenceInDays(Date date1, Date date2) {
long diffInMs = Math.abs(date2.getTime() - date1.getTime());
return diffInMs / (24 * 60 * 60 * 1000);
}
private static List<Date> getIntermediateDates(Date start, Date end) {
List<Date> intermediateDates = new ArrayList<>();
Calendar calendar = Calendar.getInstance();
calendar.setTime(start);
calendar.add(Calendar.DAY_OF_MONTH, 1);
while (calendar.getTime().before(end)) {
intermediateDates.add(calendar.getTime());
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
return intermediateDates;
}
private static void updateSheet(Sheet sheet, List<Date> dates) {
int rowIndex = 0;
for (Date date : dates) {
Row row = sheet.getRow(rowIndex);
if (row == null) {
row = sheet.createRow(rowIndex);
}
Cell cell = row.getCell(0);
if (cell == null) {
cell = row.createCell(0);
}
cell.setCellValue(date);
rowIndex++;
}
}
}
请确保将 input.xlsx 替换为你的输入文件的路径,并将 output.xlsx 替换为你想要保存结果的文件路径。另外,请确保你的 Excel 文件中 P1 工作表的日期数据位于第一列。
这段代码会读取输入文件中的日期数据,然后根据你的要求进行插入操作,直到每个相邻的日期间隔小于 10 天。最后,它会将结果写入到输出文件中。
原文地址: https://www.cveoy.top/t/topic/fToQ 著作权归作者所有。请勿转载和采集!