1、首先大家来看导出的结果

14、java实现poi操作excel,包括读和写日期格式,并且设置字体样式-LMLPHP

下边就是导出的代码了

protected void testExcel() throws IOException{
String path=getServletContext().getRealPath("/WEB-INF/Template/timeSequence.xlsx");
System.out.println(path);
InputStream input=new FileInputStream(path);
XSSFWorkbook workBook=new XSSFWorkbook(input);
XSSFSheet hssfSheet = workBook.getSheet("Sheet1");
XSSFRow hssfRow=null;
XSSFCell cell=null;
XSSFFont font=workBook.createFont();
font.setFontName("GE Inspira"); OutputStream out=new FileOutputStream(path);
XSSFSheet hssfSheet2 = workBook.createSheet("Sheet2");
for (int i = 0; i < hssfSheet.getLastRowNum(); i++) { hssfRow=hssfSheet.getRow(i);
XSSFRow row=hssfSheet2.createRow(i);
for (int j = 0; j < hssfRow.getLastCellNum(); j++) {
CellStyle style=workBook.createCellStyle();
style.setFont(font);
cell=hssfRow.getCell(j);
XSSFCell cellWrite=row.createCell(j);
if(cell.getCellType()==cell.CELL_TYPE_STRING){
//set value for strings
cellWrite.setCellValue(cell.getStringCellValue());
cellWrite.setCellStyle(style);
}else if(cell.getCellType()==cell.CELL_TYPE_NUMERIC){
//set Value for date
if(HSSFDateUtil.isCellDateFormatted(cell)){
DateFormat format=new SimpleDateFormat();
short df=workBook.createDataFormat().getFormat("yyyy-MM-dd");
style.setDataFormat(df);
cellWrite.setCellStyle(style);
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd");
String readDateValue=dateFormat.format(cell.getDateCellValue());
cellWrite.setCellValue(readDateValue);
}else{
//set value for numeric
cellWrite.setCellValue(cell.getNumericCellValue());
cellWrite.setCellStyle(style);
}
}else if(cell.getCellType()==cell.CELL_TYPE_BLANK){
//set value for blank
cellWrite.setCellValue("");
cellWrite.setCellStyle(style);
}else{
cellWrite.setCellValue(cell.getStringCellValue());
cellWrite.setCellStyle(style);
}
}
}
workBook.write(out);
}

excel模板的存放位置

14、java实现poi操作excel,包括读和写日期格式,并且设置字体样式-LMLPHP

如有非作者本人光顾的十分十分感谢

05-11 23:02