java 导出Excel
时间: 2023-09-04 10:12:02 浏览: 93
java导出Excel
3星 · 编辑精心推荐
在Java中,可以使用Apache POI库来导出Excel文件。以下是一个示例代码,将数据导出到Excel文件:
```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 ExcelExportExample {
public static void main(String[] args) {
// 创建一个工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
// 创建一个工作表
XSSFSheet sheet = workbook.createSheet("数据表");
// 创建表头
Row headerRow = sheet.createRow(0);
String[] headers = { "姓名", "年龄", "性别" };
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
// 填充数据
List<Person> persons = new ArrayList<>();
persons.add(new Person("张三", 20, "男"));
persons.add(new Person("李四", 22, "女"));
persons.add(new Person("王五", 18, "男"));
for (int i = 0; i < persons.size(); i++) {
Person person = persons.get(i);
Row row = sheet.createRow(i + 1);
row.createCell(0).setCellValue(person.getName());
row.createCell(1).setCellValue(person.getAge());
row.createCell(2).setCellValue(person.getGender());
}
// 导出Excel文件
try (FileOutputStream outputStream = new FileOutputStream("data.xlsx")) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
static class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
}
```
上述代码中,我们使用了XSSFWorkbook和XSSFSheet类来创建工作簿和工作表,并使用Row和Cell类来创建表头和填充数据。最后,使用FileOutputStream类将工作簿导出到Excel文件中。
需要注意的是,需要在项目中引入Apache POI库的依赖,具体的依赖配置可以查看官方文档:https://poi.apache.org/
阅读全文