1. maven依赖:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
2. 读取Excel文件的代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import net.sf.json.JSONObject;
public class PoiUtils {
public static void main(String args[]) {
poiExcel();
}
public static void poiExcel() {
String filePath = "C:\\Users\\Administrator\\Desktop\\hehe.xls";
try {
List<Map> listMap = readExcel(filePath);
/*
*list中存放当前excel中所有的sheet,每个sheet为一个map
*
* 每个map:三个字段
* file_Name :excel文件名
sheet_Name :sheet文名
sheet_content :sheet内容
*/
for (int i = 0; i < listMap.size(); i++) {
Map tempMap = listMap.get(i);
String file_Name = (String) tempMap.get("file_Name");
String sheet_Name = (String) tempMap.get("sheet_Name");
String sheet_content = (String) tempMap.get("sheet_content");
// System.out.println(file_Name + "\t\t"+sheet_Name +"\t\t"+sheet_content);
JSONObject json = new JSONObject();
json.put("file_Name", file_Name);
json.put("sheet_Name", sheet_Name);
json.put("sheet_content", sheet_content);
System.out.println(json);
}
// for (Map map : listMap) {
// System.out.println(map);
// }
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 读取excel
* @param filePath
* @return List<Map>
* @throws Exception
*/
public static List<Map> readExcel(String filePath) throws Exception {
File file = new File(filePath);
if (!file.exists()) {
return null;
}
String suffix = "";
if (filePath.indexOf(".xlsx") != -1) {
suffix = ".xlsx";
} else if (filePath.indexOf(".xls") != -1) {
suffix = ".xls";
} else {
return null;
}
// 返回值列
List<Map> reaultList = new ArrayList<Map>();
if (".xls".equals(suffix)) {
reaultList = readExcel2003(filePath);
} else if (".xlsx".equals(suffix)) {
reaultList = readExcel2007(filePath);
}
return reaultList;
}
/**
* 读取97-2003格式(即xls格式)
*/
public static List<Map> readExcel2003(String filePath) throws IOException {
// 返回结果集
List<Map> resurtListMap = new ArrayList<Map>();
FileInputStream fis = null;
File file = new File(filePath);
String file_Name = file.getName();
try {
fis = new FileInputStream(filePath);
HSSFWorkbook wookbook = new HSSFWorkbook(fis); // 创建对Excel工作簿文件的引用
// 遍历所有sheet
for (int page = 0; page < wookbook.getNumberOfSheets(); page++) {
Map<String, String> sheet_map = new HashMap<>();
HSSFSheet sheet = wookbook.getSheetAt(page); // 在Excel文档中,第page张工作表的缺省索引是0
int rows = sheet.getPhysicalNumberOfRows(); // 获取到Excel文件中的所有行数
String sheet_Name = sheet.getSheetName();// sheet名称,用于校验模板是否正确
String sheet_content = "";
int cells = 0;// 当前sheet的行数
// 遍历sheet中所有的行
HSSFRow firstRow = sheet.getRow(page);
if (firstRow != null) {
// 获取到Excel文件中的所有的列
cells = firstRow.getPhysicalNumberOfCells();
for (int i = 0; i < rows; i++) {
// 读取左上端单元格
HSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
boolean isValidRow = false;
// 遍历列
for (int j = 0; j < cells; j++) {
// 获取到列的值
try {
HSSFCell cell = row.getCell(j);
String cellValue = getCellValue(cell);
if(cellValue == null)
{
cellValue = "";
}
sheet_content += cellValue+"\t";
if (!isValidRow && cellValue != null
&& cellValue.trim().length() > 0) {
isValidRow = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
sheet_content += "\n";
}
}
}
//封装每个sheet入map
sheet_map.put("file_Name", file_Name);
sheet_map.put("sheet_Name", sheet_Name);
sheet_map.put("sheet_content", sheet_content);
resurtListMap.add(sheet_map);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
fis.close();
}
return resurtListMap;
}
/**
* 读取2007格式(即xlsx)
*/
public static List<Map> readExcel2007(String filePath) throws IOException {
// 返回结果集
List<Map> resurtListMap = new ArrayList<Map>();
FileInputStream fis = null;
File file = new File(filePath);
String file_Name = file.getName();
try {
fis = new FileInputStream(filePath);
XSSFWorkbook wookbook = new XSSFWorkbook(fis); // 创建对Excel工作簿文件的引用
// 遍历所有sheet
for (int page = 0; page < wookbook.getNumberOfSheets(); page++) {
Map<String, String> sheet_map = new HashMap<>();
XSSFSheet sheet = wookbook.getSheetAt(page); // 在Excel文档中,第page张工作表的缺省索引是0
int rows = sheet.getPhysicalNumberOfRows(); // 获取到Excel文件中的所有行数
String sheet_Name = sheet.getSheetName();// sheet名称,用于校验模板是否正确
String sheet_content = "";
int cells = 0;// 当前sheet的行数
// 遍历sheet中所有的行
XSSFRow firstRow = sheet.getRow(page);
if (firstRow != null) {
// 获取到Excel文件中的所有的列
cells = firstRow.getPhysicalNumberOfCells();
for (int i = 0; i < rows; i++) {
// 读取左上端单元格
XSSFRow row = sheet.getRow(i);
// 行不为空
if (row != null) {
boolean isValidRow = false;
// 遍历列
for (int j = 0; j < cells; j++) {
// 获取到列的值
try {
XSSFCell cell = row.getCell(j);
String cellValue = getCellValue(cell);
if(cellValue == null)
{
cellValue = "";
}
sheet_content += cellValue+"\t";
if (!isValidRow && cellValue != null
&& cellValue.trim().length() > 0) {
isValidRow = true;
}
} catch (Exception e) {
e.printStackTrace();
}
}
sheet_content += "\n";
}
}
}
//封装每个sheet入map
sheet_map.put("file_Name", file_Name);
sheet_map.put("sheet_Name", sheet_Name);
sheet_map.put("sheet_content", sheet_content);
resurtListMap.add(sheet_map);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
fis.close();
}
return resurtListMap;
}
private static String getCellValue(HSSFCell cell) {
DecimalFormat df = new DecimalFormat("#");
String cellValue = null;
if (cell == null)
return null;
switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
break;
}
cellValue = df.format(cell.getNumericCellValue());
break;
case HSSFCell.CELL_TYPE_STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
case HSSFCell.CELL_TYPE_FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
case HSSFCell.CELL_TYPE_BLANK:
cellValue = null;
break;
case HSSFCell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case HSSFCell.CELL_TYPE_ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
if (cellValue != null && cellValue.trim().length() <= 0) {
cellValue = null;
}
return cellValue;
}
private static String getCellValue(XSSFCell cell) {
DecimalFormat df = new DecimalFormat("#");
String cellValue = null;
if (cell == null)
return null;
switch (cell.getCellType()) {
case XSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
cellValue = sdf.format(HSSFDateUtil.getJavaDate(cell
.getNumericCellValue()));
break;
}
cellValue = df.format(cell.getNumericCellValue());
break;
case XSSFCell.CELL_TYPE_STRING:
cellValue = String.valueOf(cell.getStringCellValue());
break;
case XSSFCell.CELL_TYPE_FORMULA:
cellValue = String.valueOf(cell.getCellFormula());
break;
case XSSFCell.CELL_TYPE_BLANK:
cellValue = null;
break;
case XSSFCell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case XSSFCell.CELL_TYPE_ERROR:
cellValue = String.valueOf(cell.getErrorCellValue());
break;
}
if (cellValue != null && cellValue.trim().length() <= 0) {
cellValue = null;
}
return cellValue;
}
}
3. 导出Excel文件为xls格式的代码:
package com.mongotest.bussiness.controller;
import java.io.FileOutputStream;
import java.io.OutputStream;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
public class ExcelUtil {
public static void main(String args[]) throws Exception {
String s = "小明,男,25,北大,二班;张三,女,23,清华,一班";
String[] sFirst = s.split(";");
String[][] word = new String[sFirst.length][];
for (int i = 0; i < sFirst.length; i++) {
String[] sSecond = sFirst[i].split(",");
word[i] = new String[sSecond.length];// 这步确定行不规则数组的每行长度
for (int j = 0; j < sSecond.length; j++) {
word[i][j] = sSecond[j];
}
}
//excel标题
String[] title = {"名称","性别","年龄","学校","班级"};
//excel文件名
String fileName = "C:\\Users\\Administrator\\Desktop\\学生信息表"+System.currentTimeMillis()+".xls";
//sheet名
String sheetName = "学生信息表";
//创建HSSFWorkbook
HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, word, null);
fileName = new String(fileName.getBytes(),"UTF-8");
OutputStream os = new FileOutputStream(fileName);
wb.write(os);
}
/**
* 导出Excel
* @param sheetName sheet名称
* @param title 标题
* @param values 内容
* @param wb HSSFWorkbook对象
*/
public static HSSFWorkbook getHSSFWorkbook(String sheetName, String[] title, String[][] values, HSSFWorkbook wb) {
// 第一步,创建一个HSSFWorkbook,对应一个Excel文件
if (wb == null) {
wb = new HSSFWorkbook();
}
// 第二步,在workbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet(sheetName);
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制
HSSFRow row = sheet.createRow(0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HorizontalAlignment.CENTER); // 创建一个居中格式
// 声明列对象
HSSFCell cell = null;
// 创建标题
for (int i = 0; i < title.length; i++) {
cell = row.createCell(i);
cell.setCellValue(title[i]);
cell.setCellStyle(style);
}
// 创建内容
for (int i = 0; i < values.length; i++) {
row = sheet.createRow(i + 1);
for (int j = 0; j < values[i].length; j++) {
// 将内容按顺序赋给对应的列对象
row.createCell(j).setCellValue(values[i][j]);
}
}
return wb;
}
}
4. 运行效果:
注意:HSSF类,只支持2007以前的excel(文件扩展名为xls),而XSSH支持07以后的(文件扩展名为xlsx)。转换的时候只更改扩展名是不对的,读取的时候可能会导致报错:The document is really a OOXML file。正确操作是要打开文件另存为。你可能将上面的那个导出为Excel文件的代码中导出文件的扩展名直接改为xlsx发现也能运行成功并生成相应的xlsx文件,但这样和直接修改文件的扩展名操作一样是不对的,正确的做法是应该使用XSSH来导出为xlsx文件,我代码里偷懒没有写而已。
5. 扩展:easyexcel
感觉 POI 有些复杂,等有时间了可以研究下 easyexcel,GitHub 地址:https://github.com/alibaba/easyexcel