public class ExcelWriterExample { public static void main(String[] args) throws Exception {用这个方法再写一个上面这个程序
时间: 2024-12-24 18:31:38 浏览: 5
当然可以。在这个`ExcelWriterExample`的基础上,我们继续创建一个类似的程序,这次将写入数据到Excel文件中。假设我们已经有了处理Excel数据的库,比如Apache POI。这是一个简单的例子:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWritingExample {
// 假设你有一个包含员工信息的数据列表
private static List<Employee> employeeData = ...; // 员工类需包含姓名、职位等属性
public static void writeToExcel(String filePath) throws IOException {
Workbook workbook = new XSSFWorkbook(); // 创建一个新的工作簿
Sheet sheet = workbook.createSheet("Employee Data"); // 创建新的工作表
// 获取第一行标题行的Row
Row headerRow = sheet.createRow(0);
Cell.cellType.createCell(headerRow.createCell(0), "Name");
Cell.cellType.createCell(headerRow.createCell(1), "Position");
// 遍历员工数据并写入Excel
for (int i = 0; i < employeeData.size(); i++) {
Employee employee = employeeData.get(i);
Row dataRow = sheet.createRow(i + 1); // 行索引从1开始
Cell nameCell = dataRow.createCell(0);
nameCell.setCellValue(employee.getName());
Cell positionCell = dataRow.createCell(1);
positionCell.setCellValue(employee.getPosition());
}
try (OutputStream outputStream = new FileOutputStream(filePath)) {
workbook.write(outputStream);
System.out.println("Data has been written to the Excel file at " + filePath);
} finally {
workbook.close(); // 关闭工作簿
}
}
public static void main(String[] args) {
String fileName = "employees.xlsx"; // Excel文件名
writeToExcel(fileName);
//
阅读全文