Java POI分为2种模式:POI-HSSF、POI-XSSF
官方文档中对Java POI的说明:文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
HSSF is the POI Project\'s pure Java implementation of the Excel \'97(-2007) file format. XSSF is the POI Project\'s pure Java implementation of the Excel 2007 OOXML (.xlsx) file format.文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
简单说下,就是文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
HSSF:HSSF支撑Excel 97-2007(不包含2007)版本的文件,一般后缀名为.xls文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
XSSF:XSSF支撑Excel 2007及以上版本的文件,一般后缀名为.xlsx文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
接下来就说下POI对Excel的简单的操作,在写代码以前,咱们需要导入一些包来做支撑:(可以到官网去下载)文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
官网文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
jar包文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
(由于我电脑是2013版的Excel,所以使用的是POI-XSSF)文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
1、新建一个Workbook类文章源自微观生活(93wg.com)微观生活-https://93wg.com/17025.html
// 创立workbook
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream(\"workbook.xlsx\");
wb.write(fileOut);
fileOut.close();
2、新建一个sheet页
// 新建sheet页
Sheet sheet1 = wb.createSheet(\"new sheet\");
Sheet sheet2 = wb.createSheet(\"second sheet\");
3、新建一个单元格Cell
// 必需先创立一行
Row row = sheet.createRow(0);
// 然后在该行创立一个单元格
Cell cell = row.createCell(0);
// 给单元格设置值
cell.setCellValue(1);
4、设置单元格日期
// 先创立一个CreationHelper
CreationHelper createHelper = wb.getCreationHelper();
// 设置日期值
cell.setCellValue(new Date());
// 创立单元格的格式并设置
CellStyle cellStyle = wb.createCellStyle();
cellStyle.setDataFromat(createHelper.createDataFromat().getFormat(\"YY/MM/DD HH:妹妹:ss\"));
// 设置单元格的格式
cell.setCellStyle(cellStyle);
5、打开Excel的输入流,利便读取数据
// 获取Excel对象wb
Workbook wb = new XSSFWorkbook(new File(\"file path\"));
官方给出的例子:
// XSSFWorkbook, File
OPCPackage pkg = OPCPackage.open(new File(\"file.xlsx\"));
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();
// XSSFWorkbook, InputStream, needs more memory
OPCPackage pkg = OPCPackage.open(myInputStream);
XSSFWorkbook wb = new XSSFWorkbook(pkg);
....
pkg.close();
6、节制单元格的边框
// 创立单元格的格式
CellStyle style = wb.createCellStyle();
// 设置单元格的下边框
style.setBorderBottom(BorderStyle.THIN);
style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
// 设置单元格的做左侧框
style.setBorderLeft(BorderStyle.THIN);
style.setLeftBorderColor(IndexedColors.GREEN.getIndex());
// 设置单元格的右侧框
style.setBorderRight(BorderStyle.THIN);
style.setRightBorderColor(IndexedColors.BLUE.getIndex());
// 设置单元格的上边框
style.setBorderTop(BorderStyle.MEDIUM_DASHED);
style.setTopBorderColor(IndexedColors.BLACK.getIndex());
// 设置单元格的格式
cell.setCellStyle(style);
如果有兴致的童鞋,可以进入官网去渐渐学习,小编今天主要说了一些POI的简单操作,让你知道其实Java操作Excel也不是一件很难得事情。
评论