一.POI的简介
POI(Poor Obfuscation Implementation)是Apache提供的操作ms office格式文档的API。本文主要针对excel进行操作。使用POI可以操作Excel 95及以后的版本,即可操作后缀为 .xls 和 .xlsx两种格式的excel。
二.针对普通的java项目
1.导入相关jar包

对于只操作2003及以前版本的excel,只需要导入poi-XXX.jar ,如果还需要对2007及以后版本进行操作,则需要导入
poi-ooxml-XXX.jar
poi-ooxml-schemas-XXX.jar
2.导入excel文件(XLSX文件)
@Test
public void readXlsx2() throws Exception{
FileInputStream inputStrem = new FileInputStream("D:/t1.xlsx");
// 创建工作簿的对象
// 针对xlsx后缀的文件,使用XSSF....类
XSSFWorkbook workBook = new XSSFWorkbook(inputStrem);
// 根据索引获取Sheet对象
XSSFSheet sheet = workBook.getSheetAt(0);
// 获取最后一行的索引
int num = sheet.getLastRowNum();
// 遍历所有行
for(int i = 0; i <= num; i++){
// 根据索引获取行对象
XSSFRow row = sheet.getRow(i);
// 根据索引获取单元格的对象
XSSFCell cell = row.getCell(0);
// 获取单元格的内容,如果是字符串,使用getStringCellValue
System.out.println(cell.getStringCellValue());
XSSFCell cell2 = row.getCell(1);
if(cell2 != null){
// 如果是数字,使用getNumericCellValue
System.out.println(cell2.getNumericCellValue());
}
}
// 关闭工作簿
workBook.close();
}
3.导入xls文件事例
@Test
public void readXls() throws Exception{
FileInputStream inputStrem = new FileInputStream("D:/t2.xls");
// 创建工作簿的对象
// 针对xls后缀的文件,使用HSSF....类
HSSFWorkbook workBook = new HSSFWorkbook(inputStrem);
// 根据索引获取Sheet对象
HSSFSheet sheet = workBook.getSheetAt(0);
// 根据索引获取行对象
HSSFRow row = sheet.getRow(0);
// 根据索引获取单元格的对象
HSSFCell cell = row.getCell(0);
// 获取单元格的内容,如果是字符串,使用getStringCellValue
System.out.println(cell.getStringCellValue());
HSSFCell cell2 = row.getCell(1);
// 如果是数字,使用getNumericCellValue
System.out.println(cell2.getNumericCellValue());
// 关闭工作簿
workBook.close();
}
4.导出xlsx文件事例
@Test
public void writeXlsx() throws Exception{
List<Map<String, Object>> list = new ArrayList<>();
for(int i = 0; i < 5; i++){
Map<String, Object> map = new HashMap<>();
map.put("name","zhangsan" + i);
map.put("age", 20 + i);
map.put("tel", "12345678901");
list.add(map);
}
String[] titles = new String[]{"姓名", "年龄", "电话"};
// 新建工作簿对象
XSSFWorkbook workBook = new XSSFWorkbook();
// 创建sheet对象
XSSFSheet sheet = workBook.createSheet("学生信息");
// 创建行,标题行
XSSFRow row = sheet.createRow(0);
for(int i = 0; i < titles.length; i++){
// 创建单元格
XSSFCell cell = row.createCell(i);
// 设置单元格内容
cell.setCellValue(titles[i]);
}
for(int i = 0; i < list.size(); i++){
XSSFRow row2 = sheet.createRow(i + 1);
row2.createCell(0).setCellValue((String)list.get(i).get("name"));
row2.createCell(1).setCellValue((Integer)list.get(i).get("age"));
row2.createCell(2).setCellValue((String)list.get(i).get("tel"));
}
// 写excel需要使用输出流
FileOutputStream outputStream = new FileOutputStream("D:/t3.xlsx");
workBook.write(outputStream);
outputStream.flush();
outputStream.close();
workBook.close();
}
三.如果是针对创建好的Maven Web项目,需要用到依赖包:步骤如下:
1.导入相关依赖包
需要用到文件上传的包,相关依赖如下:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.4</version>
</dependency>
重要的当然还需要用到POI的相关依赖包:
<!-- poi -->
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<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文件为例列出前端和后台的简要写法:
(1)前端如下:
<form action="importExcel" method="post" enctype="multipart/form-data">
<input type="file" name="upfile" /><br />
<input type="submit" value="导入" />
</form>
<a href="exportExcel?file=export.xlsx">导出</a>
(2)写一个工具类ExcelUtils,将导入导出的操作放入到工具类中:
public class ExcelUtils {
// 导入
public static void importExcel(String fileName, InputStream inputStream) throws Exception{
boolean ret = isXls(fileName);
// 根据不同的后缀,创建不同的对象
Workbook workBook = null;
if(ret){
workBook = new HSSFWorkbook(inputStream);// xls
}else{
workBook = new XSSFWorkbook(inputStream);// xlsx
}
Sheet sheet = workBook.getSheetAt(0);
int num = sheet.getLastRowNum();
for(int i = 0; i <= num; i++){
Row row = sheet.getRow(i);
Cell cell = row.getCell(0);
if(cell != null){
System.out.println(cell.getStringCellValue());
}
cell = row.getCell(1);
if(cell != null){
System.out.println(cell.getNumericCellValue());
}
}
workBook.close();
}
public static void exportExcel(OutputStream outputStream) throws Exception{
List<Map<String, Object>> list = new ArrayList<>();
for(int i = 0; i < 5; i++){
Map<String, Object> map = new HashMap<>();
map.put("name","zhangsan" + i);
map.put("age", 20 + i);
map.put("tel", "12345678901");
list.add(map);
}
String[] titles = new String[]{"姓名", "年龄", "电话"};
// 新建工作簿对象
XSSFWorkbook workBook = new XSSFWorkbook();
// 创建sheet对象
XSSFSheet sheet = workBook.createSheet("学生信息");
// 创建行,标题行
XSSFRow row = sheet.createRow(0);
for(int i = 0; i < titles.length; i++){
// 创建单元格
XSSFCell cell = row.createCell(i);
// 设置单元格内容
cell.setCellValue(titles[i]);
}
for(int i = 0; i < list.size(); i++){
XSSFRow row2 = sheet.createRow(i + 1);
row2.createCell(0).setCellValue((String)list.get(i).get("name"));
row2.createCell(1).setCellValue((Integer)list.get(i).get("age"));
row2.createCell(2).setCellValue((String)list.get(i).get("tel"));
}
workBook.write(outputStream);
workBook.close();
}
// .xls .XLS .xlsx .XLSX
// aaa.xls ddd.XLSX
public static boolean isXls(String fileName){
// js /^.+\.(xls)$/i
// (?i) 右边的内容,忽略大小写
if(fileName.matches("^.+\\.(?i)(xls)$")){
return true;
}else if(fileName.matches("^.+\\.(?i)(xlsx)$")){
return false;
}else{
throw new RuntimeException("文件格式不对");
}
//Pattern p = Pattern.compile("^.+\\.(xls)$", )
}
}
(3)后台如下,我直接跳过Dao层和Service层写Controller层:
@Controller
public class UploadController {
@RequestMapping("/importExcel")
// 必须是@RequestParam MultipartFile
public String upload(@RequestParam MultipartFile upfile){
// 获取上传的文件的文件名
String filename = upfile.getOriginalFilename();
try {
// 获取文件的输入流
InputStream inputStream = upfile.getInputStream();
// 解析exel文件,进行导入操作
ExcelUtils.importExcel(filename, inputStream);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "index";
}
@RequestMapping("/exportExcel")
public void download(String file, HttpServletResponse response) throws IOException{
// 如果文件名中有中文,需要进行url编码
file = URLEncoder.encode(file, "utf-8");
// %E6%96%B0%E5%BB%BA%E6%96%87%E6%9C%AC%E6%96%87%E6%A1%A3.txt
System.out.println(file);
// 设置响应头,进行下载操作
response.setHeader("Content-Disposition", "attachment;filename=" + file);
// 通过响应对象获取输出流
ServletOutputStream outputStream = response.getOutputStream();
try {
// 导出
ExcelUtils.exportExcel(outputStream);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
outputStream.close();
}
}
网友评论