java根据对象属性生成excel文件保存在本地
时间: 2023-11-23 12:11:03 浏览: 43
要将Java对象属性生成Excel文件并保存在本地,可以使用Apache POI库。下面是一个简单的示例代码:
```java
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelWriter {
public static void writeExcel(List<Person> personList, String filePath) throws IOException {
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet sheet = workbook.createSheet("Person Data");
int rowNumber = 0;
Row headerRow = sheet.createRow(rowNumber++);
Cell headerCell = headerRow.createCell(0);
headerCell.setCellValue("Name");
headerCell = headerRow.createCell(1);
headerCell.setCellValue("Age");
for (Person person : personList) {
Row row = sheet.createRow(rowNumber++);
Cell cell = row.createCell(0);
cell.setCellValue(person.getName());
cell = row.createCell(1);
cell.setCellValue(person.getAge());
}
FileOutputStream outputStream = new FileOutputStream(filePath);
workbook.write(outputStream);
workbook.close();
}
public static void main(String[] args) throws IOException {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Alice", 25));
personList.add(new Person("Bob", 30));
personList.add(new Person("Charlie", 35));
String filePath = "person_data.xlsx";
writeExcel(personList, filePath);
System.out.println("Excel file generated and saved to " + filePath);
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
在这个示例中,`Person`类表示一个人,有两个属性`name`和`age`。`ExcelWriter`类中的`writeExcel`方法将`Person`对象列表写入Excel文件。在`main`方法中,我们创建一个`Person`列表并调用`writeExcel`方法来生成Excel文件并将其保存在本地。
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)