我有一个字符串数组,其值如下:
String[] myArray = new String[4];
myArray[0] = "one";
myArray[1] = "2012-02-25";
myArray[2] = "12345.58";
myArray[3] = "1245";
我想使用 POI 将此数组写入 Excel 工作表,其中每个值将进入新列,如下所示:
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("mySheet");
Row myRow = sheet.createRow(1);
Cell myCell;
for(int i=0;i < my.length;i++){
myCell = myRow.createCell(i);
myCell.setCellValue(myArray[i]);
sheet.autoSizeColumn(i);
}
FileOutputStream out;
try {
out = new FileOutputStream("myOutputFile");
wb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
但是,很明显,所有内容都将作为文本转储到 Excel 工作表中。我在每个单元格的左上角收到一个绿色通知,指示“数字存储为文本”等。
假设,由于源系统限制,我将无法更改获取输入的方式,即我将继续仅以字符串形式获取输入,我如何处理字符串内实际值的格式并将日期转储为Excel 中的日期、数字作为数字、文本作为文本以及 double 值作为正确的十进制格式的 double 值?
请注意,我没有有关在字符串中获取的值类型的信息。我必须在运行时决定该值是否是文本、数字、 float 、日期等,然后将其适本地放入 Excel 工作表中。
在正确阅读之前,请勿标记问题。
感谢您的阅读!
最佳答案
您可以使用以下代码..
if(myArray[i].matches(".*\\d.*") && ! myArray[i].contains("-")) //For date assuming '-' would be a separator always
{
//Its a number(int or float).. Excel treats both as numeric
HSSFCellStyle style = (HSSFCellStyle) wb.createCellStyle();
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
mycell.setCellStyle(style);
mycell.setCellValue(Float.parseFloat(myArray[i]));
}
else if(myArray[i].contains("-"))
{
// Its a date
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy h:mm"));
mycell.setCellStyle(cellStyle);
mycell.setCellValue(myArray[i]);
}
else
{
// Its a string/Text..
mycell.setCellValue(myArray[i]);
}
关于java - 在 POI 中写入 Excel 工作表之前格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18956209/