有两种可能性来实现XSSF。
第一:如果您在Excel XSSF工作表中的所有单元格,并应用样式给他们,然后cols
元素被添加到片上,风格定义为所有列:
<cols>
<col min="1" max="16384" style="1"/>
</cols>
这可以使用apache poi来实现,如下所示:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
class ExcelCellStyleAllColumns
{
public static void main(String[] args) {
try {
Workbook wb = new XSSFWorkbook();
Font font = wb.createFont();
font.setFontHeightInPoints((short)24);
font.setFontName("Courier New");
font.setItalic(true);
font.setBold(true);
CellStyle style = wb.createCellStyle();
style.setFont(font);
Sheet sheet = wb.createSheet();
org.openxmlformats.schemas.spreadsheetml.x2006.main.CTCol cTCol =
((XSSFSheet)sheet).getCTWorksheet().getColsArray(0).addNewCol();
cTCol.setMin(1);
cTCol.setMax(16384);
cTCol.setWidth(12.7109375);
cTCol.setStyle(style.getIndex());
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
cell.setCellStyle(style);
FileOutputStream os = new FileOutputStream("ExcelCellStyleAllColumns.xlsx");
wb.write(os);
os.close();
} catch (IOException ioex) {
}
}
}
这将更改工作表中所有单元格的默认单元格样式。
二:您可以修改细胞的正常样式的样式定义,像这样:
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.*;
import java.io.FileOutputStream;
import java.io.IOException;
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(CellStyle.VERTICAL_CENTER);
style.setWrapText(true);
((XSSFWorkbook) wb).getStylesSource().getCTStylesheet().addNewCellStyles().addNewCellStyle().setXfId(0);
((XSSFCellStyle)style).getStyleXf().addNewAlignment().setVertical(
org.openxmlformats.schemas.spreadsheetml.x2006.main.STVerticalAlignment.CENTER);
((XSSFCellStyle)style).getStyleXf().getAlignment().setWrapText(true);
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellValue("test");
FileOutputStream os = new FileOutputStream("ExcelDefaultCellStyle.xlsx");
wb.write(os);
os.close();
} catch (IOException ioex) {
}
}
}
这将改变所有单元格的默认单元格样式在整个工作簿。
的XML在styles.xml
显示:
<cellStyleXfs count="1">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0">
<alignment vertical="center" wrapText="true"/>
</xf>
</cellStyleXfs>
<cellXfs count="1">
<xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0">
<alignment vertical="center" wrapText="true"/>
</xf>
</cellXfs>
<cellStyles>
<cellStyle xfId="0"/>
</cellStyles>
正如你所看到的正常细胞风格在cellStyles
第一个。它指的是xfId="0"
,它是指numFmtId="0"
fontId="0"
fillId="0"
borderId="0"
。这意味着数字格式,字体,填充格式和边框的第一个定义在正常单元格样式中使用。
太棒了!非常感谢你的详细帮助。非常感激! – Gurtz