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>
讀取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;
}
}
導出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;
}
}
運行效果:
注意:HSSF類,只支持2007以前的excel(文件擴展名爲xls),而XSSH支持07以後的(文件擴展名爲xlsx)。轉換的時候只更改擴展名是不對的,讀取的時候可能會導致報錯:The document is really a OOXML file。正確操作是要打開文件另存爲。你可能將上面的那個導出爲Excel文件的代碼中導出文件的擴展名直接改爲xlsx發現也能運行成功並生成相應的xlsx文件,但這樣和直接修改文件的擴展名操作一樣是不對的,正確的做法是應該使用XSSH來導出爲xlsx文件,我代碼裏偷懶沒有寫而已。