用java导出excel表格
时间: 2024-03-09 21:17:41 浏览: 71
以下是使用Java导出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.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExportExcelExample {
public static void main(String[] args) {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("姓名");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("年龄");
Cell headerCell3 = headerRow.createCell(2);
headerCell3.setCellValue("性别");
// 填充数据
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三", 20, "男"));
personList.add(new Person("李四", 25, "女"));
personList.add(new Person("王五", 30, "男"));
int rowIndex = 1;
for (Person person : personList) {
Row dataRow = sheet.createRow(rowIndex++);
Cell dataCell1 = dataRow.createCell(0);
dataCell1.setCellValue(person.getName());
Cell dataCell2 = dataRow.createCell(1);
dataCell2.setCellValue(person.getAge());
Cell dataCell3 = dataRow.createCell(2);
dataCell3.setCellValue(person.getGender());
}
// 导出Excel文件
try (FileOutputStream outputStream = new FileOutputStream("person.xlsx")) {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
}
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 int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
```
这个示例代码创建了一个包含表头和数据的Excel表格,并将其导出到名为“person.xlsx”的文件中。你可以根据需要修改表格的内容和文件名。
阅读全文