1. 程式人生 > >java程式碼-Exccel工具類

java程式碼-Exccel工具類

package com.ufc.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


import org.apache.poi.POIXMLDocument;
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.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;




/**
 * 
 * @author 10000guo
 *  
 */
public class ExcelUtils {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";

private static HSSFWorkbook workbook = null;




 
 




/**
* 判斷檔案是否存在.

* @param fileDir
*            檔案路徑
* @return
*/
public static boolean fileExist(String fileDir) {
boolean flag = false;
File file = new File(fileDir);
flag = file.exists();
return flag;
}


/**
* 判斷檔案的sheet是否存在.

* @param fileDir
*            檔案路徑
* @param sheetName
*            表格索引名
* @return
*/
public static boolean sheetExist(String fileDir, String sheetName) throws Exception {
boolean flag = false;
File file = new File(fileDir);
if (file.exists()) { // 檔案存在
// 建立workbook
try {
workbook = new HSSFWorkbook(new FileInputStream(file));
// 新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯)
HSSFSheet sheet = workbook.getSheet(sheetName);
if (sheet != null)
flag = true;
} catch (Exception e) {
throw e;
}


} else { // 檔案不存在
flag = false;
}
return flag;
}


 


/**
* 刪除檔案.

* @param fileDir
*            檔案路徑
*/
public static boolean deleteExcel(String fileDir) {
boolean flag = false;
File file = new File(fileDir);
// 判斷目錄或檔案是否存在
if (!file.exists()) { // 不存在返回 false
return flag;
} else {
// 判斷是否為檔案
if (file.isFile()) { // 為檔案時呼叫刪除檔案方法
file.delete();
flag = true;
}
}
return flag;
}


/**
* 複製檔案
* @param f1 d:\ad.txt
* @param f2 c:\ad.txt
* @return
* @throws Exception
*/
public static long forTransfer(File f1,File f2) throws Exception{
        long time=new Date().getTime();
        int length=2097152;
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        int i=0;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                return new Date().getTime()-time;
            }
            if((inC.size()-inC.position())<20971520)
                length=(int)(inC.size()-inC.position());
            else
                length=20971520;
            inC.transferTo(inC.position(),length,outC);
            inC.position(inC.position()+length);
            i++;
        }
    }
 
