1、依赖包
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.5-FINAL</version>
</dependency>
2、写xls格式文件
Workbook wb = new XSSFWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
//创建页
Sheet sheet = wb.createSheet("sheet1");
// 创建行
Row row = sheet.createRow((short) 0);
// 创建单元格
row.createCell(0).setCellValue(258258258);
row.createCell(1).setCellValue(0.67);
row.createCell(2).setCellValue(createHelper.createRichTextString("http://www.lookhan.com"));
row.createCell(3).setCellValue(createHelper.createRichTextString("Java知识笔记"));
// 写入文件
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("D:\\lookhan.xlsx");
wb.write(fileOut);
fileOut.close();
System.out.println("写入成功!");
3、写xls格式文件
HSSFWorkbook workbook = new HSSFWorkbook();
// 在Excel工作簿中建一工作表,其名为缺省值
// HSSFSheet sheet = workbook.createSheet("");
HSSFSheet sheet = workbook.createSheet();
HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString("applicationNo"));
cell = row.createCell(1);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(new HSSFRichTextString("userId"));
// 写入文件
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("D:\\lookhan.xls");
workbook.write(fileOut);
fileOut.close();
System.out.println("写入成功!");
4、读取xlsx文件
// 构造 XSSFWorkbook 对象,strPath 传入文件路径
XSSFWorkbook xwb = new XSSFWorkbook("D:\\lookhan.xlsx");
// 读取第一章表格内容
XSSFSheet sheet = xwb.getSheetAt(0);
// 定义 row、cell
XSSFRow row;
String cell;
// 循环输出表格中的内容
for (int i = sheet.getFirstRowNum(); i < sheet.getPhysicalNumberOfRows(); i++) {
row = sheet.getRow(i);
for (int j = row.getFirstCellNum(); j < row.getPhysicalNumberOfCells(); j++) {
// 通过 row.getCell(j).toString() 获取单元格内容,
cell = row.getCell(j).toString();
System.out.print(cell + "\t");
}
System.out.println("");
}
<!--EndFra-->