1. 程式人生 > >關於Java Web使用Excel的兩種格式xls、xlsx的導如匯出(重點看方法體 要理解好)

關於Java Web使用Excel的兩種格式xls、xlsx的導如匯出(重點看方法體 要理解好)

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;


@SuppressWarnings("all")
public class Main {
    public static void main(String[] args) {
        String enter = getEnter();// 獲取鍵盤輸入
        System.out.println("正在驗證...");
        File file = new File(enter);
        boolean bool = judeFileExists(file);// 判斷檔案是否存在
        if (bool) {
            extract(file);// 提取地址
        }
    }


    // 判斷檔案是否存在
    private static boolean judeFileExists(File file) {
        if (file.exists()) {
            System.out.println("檔案存在!正在進行解析,請稍等...");
            return true;
        } else {
            System.out.print("檔案不存在...,請重新輸入路徑—>");
            String enter = getEnter();
            File reFile = new File(enter);
            boolean bool = judeFileExists(reFile);// 判斷檔案是否存在
            if (bool) {
                extract(reFile);// 提取地址
            }
            return false;
        }
    }


    // 獲取鍵盤輸入字串
    private static String getEnter() {
        Scanner sc = new Scanner(System.in);
        System.out.print("請輸入檔案路徑(例如:E:\\ExcelName.xlsx):");
        String path = sc.nextLine();
        System.out.println("檔案路徑:" + path);
        if (path.equals("") && path.length() <= 0) {
            System.out.print("沒有獲取到,請重新輸入—>");
            getEnter();
        }
        return path;
    }


    // 提取Excel地址,呼叫天地圖API介面
    private static void extract(File excelFile) {
        Workbook workbook = null;
        String excelFormat = "xls";
        try {
            if (excelFile.getName().endsWith("xlsx")) {
                workbook = new XSSFWorkbook(new FileInputStream(excelFile));
                excelFormat = "xlsx";
            } else if (excelFile.getName().endsWith("xls")) {
                workbook = new HSSFWorkbook(new FileInputStream(excelFile));
            }
            int numberOfSheets = workbook.getNumberOfSheets();
            System.out.println("該Excel只有 " + numberOfSheets + " 個工作簿;");
            int success = 0;
            int error = 0;
            if(numberOfSheets > 0){
                for (int i = 0; i < numberOfSheets; i++) {
                    String sheetName = workbook.getSheetName(i);
                    int lastRowNum = workbook.getSheetAt(i).getLastRowNum() + 1;// 這裡的加1,是因為在java中Excel的Sheets被轉成陣列所以從下標0開始獲取;
                    for (int j = 0; j < lastRowNum; j++) {
                        int physicalNumberOfCells = workbook.getSheetAt(i).getRow(j).getPhysicalNumberOfCells();
                        //System.out.println(sheetName + " 有 " + lastRowNum + " 行, " + physicalNumberOfCells + "列;");
                        Cell cell = workbook.getSheetAt(i).getRow(j).getCell(1);
                        String cellValue = cell.getStringCellValue();
                        System.out.println("↓ --- →" + cellValue);
                        JSONObject chinaMapAPI = getChinaMapAPI(cellValue);// 根據真實地址處理,返回精緯度結果值
                        if(null != chinaMapAPI){
                            workbook.getSheetAt(i).getRow(j).createCell(2).setCellValue(chinaMapAPI.get("lat").toString());
                            workbook.getSheetAt(i).getRow(j).createCell(3).setCellValue(chinaMapAPI.get("lon").toString());
                            System.out.println("↘ ----------------------------------------------------------- →已處理至第 "+ success++ +" 行");
                            continue;
                        }
                        error++;
                    }
                }
                System.out.println("↘ ----------------------------------------------------------- →資料不符共 "+ error +" 行");
                FileOutputStream fileOutputStream = new FileOutputStream(new File("E:\\result."+excelFormat));
                workbook.write(fileOutputStream);
                fileOutputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 根據真實地址處理,返回精緯度結果值
     * <p>
     * http://api.tianditu.com/geocoder?ds={"keyWord":"浙江省杭州市省建工大廈"}
     * <p>
     * {"location":{"lon":"120.14444","level":"地產小區","lat":"30.28106"},"status":"0","msg":"ok","searchVersion":"4.8.0"}
     */
    private static JSONObject getChinaMapAPI(String realAddress) {
        final String CHARSET = "utf-8";
        final String extractInterface = "http://api.tianditu.com/geocoder?ds={\"keyWord\":\"" + realAddress + "\"}";
        JSONObject childNode = null;
        try {
            URL url = new URL(extractInterface);
            URLConnection urlConnection = url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, CHARSET);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String inputLine = null;
            StringBuilder jsonbuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null) {
                jsonbuilder.append(inputLine);
            }
            bufferedReader.close();
            inputStreamReader.close();
            if (jsonbuilder.toString().length() > 0) {
                JSONObject parentNode = JSON.parseObject(jsonbuilder.toString());
                if(parentNode.get("msg").equals("無結果")){
                    return null;
                }
                Object location = parentNode.get("location");
                if(null == location){
                    Object admin = parentNode.get("admin");
                    String adminToStr = admin.toString();
                    JSONObject adminToSub = null;
                    try {
                        adminToSub = JSONObject.parseObject(adminToStr.substring(1, adminToStr.length() - 1));
                    }catch (Exception e){
                        return null;
                    }
                    String adminLocation = adminToSub.get("location").toString();
                    childNode = JSONObject.parseObject(adminLocation);
                    String lat = childNode.get("lat").toString();
                    String lon = childNode.get("lon").toString();
                    System.out.println("lat:"+lat+",lon:"+lon);
                    return childNode;
                }
                childNode = JSON.parseObject(location.toString());
                String lat = childNode.get("lat").toString();
                String lon = childNode.get("lon").toString();
                System.out.println("lat:"+lat+",lon:"+lon);
                return childNode;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return childNode;
    }


}