javal导出excel,如何将单元格做成时间选择
时间: 2024-05-29 07:12:53 浏览: 59
可以使用Apache POI库来实现将单元格做成时间选择的功能。具体实现方法如下:
1. 创建一个Workbook对象,如下所示:
Workbook wb = new HSSFWorkbook();
2. 创建一个Sheet对象,如下所示:
Sheet sheet = wb.createSheet("Sheet1");
3. 创建一个CellStyle对象,设置单元格的格式为时间格式,如下所示:
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
4. 创建一个Row对象和一个Cell对象,并将CellStyle对象应用到Cell对象上,如下所示:
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(cellStyle);
5. 设置单元格的值为当前时间,如下所示:
cell.setCellValue(new Date());
6. 将Workbook对象写入到输出流中,生成Excel文件,如下所示:
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
完整代码示例:
import java.io.FileOutputStream;
import java.util.Date;
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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class ExcelExport {
public static void main(String[] args) throws Exception {
Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("Sheet1");
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFormat(wb.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
cell.setCellStyle(cellStyle);
cell.setCellValue(new Date());
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
}
}
阅读全文