JAVA-POI 匯入匯出EXCEL(含JSON)__JAVA

來源:互聯網
上載者:User

         最近做了幾個很有意思的功能,女朋友公司需要收集北京互連網的資訊,第一反應就是爬蟲,但是又不太擅長,因此想到了用正則解析轉換為JSON格式匯出為EXCEL。恰好工作內容也要做一個把資料庫中的資料匯入匯出並發送郵件的定時任務,因此這裡詳細學習了一下操作excel的一些內容。

現在主流的操作Excel檔案的開源工具有很多,用得比較多的就是Apache的POI及JExcelAPI。這裡我們用Apache POI。

這裡先附上Apache 官方給的例子吧 可以參考下 http://poi.apache.org/spreadsheet/quick-guide.html 一、POI簡介

     Apache POI是Apache軟體基金會提供的100%開源庫。大多數中小規模的應用程式開發主要依賴於Apache POI(HSSF+ XSSF)。它支援Excel 庫的所有準系統; 然而,呈現和文本提取是它的主要特點。


二、所需JAR包

這裡我們使用的是maven項目,給出POM檔案作為參考:

 <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi</artifactId>            <version>3.15</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.15</version>        </dependency>


三、使用執行個體         大體的思路都是調用API,建立工作薄,建立sheet,得到要操作的row行數,操作cell儲存格內容。

       需要注意的是Apache POI(HSSF+ XSSF)中HSSF是對應2004版本以前的,XSSF是對應2004年以後版本的excel檔案,也就是說需要.xlsx檔案結尾的需要使用XSSF。

      row,cell的座標都是從0開始而不是從1開始。

這裡我們給出幾個DEMO和注釋供參考: (1)建立一張Excel表做操作

 
  /**1、建立工作薄*/        XSSFWorkbook xs = new XSSFWorkbook(pkg);        /**2、在xs中添加一個sheet,對應Excel檔案中的sheet */        XSSFSheet sheet = xs.createSheet("sheet1");        /**3、在sheet中添加表頭第0行,注意老版本poi對Excel的行數列數有限制short*/        //XSSFRow row=sheet.createRow(0);        /**4、建立儲存格,並設定值表頭 設定表頭置中 */        XSSFCellStyle style = xs.createCellStyle();        style.setAlignment(XSSFCellStyle.ALIGN_CENTER);//// 建立一個置中格式        /**5、逐行寫入資料*///        XSSFCell cell=row.createCell(0);//        cell.setCellValue();        int a = 0;        //遍曆List擷取資料        for (int i = 0; i < valuelist.size(); i++) {            ExcelInformation excelInfo = valuelist.get(i);            XSSFRow row = sheet.createRow(a);            row.setRowStyle(style);            /**合併儲存格*/            sheet.addMergedRegion(new CellRangeAddress(a, a, 0, 5));            sheet.addMergedRegion(new CellRangeAddress(a, a, 6, 10));            row.createCell(0).setCellValue(excelTitleMap.get(excelInfo.getServiceType()));            row.createCell(1).setCellValue("錯誤提示Top5");            XSSFRow row1 = sheet.createRow(a + 1);            row1.setRowStyle(style);            row1.setRowStyle(style);            row1.createCell(0).setCellValue("");            row1.createCell(1).setCellValue("");            row1.createCell(2).setCellValue("");            row1.createCell(3).setCellValue("");            row1.createCell(4).setCellValue("");            row1.createCell(5).setCellValue("");            XSSFRow row2 = sheet.createRow(a + 2);            row2.setRowStyle(style);            row2.createCell(0).setCellValue(excelInfo.getEnterPage());            row2.createCell(1).setCellValue(excelInfo.getFailureNumber());            row2.createCell(2).setCellValue(excelInfo.getAuthorizedSuccess());            row2.createCell(3).setCellValue(excelInfo.getAuthorizationRate());            row2.createCell(4).setCellValue(excelInfo.getCrawlSuccess());            row2.createCell(5).setCellValue(excelInfo.getCrawlRate());            a = a + 4;        }

(2)寫入到本地:

  try        {            FileOutputStream fout = new FileOutputStream("檔案路徑");            workbook.write(fout);            fout.close();        }        catch (Exception e)        {            e.printStackTrace();        }

(3)讀取項目中路徑Excel 並修改

 XSSFWorkbook workbook = null;        try {            InputStream excelFileInputStream = ExcelUtil.class.getResourceAsStream("檔案路徑");            workbook = new XSSFWorkbook(excelFileInputStream);        } catch (IOException e) {            e.printStackTrace();        }

(4)以流的形式返回 

 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        try {            workbook.write(byteArrayOutputStream);        } catch (IOException e) {            e.printStackTrace();        }
(5)JSON作為資料傳入匯出Excel

/** * Created by tanyunlong on 2017/4/10. */public class ExcelUtil {    @SuppressWarnings("unchecked")    // 建立excel檔案函數    // src為待儲存的檔案路徑,json為待儲存的json資料    public static JSONObject createExcel(String src, JSONObject json) {        JSONObject result = new JSONObject(); // 用來反饋函數調用結果        try {            // 建立檔案            File file = new File(src);            file.createNewFile();            OutputStream outputStream = new FileOutputStream(file);// 建立工作薄            WritableWorkbook writableWorkbook = Workbook.createWorkbook(outputStream);            WritableSheet sheet = writableWorkbook.createSheet("First sheet", 0);// 建立新的一頁            JSONArray jsonArray = json.getJSONArray("data");// 得到data對應的JSONArray            Label label; // 儲存格對象            int column = 0; // 列數計數            // 將第一行資訊加到頁中。如:姓名、年齡、性別            JSONObject first = jsonArray.getJSONObject(0);            Iterator<String> iterator = first.keys(); // 得到第一項的key集合            while (iterator.hasNext()) { // 遍曆key集合                String key = (String) iterator.next(); // 得到key                label = new Label(column++, 0, key); // 第一個參數是儲存格所在列,第二個參數是儲存格所在行,第三個參數是值                sheet.addCell(label); // 將儲存格加到頁            }            // 遍曆jsonArray            for (int i = 0; i < jsonArray.size(); i++) {                JSONObject item = jsonArray.getJSONObject(i); // 得到數組的每項                iterator = item.keys(); // 得到key集合                column = 0;// 從第0列開始放                while (iterator.hasNext()) {                    String key = iterator.next(); // 得到key                    String value = item.getString(key); // 得到key對應的value                    label = new Label(column++, (i + 1), value); // 第一個參數是儲存格所在列,第二個參數是儲存格所在行,第三個參數是值                    sheet.addCell(label); // 將儲存格加到頁                }            }            writableWorkbook.write(); // 加入到檔案中            writableWorkbook.close(); // 關閉檔案,釋放資源        } catch (Exception e) {            result.put("result", "failed"); // 將調用該函數的結果返回            result.put("reason", e.getMessage()); // 將調用該函數失敗的原因返回            return result;        }        result.put("result", "successed");        return result;    }}


附幾個參考API

POI API中文說明

POI 官方說明及範例









聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.