文章目录
这里有一篇非常细致的文章,可供需要时候查看
Apache POI使用详解
1. 新建Maven项目,引入POI的依赖
<!-- apache POI for xls -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- apache POI for xlsx -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
2. 导出Excel(xls)
@Test
public void importExcel() throws IOException {
//创建新工作簿
HSSFWorkbook workbook = new HSSFWorkbook();
//新建工作表
HSSFSheet sheet = workbook.createSheet("sheet1");
//创建行,行号作为参数传递给createRow()方法,第一行从0开始计算
HSSFRow row = sheet.createRow(0);
//创建单元格,row已经确定了行号,列号作为参数传递给createCell(),第一列从0开始计算
HSSFCell cell = row.createCell(2);
//设置单元格的值,即C1的值(第一行,第三列)
cell.setCellValue("hello sheet");
//输出到磁盘中
FileOutputStream fos = new FileOutputStream(new File("D:\\exportTest.xls"));
workbook.write(fos);
workbook.close();
fos.close();
}
3. 读取Excel(xls)
@Test
public void importExcel() throws IOException {
//创建输入流
FileInputStream fis = new FileInputStream(new File("D:\\testExcel.xls"));
//通过构造函数传参
HSSFWorkbook workbook = new HSSFWorkbook(fis);
//获取工作表
HSSFSheet sheet = workbook.getSheetAt(0);
//获取行,行号作为参数传递给getRow方法,第一行从0开始计算
HSSFRow row = sheet.getRow(0);
//获取单元格,row已经确定了行号,列号作为参数传递给getCell,第一列从0开始计算
HSSFCell cell = row.getCell(2);
//获取单元格的值,即C1的值(第一行,第三列)
String cellValue = cell.getStringCellValue();
System.out.println("第一行第三列的值是"+cellValue);
workbook.close();
fis.close();
}
4. 导出Excel(xlsx)
@Test
public void exportExcel() throws IOException {
//创建工作簿
XSSFWorkbook workbook = new XSSFWorkbook();
//新建工作表
XSSFSheet sheet = workbook.createSheet("sheet1");
//创建行,0表示第一行
XSSFRow row = sheet.createRow(0);
//创建单元格行号由row确定,列号作为参数传递给createCell;第一列从0开始计算
XSSFCell cell = row.createCell(2);
//给单元格赋值
cell.setCellValue("hello sheet in Xlsx");
//创建输出流
FileOutputStream fos = new FileOutputStream(new File("D:\\testExcel.xlsx"));
workbook.write(fos);
workbook.close();
fos.close();
}
5. 读取Excel(xlsx)
@Test
public void importXlsx() throws IOException {
//创建输入流
FileInputStream fis = new FileInputStream(new File("D:\\testExcel.xlsx"));
//由输入流得到工作簿
XSSFWorkbook workbook = new XSSFWorkbook(fis);
//得到工作表
XSSFSheet sheet = workbook.getSheet("sheet1");
//得到行,0表示第一行
XSSFRow row = sheet.getRow(0);
//创建单元格行号由row确定,列号作为参数传递给createCell;第一列从0开始计算
XSSFCell cell = row.getCell(2);
//给单元格赋值
String cellValue = cell.getStringCellValue();
System.out.println("第一行第三列的值是"+cellValue);
workbook.close();
fis.close();
}
6. 通用方法处理xls和xlsx
@Test
public void importXlsOrXlsx() throws IOException{
String filePath = "D://testExcel.xls";
if(filePath.matches("^.+\\.(?i)((xls)|(xlsx))$"))
{
FileInputStream fis = new FileInputStream(filePath);
boolean is03Excell = filePath.matches("^.+\\.(?i)(xls)$")?true:false;
Workbook workbook = is03Excell ? new HSSFWorkbook(fis):new XSSFWorkbook(fis);
Sheet sheet = workbook.getSheetAt(0);
Row row = sheet.getRow(0);
Cell cell = row.getCell(2);
System.out.println("第一行第一列的数据是:"+cell.getStringCellValue());
workbook.close();
fis.close();
}
}
7. 综合案例
(1) 读取“user.xls”并储存于list集合中
user.xls中的数据如下图所示:
userImport.java
package com.fukaiit;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
public class UserImport {
public List<User> userImport(String filePath) {
List<User> userList = new ArrayList<User>();
try {
FileInputStream fio = new FileInputStream(filePath);
HSSFWorkbook workbook = new HSSFWorkbook(fio);
HSSFSheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
if (row.getRowNum() == 0) {// 首行表头不读取
continue;
}
User user = new User();
user.setUserName(row.getCell(0).getStringCellValue());
user.setPassword(row.getCell(1).getStringCellValue());
user.setAge((int) row.getCell(2).getNumericCellValue());
user.setAddress(row.getCell(3).getStringCellValue());
userList.add(user);
}
workbook.close();
fio.close();
} catch (IOException e) {
e.printStackTrace();
}
return userList;
}
}
TestUserImport.java
@Test
public void userImport(){
List<User> userList = new UserImport().userImport("D://user.xls");
for (User user : userList) {
System.out.println("用户信息为:"+user.getUserName()+";"+user.getPassword()+";"+user.getAge()+";"+user.getAddress());
}
}
运行输出如下:
(2) 将User对象组成的userList导出到userList.xls文件中
UserExport.java
package com.fukaiit;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class UserExport {
public void userExport(String filePath, List<User> userList){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet();
HSSFRow titleRow = sheet.createRow(0);
titleRow.createCell(0).setCellValue("用户名");
titleRow.createCell(1).setCellValue("密码");
titleRow.createCell(2).setCellValue("年龄");
titleRow.createCell(3).setCellValue("地址");
for (User user : userList) {
int lastRowNum = sheet.getLastRowNum();//获取最后一行行号
HSSFRow row = sheet.createRow(lastRowNum+1);
row.createCell(0).setCellValue(user.getUserName());
row.createCell(1).setCellValue(user.getPassword());
row.createCell(2).setCellValue(user.getAge());
row.createCell(3).setCellValue(user.getAddress());
}
try {
FileOutputStream fos = new FileOutputStream(filePath);
workbook.write(fos);
workbook.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
TestUserExport.java
@Test
public void userExport(){
List<User> userList = new ArrayList<User>();
for (int i = 0; i < 10; i++) {
User user = new User();
user.setUserName("sa"+i);
user.setPassword("upsd"+i);
user.setAge(21+i);
user.setAddress("浙江省");
userList.add(user);
}
new UserExport().userExport("D://userList.xls", userList);
}
导出效果如下图所示:
8. 总结
- 操作excel,Workbook->Sheet->Row->Cell,得到对应对象通常都是get方法,建立对应对象通常是create方法
- 设置sheet名称
HSSFSheet sheet = workbook.createSheet("测试名称");
OR
workbook.setSheetName(0, "testname");
- 设置单元格内容
cell.setCellValue("单元格内容");
- 获取sheet数目
workbook.getNumberOfSheets()
- 根据index取得sheet对象
HSSFSheet sheet = wb.getSheetAt(0);
- 取得有效的行数
int rowCount = sheet.getLastRowNum();
- 取得一行的有效单元格个数
row.getLastCellNum();
- 设置单元格格式
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
- 读取数值类型的单元格内容
cell.getNumericCellValue();
- 设置列宽、行高
sheet.setColumnWidth((short)column,(short)width);
row.setHeight((short)height);
- 添加区域,合并单元格
CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 3);
sheet.addMergedRegion(cellRangeAddress);
HSSFRow mergedRow = sheet.createRow(0);
HSSFCell mergedCell = mergedRow.createCell(0);
mergedCell.setCellValue("表格标题行");
- 根据单元格不同属性返回字符串数值
public String getCellStringValue(HSSFCell cell) {
String cellValue = "";
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING://字符串类型
cellValue = cell.getStringCellValue();
if(cellValue.trim().equals("")||cellValue.trim().length()<=0)
cellValue=" ";
break;
case HSSFCell.CELL_TYPE_NUMERIC: //数值类型
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA: //公式
cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
cellValue = String.valueOf(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_BLANK:
cellValue=" ";
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
break;
case HSSFCell.CELL_TYPE_ERROR:
break;
default:
break;
}
return cellValue;
}
- 设置样式
HSSFCellStyle style = wb.createCellStyle();
style.set*
- 设置字体样式的对象有HSSFCellStyle, HSSFFont, HSSFDataFormat等