/**
* 判斷Excel的版本,獲取Workbook

* @param in
* @param filename
* @return
* @throws IOException
*/
public static Workbook getWorkbok(File file) throws IOException {
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if (file.getName().endsWith(EXCEL_XLS)) { // Excel 2003
wb = new HSSFWorkbook(in);
} else if (file.getName().endsWith(EXCEL_XLSX)) { // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}


public static void main(String[] args) {
String[] a={"123.1","321","222"};
String[] b={"123","321","222"};
String[][] aa={{"11","111","111"},{"133","331","232"},{"153","351","55"}};
String[][] bb={{"11","112","111"},{"133","331","232"},{"153","351","55","66"}};

//建立oneSheet假資料
List list=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 3; i++) {
Map map = new HashMap<String, String>();
for (int j = 0; j < 3; j++) {
map.put("777"+j, "666"+j);
}
list.add(map);
}
String[] title={"7770","7771","7772"};


System.out.println(list);//[{7770=6660, 7772=6662, 7771=6661}, {7770=6660, 7772=6662, 7771=6661}, {7770=6660, 7772=6662, 7771=6661}]
String sheetName="123";




//建立SameTitel假資料
Random rand = new Random(); 
List list_same=new ArrayList<>();
for (int l = 0; l < 3; l++) {
List list_SameTitel1=new ArrayList<HashMap<String, String>>();
for (int i = 0; i < 3; i++) {//3 個sheet
Map map = new HashMap<String, String>();
for (int j = 0; j < 3; j++) {//3行資料
for (int k = 0; k < 3; k++) {//每行的資料
map.put("777"+j, rand.nextInt(100) + 1);
}
}
list_SameTitel1.add(map);
}
list_same.add(l, list_SameTitel1);
}
System.out.println(list_same);
//[[{7770=31, 7772=85, 7771=19}, {7770=61, 7772=10, 7771=79}, {7770=78, 7772=66, 7771=73}], [{7770=62, 7772=36, 7771=52}, {7770=68, 7772=7, 7771=46}, {7770=17, 7772=71, 7771=43}], [{7770=83, 7772=76, 7771=62}, {7770=48, 7772=6, 7771=18}, {7770=47, 7772=6, 7771=94}]]
String[] sheetName_SameTitel={"123","321","222"};

//[[{7770=51, 7772=58, 7771=68}, {7770=23, 7772=84, 7771=50}, {7770=40, 7772=18, 7771=24}], [{7770=12, 7772=96, 7771=23}, {7770=40, 7772=15, 7771=20}, {7770=97, 7772=73, 7771=61}], [{7770=91, 7772=68, 7771=70}, {7770=66, 7772=10, 7771=6}, {7770=48, 7772=45, 7771=64}]]



//建立DisaffinityTitel假資料
String[] sheetName_disaff={"123","321","222"};
String[][] title_disaff={{"110","111","112"},{"220","221","222"},{"440","441","442","443"}};
List list_disaff=new ArrayList<>();
for (int l = 0; l < 3; l++) {
List list_disaff1=new ArrayList<HashMap<String, String>>();
if (l==0) {
list_disaff1.clear();
for (int i = 0; i < 3; i++) {//3行資料
Map map = new HashMap<String, String>();
for (int k = 0; k < 3; k++) {//每行的資料
map.put("11"+k, rand.nextInt(100) + 1);
}
list_disaff1.add(map);
}
} else if (l==1){
list_disaff1.clear();
for (int i = 0; i < 3; i++) {//3行資料
Map map = new HashMap<String, String>();
for (int k = 0; k < 3; k++) {//每行的資料
map.put("22"+k, rand.nextInt(100) + 1);
}
list_disaff1.add(map);
}
} else if (l==2){
list_disaff1.clear();
for (int i = 0; i < 4; i++) {//4行資料
Map map = new HashMap<String, String>();
for (int k = 0; k < 4; k++) {//每行的資料
map.put("44"+k, rand.nextInt(100) + 1);
}
list_disaff1.add(map);
}
}

list_disaff.add(l, list_disaff1);
}
System.out.println(list_disaff);
//[[{110=99, 111=37, 112=83}, {110=37, 111=86, 112=79}, {110=93, 111=55, 112=59}], [{220=17, 221=48, 222=65}, {220=98, 221=51, 222=20}, {220=46, 221=79, 222=11}], [{440=69, 441=68, 442=54, 443=71}, {440=29, 441=53, 442=1, 443=52}, {440=47, 441=65, 442=88, 443=46}, {440=53, 441=70, 442=5, 443=12}]]


String path = ExcelUtils.filePath()+File.separator+"writeweather_sameTitel.xls";
System.out.println(path);
try {
//createExcel_OneSheet(path, "sheet123", a);
  //createExcel_ManySheet_SameTitel(path, b, a);
//createExcel_ManySheet_DisaffinityTitel(path, b, aa);

// JSONArray readExcel_OneSheet = readExcel_OneSheet(path, a);// readweather
// System.out.println(readExcel_OneSheet);
// JSONArray readExcel_SameTitel = readExcel_SameTitel(path, a);//  readweather_sameTitel
// System.out.println(readExcel_SameTitel);
// JSONArray readExcel_DisaffinityTitel = readExcel_DisaffinityTitel(path, bb);//  readweather_diffTitel
// System.out.println(readExcel_DisaffinityTitel);

// writeToExcel_OneSheet(path, sheetName, list, title); // writeweather
// writeToExcel_ManySheet_SameTitel(path, sheetName_SameTitel, list_same, title); // writeweather_sameTitel
// writeToExcel_ManySheet_DisaffinityTitel(path, sheetName_disaff, list_disaff, title_disaff); // writeweather_diffTitel

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

/** 
* 下載檔案 
* 返回byte[] 
* @param fileName 需要下載的檔名 
* @return 
* @throws Exception 
*/  
public static byte[] downFileByte(String downLoadPath) throws Exception{  
    byte[] return_arraybyte=null;  
        InputStream ins=new FileInputStream(downLoadPath );  
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();  
        byte[] buf = new byte[1024];  
        int bufsize = 0;  
        while ((bufsize = ins.read(buf, 0, buf.length)) != -1) {  
            byteOut.write(buf, 0, bufsize);  
        }  
        return_arraybyte = byteOut.toByteArray();  
        byteOut.close();  
        ins.close();  
return return_arraybyte;  
}


   /**
    * 靜態方法  解決建立Workbook 建立產生的問題(核心方法)
    * @param inp
    * @return
    * @throws IOException
    * @throws InvalidFormatException
    */
   public static Workbook createworkbook(InputStream inp) throws IOException,InvalidFormatException {
       if (!inp.markSupported()) {
           inp = new PushbackInputStream(inp, 8);
       }
       if (POIFSFileSystem.hasPOIFSHeader(inp)) {
           return new HSSFWorkbook(inp);
       }
       if (POIXMLDocument.hasOOXMLHeader(inp)) {
           return new XSSFWorkbook(OPCPackage.open(inp));
       }
       throw new IllegalArgumentException("你的excel版本目前poi解析不了");
   }
   
///////////////////////////////////////////////////////建立Excel方法/////////////////////////////////////////////////////////////
/**
* 建立一個新excel.  一個sheet

* @param fileDir
*            excel的路徑
* @param sheetName
*            要建立的表格索引
* @param titleRow
*            excel的第一行即表格頭
*/
public static void createExcel_OneSheet(String fileDir, String sheetName, String titleRow[]) throws Exception {
// 建立workbook
workbook = new HSSFWorkbook();
// 新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯)
HSSFSheet sheet1 = workbook.createSheet(sheetName);
// 新建檔案
FileOutputStream out = null;
try {
// 新增表頭
HSSFRow row = workbook.getSheet(sheetName).createRow(0); // 建立第一行
for (short i = 0; i < titleRow.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(titleRow[i]);
}
out = new FileOutputStream(fileDir);
workbook.write(out);
} catch (Exception e) {
throw e;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 建立一個新excel,多個sheet的名字, 表格頭都相同 

* @param fileDir
*            excel的路徑
* @param sheetName[]
*            要建立的表格索引名
* @param titleRow
*            excel的第一行即表格頭
*/
public static void createExcel_ManySheet_SameTitel(String fileDir, String[] sheetName, String titleRow[]) throws Exception {
// 建立workbook
workbook = new HSSFWorkbook();
// 新建檔案
FileOutputStream out = null;
try {
for (int k = 0; k < sheetName.length; k++) {
// 新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯)
HSSFSheet sheet1 = workbook.createSheet(sheetName[k]); 
// 新增表頭
HSSFRow row = workbook.getSheet(sheetName[k]).createRow(0); // 建立第一行
//HSSFSheet sheet1 = workbook.createSheet(); 建立預設名字的sheet
//HSSFRow row = workbook.getSheetAt(k).createRow(0);
for (short i = 0; i < titleRow.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(titleRow[i]);
}
out = new FileOutputStream(fileDir);
workbook.write(out);
}

} catch (Exception e) {
throw e;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 建立一個新excel,多個sheet的名字, 表格頭不相同 

* @param fileDir
*            excel的路徑
* @param sheetName[]
*            要建立的表格索引 
*            {"sheet1","sheet2","sheet3","sheet4",......}
* @param titleRow[][]
*            excel的第一行即表格頭
*            {{"專案編號","專案名稱","所屬事業部"...},{"編號1","名稱2","事業部3","專案經理4"...},{"編號5","名稱6","事業部7"...},{"11","22","33","44"...},...}
*/
public static void createExcel_ManySheet_DisaffinityTitel(String fileDir, String[] sheetName, String titleRow[][])
throws Exception {
// 建立workbook
workbook = new HSSFWorkbook();
// 新建檔案
FileOutputStream out = null;
try {
for (int k = 0; k < sheetName.length; k++) {
// 新增Worksheet(不新增sheet時生成的xls檔案開啟時會報錯)
HSSFSheet sheet1 = workbook.createSheet(sheetName[k]);
// 新增表頭
HSSFRow row = workbook.getSheet(sheetName[k]).createRow(0); // 建立第一行
// HSSFSheet sheet1 = workbook.createSheet(); 建立預設名字的sheet
// HSSFRow row = workbook.getSheetAt(k).createRow(0);
for (short i = 0; i < titleRow[k].length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(titleRow[k][i]);
}
out = new FileOutputStream(fileDir);
workbook.write(out);
}
} catch (Exception e) {
throw e;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
///////////////////////////////////////////////////////建立Excel方法完////////////////////////////////////////////////////////



///////////////////////////////////////////////////////寫入Excel方法////////////////////////////////////////////////////////
/**
* 往excel中寫入(已存在的資料無法寫入).

* @param fileDir
*            檔案路徑
* @param sheetName 
*            表格索引
* @param mapList 
*            需要寫入的資料
* @param titleRow[]
*            excel的第一行即表格頭
* @throws Exception
*/
public static void writeToExcel_OneSheet(String fileDir, String  sheetName, List<Map> mapList,String titleRow[]) throws Exception {
OutputStream out = null;
// 建立workbook
File file = new File(fileDir);
Workbook workBook = getWorkbok(file);
Sheet sheet = workBook.getSheet(sheetName);
// 刪除原有資料,除了屬性列
int rowNumber = sheet.getLastRowNum(); // 第一行從0開始算
Row row0 = sheet.getRow(0);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}
// 往Excel中寫新資料
for (int j = 0; j < mapList.size(); j++) {
// 建立一行:從第二行開始,跳過屬性列
Row row = sheet.createRow(j + 1);
Map dataMap = mapList.get(j);
System.out.println(dataMap);
int count = row0.getLastCellNum(); 
for (int k = 0; k <count; k++) {
for (int i = 0; i < titleRow.length; i++) {
Cell cell = row.createCell(k);
if (dataMap.get(titleRow[k])!=null) {
cell.setCellValue(dataMap.get(titleRow[k]).toString());
}
}
}
}
// 建立檔案輸出流,準備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
out = new FileOutputStream(fileDir);
workBook.write(out);
}

/**
* 往excel中寫入(已存在的資料無法寫入). 多個sheet,相同的表格頭

* @param fileDir
*            檔案路徑
* @param sheetName[]
*            表格索引
* @param mapList 
*            需要寫入的資料     
         * @param titleRow[]
*            excel的第一行即表格頭
* @param object
* @throws Exception
*/
public static void writeToExcel_ManySheet_SameTitel(String fileDir, String[]  sheetName, List<List<Map>> mapList,String titleRow[]) throws Exception {
OutputStream out = null;
// 建立workbook
File file = new File(fileDir);
Workbook workBook = getWorkbok(file);
for (int q = 0; q < sheetName.length; q++) {
Sheet sheet = workBook.getSheet(sheetName[q]);
// 刪除原有資料,除了屬性列
int rowNumber = sheet.getLastRowNum(); // 第一行從0開始算
Row row0 = sheet.getRow(0);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}
// 往Excel中寫新資料
List<Map> list = mapList.get(q);
for (int j = 0; j < list.size(); j++) {
// 建立一行:從第二行開始,跳過屬性列
Row row = sheet.createRow(j + 1);
Map dataMap = list.get(j);
System.out.println(dataMap);
int count = row0.getLastCellNum(); 
for (int k = 0; k <count; k++) {
for (int i = 0; i < titleRow.length; i++) {
Cell cell = row.createCell(k);
if (dataMap.get(titleRow[k])!=null) {
cell.setCellValue(dataMap.get(titleRow[k]).toString());
}
}
}
}
}
// 建立檔案輸出流,準備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
out = new FileOutputStream(fileDir);
workBook.write(out);
}

/**
* 往excel中寫入(已存在的資料無法寫入). 多個sheet,不相同的表格頭

* @param fileDir
*            檔案路徑
* @param sheetName[]
*            表格索引
* @param mapList 
*            需要寫入的資料                     
* @param titleRow[][]
*            excel的第一行即表格頭
* @param object
* @throws Exception
*/
public static void writeToExcel_ManySheet_DisaffinityTitel(String fileDir, String[]  sheetName, List<List<Map>> mapList,String titleRow[][]) throws Exception {
OutputStream out = null;
// 建立workbook
File file = new File(fileDir);
Workbook workBook = getWorkbok(file);
for (int q = 0; q < sheetName.length; q++) {
Sheet sheet = workBook.getSheet(sheetName[q]);
// 刪除原有資料,除了屬性列
int rowNumber = sheet.getLastRowNum(); // 第一行從0開始算
Row row0 = sheet.getRow(0);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow(row);
}
// 往Excel中寫新資料
List<Map> list = mapList.get(q);
for (int j = 0; j < list.size(); j++) {
// 建立一行:從第二行開始,跳過屬性列
Row row = sheet.createRow(j + 1);
Map dataMap = list.get(j);
System.out.println(dataMap);
int count = row0.getLastCellNum(); 
for (int k = 0; k <count; k++) {
for (int i = 0; i < titleRow[q].length; i++) {
Cell cell = row.createCell(k);
if (dataMap.get(titleRow[q][k])!=null) {
cell.setCellValue(dataMap.get(titleRow[q][k]).toString());
}
}
}
}
}
// 建立檔案輸出流,準備輸出電子表格:這個必須有,否則你在sheet上做的任何操作都不會有效
out = new FileOutputStream(fileDir);
workBook.write(out);
}
///////////////////////////////////////////////////////寫入Excel方法完////////////////////////////////////////////////////////




///////////////////////////////////////////////////////讀取Excel方法////////////////////////////////////////////////////////

/**
* 只讀sheet1,其餘sheet有值也不讀
* @param filePath
* @param excel_row
* @return
* @throws IOException
* @throws InvalidFormatException
*/
public static JSONArray readExcel_OneSheet(String filePath,String excel_row[]) throws IOException, InvalidFormatException {
InputStream is = new FileInputStream(filePath);
Workbook workbook = createworkbook(is);
JSONArray array = new JSONArray();
List<String> list = new ArrayList<>();
if (workbook != null) {
// Read the Sheet
for (int numSheet = 0; numSheet < 1; numSheet++) {//1 workbook.getNumberOfSheets();
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
// Read the Row
for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) {
JSONObject data = new JSONObject();
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
int start = row.getFirstCellNum();
int end = row.getLastCellNum();
boolean isRowBlank=true;
for(int i=start;i<end;i++){
Cell cell = row.getCell(i);
String element = "";
if (cell!=null&&!cell.equals("")) {
switch (cell.getCellType()) { 
case HSSFCell.CELL_TYPE_NUMERIC: // 數字    
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date d = cell.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
element = formater.format(d);
}else{
//因為數值會由12變成12.0 所以處理一下
String b=cell.getNumericCellValue()+"";
String bb=b.substring(b.lastIndexOf(".")+1);
if (Integer.valueOf(bb)==0) {
element =b.substring(0, b.lastIndexOf("."));
}else{
element = cell.getNumericCellValue() + "";
}
}
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_STRING: // 字串
element = cell.getStringCellValue();
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
element = cell.getBooleanCellValue() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
element = cell.getCellFormula() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
break;
default:
break;
}
}  
if(isRowBlank) continue;
 
if (rowNum == 0) {
list.add(i, element);
} else {
data.put(list.get(i), element);
}
}
if(rowNum == 0){
if(!validateFormat(list,excel_row)){
System.out.println("文件格式不正確");
return null;
}else{
System.out.println("驗證通過");
}
}
if (rowNum > 0&&!data.isEmpty())
array.add(data);
}
}
}
return array;
}




   /**
* 讀取Excel檔案,格式:.xls,.xlsx,多個sheet的標題頭格式必須保持一致
* 返回資料K-V格式,表頭作為key格式如下:[{"所屬專項名稱":"金鳳","指南方向":"指南方向","負責人":"XXX"}]
* @param filePath
*            檔案詳細地址 /path/excel.xls
* @param excel_row
*             Excel的標題頭
* @throws IOException 
* @throws InvalidFormatException 
* @return 合併多個sheet的row值
* [[{"321":"2","222":"3","123.1":"1"},{"321":"5","222":"6","123.1":"4"}],[{"321":"222","222":"333","123.1":"222"}],[{"321":"222","222":"222","123.1":"222"}]]
*/
public static JSONArray readExcel_SameTitel(String filePath,String[] excel_row) throws IOException, InvalidFormatException {
InputStream is = new FileInputStream(filePath);
Workbook workbook = createworkbook(is);
JSONArray array = new JSONArray();
List<String> list = new ArrayList<>();
if (workbook != null) {
// Read the Sheet
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
list.clear();
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
JSONArray array_sheet = new JSONArray();
// Read the Row
for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) {
JSONObject data = new JSONObject();
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
int start = row.getFirstCellNum();
int end = row.getLastCellNum();
boolean isRowBlank=true;
for(int i=start;i<end;i++){
Cell cell = row.getCell(i);
String element = "";
if (cell!=null&&!cell.equals("")) {
switch (cell.getCellType()) { 
case HSSFCell.CELL_TYPE_NUMERIC: // 數字    
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date d = cell.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
element = formater.format(d);
}else{
//因為數值會由12變成12.0 所以處理一下
String b=cell.getNumericCellValue()+"";
String bb=b.substring(b.lastIndexOf(".")+1);
if (Integer.valueOf(bb)==0) {
element =b.substring(0, b.lastIndexOf("."));
}else{
element = cell.getNumericCellValue() + "";
}
}
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_STRING: // 字串
element = cell.getStringCellValue();
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
element = cell.getBooleanCellValue() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
element = cell.getCellFormula() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
break;
default:
break;
}
}  
if(isRowBlank) continue;
 
if (rowNum == 0) {
list.add(i, element);
} else {
data.put(list.get(i), element);
}
}
if(rowNum == 0){
if(!validateFormat(list,excel_row)){
System.out.println("文件格式不正確");
return null;
}else{
System.out.println("驗證通過");
}
}
if (rowNum > 0&&!data.isEmpty()){
array_sheet.add(data);
}
}
array.set(numSheet, array_sheet); 
}
}
System.out.println("size:"+array.size());
System.out.println(array.toJSONString());
return array;
}




   /**
* 讀取Excel檔案,格式:.xls,.xlsx,多個sheet格式不一致
* 返回資料K-V格式,表頭作為key格式如下:[{"所屬專項名稱":"金鳳","指南方向":"指南方向","負責人":"XXX"}]
* @param filePath
*            檔案詳細地址 /path/excel.xls
* @param excel_row
*             多個sheet的標題頭 
* @throws IOException 
* @throws InvalidFormatException 
* @return
* [[{"11":"1","111":"3","112":"2"},{"11":"4","111":"6","112":"5"}],[{"133":"222","331":"222","232":"333"}],[{"55":"222","66":"2","153":"222","351":"222"}]]
*/
public static JSONArray readExcel_DisaffinityTitel(String filePath,String[][] excel_row) throws IOException, InvalidFormatException {
InputStream is = new FileInputStream(filePath);
Workbook workbook = createworkbook(is);
JSONArray array = new JSONArray();
List<String> list = new ArrayList<>();
if (workbook != null) {
// Read the Sheet
for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
list.clear();
Sheet sheet = workbook.getSheetAt(numSheet);
if (sheet == null) {
continue;
}
JSONArray array_sheet = new JSONArray();
// Read the Row
for (int rowNum = sheet.getFirstRowNum(); rowNum <= sheet.getLastRowNum(); rowNum++) {
JSONObject data = new JSONObject();
Row row = sheet.getRow(rowNum);
if (row == null) {
continue;
}
int start = row.getFirstCellNum();
int end = row.getLastCellNum();
boolean isRowBlank=true;
for(int i=start;i<end;i++){
Cell cell = row.getCell(i);
String element = "";
if (cell!=null&&!cell.equals("")) {
switch (cell.getCellType()) { 
case HSSFCell.CELL_TYPE_NUMERIC: // 數字    
if (HSSFDateUtil.isCellDateFormatted(cell)) {
Date d = cell.getDateCellValue();
DateFormat formater = new SimpleDateFormat("yyyy-MM-dd");
element = formater.format(d);
}else{
//因為數值會由12變成12.0 所以處理一下
String b=cell.getNumericCellValue()+"";
String bb=b.substring(b.lastIndexOf(".")+1);
if (Integer.valueOf(bb)==0) {
element =b.substring(0, b.lastIndexOf("."));
}else{
element = cell.getNumericCellValue() + "";
}
}
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_STRING: // 字串
element = cell.getStringCellValue();
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
element = cell.getBooleanCellValue() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_FORMULA: // 公式
element = cell.getCellFormula() + "";
isRowBlank=false;
break;
case HSSFCell.CELL_TYPE_BLANK: // 空值
break;
case HSSFCell.CELL_TYPE_ERROR: // 故障
break;
default:
break;
}
}  
if(isRowBlank) continue;
 
if (rowNum == 0) {
list.add(i, element);
} else {
data.put(list.get(i), element);
}
}
if(rowNum == 0){
if(!validateFormat(list,excel_row[numSheet])){
System.out.println("文件格式不正確");
return null;
}else{
System.out.println("驗證通過");
}
}
if (rowNum > 0&&!data.isEmpty())
array_sheet.add(data);
}
array.set(numSheet, array_sheet); 
}
}
System.out.println("size:"+array.size());
System.out.println(array.toJSONString());
return array;
}


///////////////////////////////////////////////////////讀取Excel方法完////////////////////////////////////////////////////////


/**
* 驗證標題頭
* @param list
* @param excel_row
* @return
*/
public static  boolean validateFormat(List<String> list,String excel_row[]){
boolean state =false;
if(list.size()==excel_row.length){
for (int i = 0; i < list.size(); i++) {
state = list.get(i).equals(excel_row[i]);
if (!state) {
break;
}
}
}
return state;
}

 
}