java导出excel动态表头
时间: 2023-09-04 21:17:18 浏览: 108
java实现导出excel表
4星 · 用户满意度95%
Java 中可以使用 Apache POI 库来操作 Excel 文件。如果表头是动态的,可以采用以下方法来实现动态表头:
1. 首先,创建工作簿和工作表对象:
```
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
```
2. 创建表头行和数据行:
```
Row headerRow = sheet.createRow(0);
Row dataRow = sheet.createRow(1);
```
3. 动态生成表头并写入表头行:
```
String[] headers = {"姓名", "年龄", "性别"};
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
```
4. 写入数据行:
```
String[] data = {"张三", "18", "男"};
for (int i = 0; i < data.length; i++) {
Cell cell = dataRow.createCell(i);
cell.setCellValue(data[i]);
}
```
5. 最后,将工作簿写入到输出流中:
```
OutputStream outputStream = new FileOutputStream("test.xlsx");
workbook.write(outputStream);
outputStream.close();
```
完整代码示例:
```
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelExporter {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row headerRow = sheet.createRow(0);
Row dataRow = sheet.createRow(1);
String[] headers = {"姓名", "年龄", "性别"};
for (int i = 0; i < headers.length; i++) {
Cell cell = headerRow.createCell(i);
cell.setCellValue(headers[i]);
}
String[] data = {"张三", "18", "男"};
for (int i = 0; i < data.length; i++) {
Cell cell = dataRow.createCell(i);
cell.setCellValue(data[i]);
}
OutputStream outputStream = new FileOutputStream("test.xlsx");
workbook.write(outputStream);
outputStream.close();
}
}
```
执行以上代码,将生成一个名为 test.xlsx 的 Excel 文件,其中包含一个工作表,动态生成的表头为“姓名”、“年龄”、“性别”,数据行中包含一条数据“张三”、“18”、“男”。
阅读全文