修改默认的excel单元格样式

两种方式可以实现这种功能:

方案一、 在xl/worksheet/sheet*.xml下增加一个cols子节点

这个节点从第一列到最后一列,style指向同一个单元格样式

<cols>
    <col min="1" max="16384" style="23" width="8.0" customWidth="false"/>
</cols>

实现代码:

@Test
public void lockColumns4() {
    try {
        String   fileName  = "/temp/lock11.xlsx";
        Workbook wb        = new XSSFWorkbook();
        Sheet    xssfSheet = wb.createSheet();
        //不可编辑的单元格样式
        CellStyle unlockedCellStyle = xssfSheet.getWorkbook().createCellStyle();
        unlockedCellStyle.setLocked(false);
        //可编辑的单元格样式
        CellStyle lockedCellStyle = xssfSheet.getWorkbook().createCellStyle();
        lockedCellStyle.setLocked(true);

        org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cTCol = ((XSSFSheet) xssfSheet).getCTWorksheet().getColsArray(0).addNewCol();
        cTCol.setMin(1);
        cTCol.setMax(SpreadsheetVersion.EXCEL2007.getMaxColumns());
        cTCol.setStyle(unlockedCellStyle.getIndex());

        xssfSheet.createRow(0).setRowStyle(lockedCellStyle);
        xssfSheet.createRow(1).setRowStyle(lockedCellStyle);

        xssfSheet.protectSheet("123456");
        wb.write(new FileOutputStream(fileName));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

方案二、 获取默认的单元格样式

第0号位的单元格样式就是默认的样式,在xl/styles.xml下有这样一个节点

<cellXfs count="1">
    <xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0">
        <alignment vertical="center" wrapText="true"/>
    </xf>
</cellXfs>

这个节点就是默认的单元格样式。
实现代码:

public class ExcelDefaultCellStyle {

    public static void main(String[] args) {
        try {

            Workbook wb = new XSSFWorkbook();

            Font font = wb.getFontAt((short) 0);
            font.setFontHeightInPoints((short) 24);
            font.setFontName("Courier New");
            ((XSSFFont) font).setFamily(3);
            ((XSSFFont) font).setScheme(FontScheme.NONE);
            font.setItalic(true);
            font.setBold(true);

            CellStyle style = wb.getCellStyleAt(0);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setWrapText(true);


            Sheet sheet = wb.createSheet();

            Row  row  = sheet.createRow(0);
            Cell cell = row.createCell(0);
            cell.setCellValue("test");

            FileOutputStream os = new FileOutputStream("/temp/defaultCell/ExcelDefaultCellStyle.xlsx");
            wb.write(os);
            os.close();

        } catch (IOException ioex) {
            ioex.printStackTrace();
        }
    }
}

第二种方式在mac平台下对于单元格的加锁与解锁是不生效的,亲测。

附录: xlsx的文件结构

07版office采用的是open office xml的文件格式。将.xlsx的文件后缀名改成.zip, 解压缩,可以看到如下的文件结构:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/bruce128/article/details/78948052