java 合并 excel 相邻的相同行单元如图所示

excel合并相邻的相同行单元如图所示

如图所示

目标

效果
脑残了不小心把次数抹掉了

需要的jar包apache下的poi

下载地址:https://poi.apache.org/download.html
poi
导入所有的jar包(其实用不着所有,导入下面的包)

jar
jar
jar包

代码

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;


import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

//CellRangeAddress region = new CellRangeAddress(startRow, endRow, startCol, endCol);
//sheet.addMergedRegion(region);

public class Demo {
	/**
	 * 	合并相同的相邻行单元格
	 * @author hansh
	 */
	public static void read() {
		File file = new File("Demo.xlsx");
		String temp = "";
		int offset = 0, start = 0;
		CellRangeAddress region = null;
		try {
			FileInputStream fis = new FileInputStream(file);
			XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
			XSSFSheet xssfSheet = xssfWorkbook.getSheet("Sheet1");
			int lastNum = xssfSheet.getLastRowNum();
			for(int i = 0; i <= lastNum; i++) {
				XSSFRow hssfRow = xssfSheet.getRow(i);
				XSSFCell hssfCell = hssfRow.getCell(0);
				hssfCell.setCellType(CellType.STRING);
				String value = hssfCell.getStringCellValue();
				if(!temp.equals(value.trim()) || i == lastNum) {
					temp = value;
					if(i == lastNum) {
						offset++;
					}
					if(offset != 0) {
						region = new CellRangeAddress(start, start + offset, 0, 0);//0, 0表示第几列合并
						xssfSheet.addMergedRegion(region);
						region = new CellRangeAddress(start, start + offset, 10, 10);//10, 10表示有几列相同
						xssfSheet.addMergedRegion(region);
						hssfRow = xssfSheet.getRow(start);
						hssfCell = hssfRow.getCell(10);
						if(hssfCell == null) {
							hssfCell = hssfRow.createCell(10);
						}
						hssfCell.setCellValue(Integer.toString(offset + 1));
					}
					start = i;
					offset = 0;
				}else {
					hssfCell.setCellValue("");
					offset++;
				}
			}
			FileOutputStream fout = new FileOutputStream(file);
			xssfWorkbook.write(fout);
			fis.close();
			fout.close();
			xssfWorkbook.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		read();
		System.out.println("finish.....");
	}

}

代码写得不够人性化,研究研究吧!!!

发布了5 篇原创文章 · 获赞 0 · 访问量 123

猜你喜欢

转载自blog.csdn.net/qq_35867420/article/details/103042608