要基于两个日期参数导出到Excel,可以使用Apache POI库。以下是一个示例代码,说明了如何使用Apache POI在Java中导出带有两个日期参数的数据到Excel:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class ExcelExporter {
public static void main(String[] args) {
String startDate = "2022-01-01";
String endDate = "2022-01-31";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate start = LocalDate.parse(startDate, formatter);
LocalDate end = LocalDate.parse(endDate, formatter);
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Date Range");
// Create header row
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("Date");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("Day of Week");
// Populate data rows
int rowNum = 1;
while (start.isBefore(end) || start.isEqual(end)) {
Row row = sheet.createRow(rowNum++);
Cell cell1 = row.createCell(0);
cell1.setCellValue(start.format(formatter));
Cell cell2 = row.createCell(1);
cell2.setCellValue(start.getDayOfWeek().toString());
start = start.plusDays(1);
}
// Auto-size columns
sheet.autoSizeColumn(0);
sheet.autoSizeColumn(1);
// Save workbook to file
try (FileOutputStream fileOut = new FileOutputStream("date_range.xlsx")) {
workbook.write(fileOut);
System.out.println("Excel file exported successfully!");
} catch (IOException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
此代码将在项目目录下创建一个名为"date_range.xlsx"的Excel文件,其中包含从起始日期到结束日期的日期范围和对应的星期几。