java 导出exsel文档 代码
时间: 2023-11-26 13:02:28 浏览: 56
以下是使用Apache POI库导出Excel文档的Java代码示例:
```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.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void main(String[] args) {
List<Person> persons = new ArrayList<Person>();
persons.add(new Person("John", "Doe", 30));
persons.add(new Person("Jane", "Doe", 25));
persons.add(new Person("Bob", "Smith", 40));
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Persons");
int rowCount = 0;
Row headerRow = sheet.createRow(rowCount++);
Cell firstNameHeaderCell = headerRow.createCell(0);
firstNameHeaderCell.setCellValue("First Name");
Cell lastNameHeaderCell = headerRow.createCell(1);
lastNameHeaderCell.setCellValue("Last Name");
Cell ageHeaderCell = headerRow.createCell(2);
ageHeaderCell.setCellValue("Age");
for (Person person : persons) {
Row row = sheet.createRow(rowCount++);
Cell firstNameCell = row.createCell(0);
firstNameCell.setCellValue(person.getFirstName());
Cell lastNameCell = row.createCell(1);
lastNameCell.setCellValue(person.getLastName());
Cell ageCell = row.createCell(2);
ageCell.setCellValue(person.getAge());
}
try (FileOutputStream outputStream = new FileOutputStream("persons.xlsx")) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
}
```
此代码将创建一个包含人员信息的Excel文档,并将其保存到名为“persons.xlsx”的文件中。可以通过更改“persons”工作表的名称,更改文档的输出路径等来进行自定义。
阅读全文