JAVA execl获取sheet页,并为其sheet页中的内容添加边框
1.添加前:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210526145949897.png)
2.添加后:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210526150102824.png)
代码
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
public class ExeclUtil {
public static void SetBorder(String path) throws EncryptedDocumentException, InvalidFormatException, IOException {
FileInputStream inp = new FileInputStream(path);
Workbook wb = WorkbookFactory.create(inp);
//获取sheet页页数
int numberOfSheets = wb.getNumberOfSheets();
for (int K = 0; K < numberOfSheets; K++) {
Sheet sheet = wb.getSheetAt(K);
//获得总列数
int coloumNum=sheet.getRow(0).getPhysicalNumberOfCells();
//获得总行数
int rowNum=sheet.getLastRowNum();
CellStyle cellStyle = wb.createCellStyle();
//下边框
cellStyle.setBorderBottom(XSSFCellStyle.BORDER_THIN);
//左边框
cellStyle.setBorderLeft(XSSFCellStyle.BORDER_THIN);
//上边框
cellStyle.setBorderTop(XSSFCellStyle.BORDER_THIN);
//右边框
cellStyle.setBorderRight(XSSFCellStyle.BORDER_THIN);
for (int i = 0; i <= rowNum; i++) {
Row row = sheet.getRow(i);
for (int j = 0; j <coloumNum; j++) {
Cell cell2 = row.getCell(j);
cell2.setCellStyle(cellStyle);
}
}
}
wb.write(new FileOutputStream(path));
}
}
测试
public static void main(String[] args) throws Exception {
ExeclUtil.SetBorder("excel文件地址");
}