有兩種可能性來實現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