excel表格合并单元格
时间: 2024-01-25 20:03:14 浏览: 38
你可以使用 Apache POI 库来操作 Excel 表格并合并单元格。以下是一个简单的示例代码:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class ExcelMergeCells {
public static void main(String[] args) {
// 创建工作簿
Workbook workbook = new XSSFWorkbook();
// 创建工作表
Sheet sheet = workbook.createSheet("Sheet1");
// 合并单元格
CellRangeAddress mergedRegion = new CellRangeAddress(0, 0, 0, 4);
sheet.addMergedRegion(mergedRegion);
// 设置合并后的单元格样式
CellStyle mergedCellStyle = workbook.createCellStyle();
mergedCellStyle.setAlignment(HorizontalAlignment.CENTER);
mergedCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
// 创建合并后的单元格
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Merged Cell");
cell.setCellStyle(mergedCellStyle);
// 输出到文件
try (FileOutputStream fileOut = new FileOutputStream("output.xlsx")) {
workbook.write(fileOut);
System.out.println("Excel 文件创建成功!");
} catch (IOException e) {
e.printStackTrace();
}
// 关闭工作簿
try {
workbook.close();
} catch (IOException e) {
e.printStackTrace();
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)