java导出excel合并单元格
时间: 2023-06-18 20:03:30 浏览: 105
在Java中导出Excel并合并单元格,可以使用POI库来实现。
以下是一个示例代码,演示如何导出Excel并合并单元格:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
public class ExcelExportExample {
public static void main(String[] args) throws Exception {
// 创建Excel工作簿
Workbook workbook = new XSSFWorkbook();
// 创建Sheet
Sheet sheet = workbook.createSheet("Sheet1");
// 创建表头
Row headerRow = sheet.createRow(0);
Cell headerCell = headerRow.createCell(0);
headerCell.setCellValue("姓名");
headerCell = headerRow.createCell(1);
headerCell.setCellValue("年龄");
headerCell = headerRow.createCell(2);
headerCell.setCellValue("地址");
// 创建数据行
List<String[]> dataList = new ArrayList<>();
dataList.add(new String[]{"张三", "20", "北京"});
dataList.add(new String[]{"李四", "25", "上海"});
dataList.add(new String[]{"王五", "30", "广州"});
dataList.add(new String[]{"赵六", "35", "深圳"});
int rowIndex = 1;
for (String[] data : dataList) {
Row dataRow = sheet.createRow(rowIndex++);
Cell dataCell = dataRow.createCell(0);
dataCell.setCellValue(data[0]);
dataCell = dataRow.createCell(1);
dataCell.setCellValue(data[1]);
dataCell = dataRow.createCell(2);
dataCell.setCellValue(data[2]);
}
// 合并单元格
CellRangeAddress region = new CellRangeAddress(1, 2, 2, 2);
sheet.addMergedRegion(region);
// 输出Excel文件
FileOutputStream outputStream = new FileOutputStream("example.xlsx");
workbook.write(outputStream);
outputStream.close();
}
}
```
在上面的示例代码中,首先创建Excel工作簿和Sheet,然后创建表头和数据行,并将数据填充到单元格中。最后,使用`CellRangeAddress`类创建一个单元格区域,并将其添加到Sheet中,以实现单元格合并。最终,将Excel文件输出到磁盘上的文件中。
需要注意的是,上面的示例代码是使用XSSF格式的Excel文件(即.xlsx文件),如果需要使用旧版本的Excel文件(即.xls文件),可以使用HSSFWorkbook类代替XSSFWorkbook类。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)