1. apache poi包里有4個主要的類:
- Workbook------工作表,通過WorkbookFactory的create(FileInputStream fis)方法獲取核行,
- Sheet------------表格秧了,Workbook實例的getSheetAt(int num)方法獲取刊愚,
- Row--------------行,Sheet實例的getRow(int num)方法獲取栅哀,
- Cell--------------單元格丑婿,Row實例的getCell(int num)方法獲取,
最后通過Cell實例根據(jù)數(shù)據(jù)類型調(diào)用對應(yīng)的方法獲取單元格的值娄周。
2. 代碼
package com.upi.institution.utils;
import com.upi.institution.common.utils.CommonUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class ExcelUtil {
private static Logger logger = LoggerFactory.getLogger(ExcelUtil.class);
private static Workbook workbook;
private static Sheet sheet;
/**
* 初始化表格涕侈,判斷文件格式是xls還是xlsx
* @param excelPath
*/
private static void initExcel(String excelPath){
if (CommonUtils.isEmpty(excelPath)){
logger.info("文件路徑不能為空");
workbook = null;
return;
}
try {
InputStream is = new FileInputStream(excelPath);
if (excelPath.endsWith(".xls")){//.xls格式
workbook = new HSSFWorkbook(is);
}else if(excelPath.endsWith(".xlsx")){//.xlsx格式
workbook = new XSSFWorkbook(is);
}else{
workbook = null;
logger.info("無法轉(zhuǎn)換的Excel文件格式(后綴名應(yīng)為:.xls或.xlsx)");
}
} catch (FileNotFoundException e) {
logger.info("找不到指定文件");
} catch (IOException e) {
logger.info("IO異常");
}
}
/**
* 讀取Excel文件并解析成json字符串后寫入新的文件
* @param excelPath 要解析的Excel文件路徑(具體文件)
* @param fromRow 指定開始讀取的行數(shù),如從第2行開始則為2
* @param filePath 寫入json后的文件保存位置(文件路徑)
*/
private static void readExcelToJsonFile(String excelPath, int headerNum, int fromRow, String filePath){
initExcel(excelPath);
if(workbook == null){
logger.info("初始化工作簿失敗");
return;
}
for(int s=0; s<workbook.getNumberOfSheets(); s++){//遍歷sheet
sheet = workbook.getSheetAt(s);
Row headerRow = getRow(sheet, headerNum);//首行煤辨,即json-key
int rowNum = sheet.getLastRowNum() + 1;//總行數(shù)
for(int i=(fromRow-1); i<rowNum; i++){//遍歷行,從fromRow行開始遍歷
Map<String, String > map = new HashMap<String, String>();
Row row = sheet.getRow(i);
if(row == null){
continue;
}
int cellNum = row.getLastCellNum();//總列數(shù)
for(int j=0; j<cellNum; j++){//遍歷單元格
String key = getCellValue(headerRow.getCell(j));
String value = getCellValue(row.getCell(j));
if(!CommonUtils.isEmpty(key) && !CommonUtils.isEmpty(value)){
map.put(key, value);
}
}
String jsonStr = JsonUtil.toJson(map);//將map解析成json字符串
String fileName = UUIDUtil.UUID("002");//生成隨機文件名裳涛,以"002"開頭
String finalFilePath = filePath + "\\" + fileName + ".txt";//最終保存的文件路徑
FileUtil.writeToFile(finalFilePath, jsonStr, false);//將json字符串寫入文件,不追加众辨,每一行數(shù)據(jù)即生成一個文件
String fileNamePath = filePath + "\\fileNames.txt";//保存所有隨機文件名
FileUtil.writeToFile(fileNamePath, (fileName + "\r\n"), true);//將文件名寫入fileNames.txt文本中
}
logger.info("成功讀取Excel并生成文件");
}
}
/**
* 獲取指定行
* @param sheet
* @param rowNum
* @return
*/
private static Row getRow(Sheet sheet, int rowNum){
if(sheet == null){
return null;
}
return sheet.getRow(rowNum - 1);
}
/**
* 獲取單元格的值
* @param cell
* @return 單元格值
*/
private static String getCellValue(Cell cell){
String cellValue = "";
if(cell != null){
switch (cell.getCellType()){//單元格類型
case Cell.CELL_TYPE_BOOLEAN://布爾類型
cellValue = cell.getBooleanCellValue() + "";
break;
case Cell.CELL_TYPE_NUMERIC://數(shù)字類型
if (DateUtil.isCellDateFormatted(cell)) {//格式化后的日期數(shù)值類型
cellValue = new DataFormatter().formatCellValue(cell);
} else {
//數(shù)值
double value = cell.getNumericCellValue();
int intValue = (int) value;
cellValue = value - intValue == 0 ? String.valueOf(intValue) : String.valueOf(value);
}
break;
case Cell.CELL_TYPE_FORMULA:{//公式
try{
cellValue = cell.getNumericCellValue() + "";
}catch(IllegalStateException e){
cellValue = String.valueOf(cell.getRichStringCellValue());
}
}
break;
case Cell.CELL_TYPE_STRING://字符串
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BLANK://空值
cellValue = "";
break;
case Cell.CELL_TYPE_ERROR://故障
cellValue = "非法字符";
break;
default:
cellValue = "未知類型";
break;
}
}
return cellValue.trim();
}
public static void main(String[] args) {
String test = "C:\\Users\\Administrator\\Desktop\\test.xls";
String filePath = "C:\\Users\\Administrator\\Desktop";
readExcelToJsonFile(test, 1, 2, filePath);
}
}
3. 測試
運行代碼: