实现代码
word
//获取需要操作的word文件
FileInputStream fileInputStream = new FileInputStream(path);
XWPFDocument document = new XWPFDocument(fileInputStream);
//获取表格 这里获取的是文件中最后一个表格
XWPFTable table = document.getTables().get(document.getTables().size() - 1);
调用方法
// word跨行并单元格
public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
if ( rowIndex == fromRow ) { cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
} else {
cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
}
cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
}
}
最后保存
FileOutputStream fileOutputStream = new FileOutputStream(newPah);
document.write(fileOutputStream);
fileOutputStream.close();
excel
InputStream in = new FileInputStream(path);
XSSFWorkbook workbook = new XSSFWorkbook(in);
// 获取第一个工作表
XSSFSheet sheet = workbook.getSheetAt(0);
// 遍历行
Iterator<Row> rowIterator = sheet.iterator();
XSSFCellStyle cellStyle = workbook.createCellStyle();
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 14);
font.setFontName("宋体");// 设置标题字体
cellStyle.setFont(font);
cellStyle = workbook.createCellStyle();
cellStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 居中
Map<String,Integer> start = Maps.newHashMap();
Map<String,Integer> end = Maps.newHashMap();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// 获取第一个单元格的值
Cell cell = row.getCell(0);
String cellValue = cell.getStringCellValue();
//设置居中样式
CellStyle style = workbook.createCellStyle();
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
// 如果与上一行单元格的值相同,则合并单元格
if (row.getRowNum() > 5) {
if (start.containsKey(cellValue)){
end.put(cellValue,row.getRowNum());
}else {
start.put(cellValue,row.getRowNum());
}
}
}
for (String key : start.keySet()) {
if (end.containsKey(key)){
CellRangeAddress cellRangeAddress = new CellRangeAddress(start.get(key), end.get(key), 0, 0);
sheet.addMergedRegion(cellRangeAddress);
}
}
// 写出 Excel 文件
FileOutputStream outputStream = new FileOutputStream(newPath);
workbook.write(outputStream);
outputStream.close();
in.close();