可以通過(guò)Apache POI庫(kù)來(lái)操作Excel文件,實(shí)現(xiàn)合并單元格并設(shè)置內(nèi)容居中。下面是一個(gè)簡(jiǎn)單的示例代碼:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileOutputStream;
import java.io.IOException;
public class MergeCellsExample {
public static void main(String[] args) {
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("Merged Cell");
CellStyle style = workbook.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER);
style.setVerticalAlignment(VerticalAlignment.CENTER);
cell.setCellStyle(style);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 5));
try (FileOutputStream fileOut = new FileOutputStream("workbook.xlsx")) {
workbook.write(fileOut);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
在這個(gè)示例中,首先創(chuàng)建一個(gè)新的Workbook和Sheet對(duì)象,然后創(chuàng)建一個(gè)新的Row和Cell對(duì)象,并設(shè)置單元格的值為"Merged Cell"。接著創(chuàng)建一個(gè)CellStyle對(duì)象,并設(shè)置單元格內(nèi)容的水平和垂直居中。然后調(diào)用addMergedRegion方法合并單元格,最后將Workbook寫(xiě)入到文件中。
這樣就實(shí)現(xiàn)了在Excel文件中合并單元格并設(shè)置內(nèi)容居中的操作。