Quick-guide - DataFormats
您需要使用单元格样式来格式化
Excel
具有特殊数字格式的单元格。
那些
CellStyle
在工作簿级别,可以根据需要创建,如上面链接的示例所示。但你不应该创造完全相同的
蜂窝式
limits for unique cell formats/cell styles
在里面
擅长
更灵活的方法是使用
CellUtil
. 在那里:
处理样式的各种方法允许您创建
需要。如果没有,那么它将创建一个新样式。这是为了防止
创建的样式太多。
使用它,我们可以创建一个结构,其中包含每行和每单元格的数据对象,以及一个结构,其中包含每列的数据格式。
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellUtil;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
class CreateExcelFormattedValues {
public static void main(String[] args) throws Exception {
Workbook workbook = new XSSFWorkbook();
DataFormat format = workbook.createDataFormat();
// structure which holds data objects per row and cell
Object[][] data = new Object[][]{
new Object[]{"Price", "Percent"},
new Object[]{203.9483495949, 0.53282},
new Object[]{0.8375733, 0.009383484}
};
// structure which holds data formats per column
short currencyDataFormat = format.getFormat("$#,##0.00");
short percentDataFormat = format.getFormat("0.00%");
short[] dataFormats = {currencyDataFormat, percentDataFormat};
Sheet sheet = workbook.createSheet();
Row row;
int firstRow = 1; // first row is second row
int r = 0; // loop variable for row
Cell cell;
int firstCol = 1; // first column is column B
int c = 0; // loop variable for column
for (Object[] dataRow : data) {
row = sheet.createRow(firstRow + r);
c = 0;
for (Object dataValue : dataRow) {
cell = row.createCell(firstCol + c);
CellUtil.setCellStyleProperty(cell, CellUtil.DATA_FORMAT, dataFormats[c]);
if (dataValue instanceof String) {
cell.setCellValue((String)dataValue);
} else if (dataValue instanceof Double) {
cell.setCellValue((Double)dataValue);
}
c++;
}
r++;
}
FileOutputStream out = new FileOutputStream("Excel.xlsx");
workbook.write(out);
out.close();
workbook.close();
}
}