利用poi把数据保存excel,并格式化日期实例

下面是一个简单的小例子,利用poi进行保存excel操作。

package com.cn;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class CellTypes {
 public static void main(String[] args) throws IOException {
     HSSFWorkbook wb = new HSSFWorkbook();
     HSSFSheet sheet = wb.createSheet("new sheet");
     HSSFRow row = sheet.createRow(2);
     row.createCell(0).setCellValue(1.1);
     row.createCell(1).setCellValue(new Date());
     row.createCell(2).setCellValue("a string");
     row.createCell(3).setCellValue(true);
     row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR);

     FileOutputStream fileOut = new FileOutputStream("d:\\workbook.xls");
     wb.write(fileOut);
     fileOut.close();
 }
}

下面的是运行结果

在运行结果中发现时间的显示是正常的时间,怎么格式化时间呢?

下面的例子就是格式化时间

package com.cn;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

public class CellTypes {
 public static void main(String[] args) throws IOException {
     HSSFWorkbook wb = new HSSFWorkbook();
     HSSFSheet sheet = wb.createSheet("new sheet");
     
	 HSSFRow row = sheet.createRow(2);
	 row.createCell(0).setCellValue(1.1);
	 Cell cell = row.createCell(1);
     cell.setCellValue(new Date());
     CreationHelper createHelper = wb.getCreationHelper();
     CellStyle cellStyle = wb.createCellStyle();
     cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("yyyy-MM-dd"));
     cell.setCellStyle(cellStyle);
     
     row.createCell(2).setCellValue("a string");
     row.createCell(3).setCellValue(true);
     row.createCell(4).setCellType(HSSFCell.CELL_TYPE_ERROR);

     FileOutputStream fileOut = new FileOutputStream("d:\\workbook.xls");
     wb.write(fileOut);
     fileOut.close();
 }
}

运行结果如下:



你可能感兴趣的:(Date,String,Excel,Class)