【发布时间】:2017-11-28 07:32:28
【问题描述】:
我创建了一个创建 excel 表的程序,其中包含一些数据 第 1 列 - 包含字符串 第 2 列 - 包含数字(基本上是一个整数,但在阅读为什么它被转换为 Float 时?)
public class ApachePOI8 {
public static void main(String[] args) {
String file = "C:\\Eclipse workspace\\PoiExample\\Excel8.xlsx";
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
sheet.protectSheet("Pwd1"); //This statements locks the entire sheet with password: Pwd1
DataFormat fmt = wb.createDataFormat(); //created a textStyle, which prevents Excel to interprate data, in short it means it will be taken as String
CellStyle textStyle = wb.createCellStyle();
textStyle.setDataFormat(fmt.getFormat("@"));
textStyle.setLocked(false);
CellStyle numerStyle = wb.createCellStyle();
numerStyle.setDataFormat(fmt.getFormat("0"));
numerStyle.setLocked(false);
Row row0 = CellUtil.getRow(0, sheet);
for (int columnIndex = 0; columnIndex<4; columnIndex++){
Cell cell = CellUtil.getCell(row0, columnIndex);
if(columnIndex == 0) {
cell.setCellStyle(textStyle);
cell.setCellValue("Product 1");
}else if(columnIndex == 1) {
cell.setCellStyle(numerStyle);
cell.setCellValue(1);
}
}
else{
cell.setCellStyle(textStyle);
}
} //end of for Loop
try {
FileOutputStream outputStream = null;
outputStream = new FileOutputStream(file);
wb.write(outputStream);
outputStream.close();
System.out.println("Done!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
现在阅读生成的 excel 表
public class ApachePOIExcelRead {
private static final String FILE_NAME = "C:\\Eclipse workspace\\PoiExample\\Excel8.xlsx";
public static void main(String[] args) {
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_NAME));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
//getCellTypeEnum shown as deprecated for version 3.15
//getCellTypeEnum ill be renamed to getCellType starting from version 4.0
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print("String: "+currentCell.getStringCellValue() + "\n");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print("NUMERIC "+currentCell.getNumericCellValue() + "\n");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
但我得到的输出为 字符串:产品 1 NUMERIC 1.0 字符串:12-12-12
为什么输入的数字,即 1 以浮点数 NUMERIC 1.0 的形式出现?
请推荐。
【问题讨论】:
标签: java apache apache-poi