Java POI組件——讀、篩選、寫Excel__Java

來源:互聯網
上載者:User

接上一篇《Java POI組件——寫Excel》http://blog.csdn.net/chy555chy/article/details/52739711

假設有這麼一個需求——領導挑出了一些員工的名字(準備評先進),只需要這些員工的部分資訊。需要你從員工表中找出它們和這些員工相應的某些資訊。

員工表如下

評先進的人是:”陳七”, “張三”, “林八”, “錢二”, “東方不敗” 需要的欄位要按如下順序排序:”姓名”,”員工號”,”部門”,”年齡”,”入崗時間” 另外需要在首列產生索引,自動排序

結果如下

則本次讀寫Excel需要使用到的jar為

poi-3.15.jar
poi-ooxml-3.15.jar
poi-ooxml-schemas-3.15.jar
commons-collections4-4.1.jar
xmlbeans-2.6.0.jar

package com.example.pkg;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.text.Format;import java.util.ArrayList;import java.util.Date;import org.apache.poi.EncryptedDocumentException;import org.apache.poi.hssf.extractor.ExcelExtractor;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.openxml4j.exceptions.InvalidFormatException;import org.apache.poi.ss.usermodel.BorderStyle;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.CellType;import org.apache.poi.ss.usermodel.CellValue;import org.apache.poi.ss.usermodel.CreationHelper;import org.apache.poi.ss.usermodel.DataFormat;import org.apache.poi.ss.usermodel.DataFormatter;import org.apache.poi.ss.usermodel.DateUtil;import org.apache.poi.ss.usermodel.FillPatternType;import org.apache.poi.ss.usermodel.Font;import org.apache.poi.ss.usermodel.FormulaEvaluator;import org.apache.poi.ss.usermodel.IndexedColors;import org.apache.poi.ss.usermodel.RichTextString;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.ss.usermodel.WorkbookFactory;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.extractor.XSSFExcelExtractor;import org.apache.poi.xssf.usermodel.XSSFWorkbook;public class PoiExcelClass {/**     * 篩選並重組表格(自動產生索引),只篩選第一個sheet     *      * @params originFileName 源檔案名稱     * @params targetFileName 目標檔案名     * @params columns 只提取原表格中出現過的列(不包括索引)     * @params filterItems 篩選條件,只提取出現該項的行     */    private static void filter(String originFileName, String targetFileName, String[] columns, String filterColumn, String[] filterItems) {        InputStream inp = null;        Workbook workbook = null;        ArrayList<Integer> columnIndexList = new ArrayList<Integer>(columns.length);        int filterColumnIndex = -1;        Workbook workbook_w = null;        FileOutputStream fos = null;        try {            inp = new FileInputStream(originFileName);            workbook = WorkbookFactory.create(inp);            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();            Sheet sheet = workbook.getSheetAt(0);            Row row = sheet.getRow(0);            // 如果未發現有行,則返回            if (row == null)                return;            // 第一行規定必須是標題            for (Cell cell : row) {                if (cell.getCellTypeEnum() == CellType.STRING) {                    for (String str : columns) {                        String value = cell.getStringCellValue();                        if (str.equals(value)) {                            int index = cell.getColumnIndex();                            columnIndexList.add(index);                            if(filterColumnIndex == -1 && filterColumn.equals(value)) {                                filterColumnIndex = index;                            }                            break;                        }                    }                }            }            // 如果待篩選的欄位一個也沒找到就返回            if (columnIndexList.size() == 0 || filterColumnIndex == -1)                return;            if (targetFileName.endsWith(SUFFIX_XSSF)) {                workbook_w = new XSSFWorkbook();            } else {                workbook_w = new HSSFWorkbook();            }            Sheet sheet_w = workbook_w.createSheet("Sheet1");            int rowIndex = 1;            //添加標題列            Row row_w = sheet_w.createRow(0);            row_w.createCell(0).setCellValue("索引");            for (int i = 0; i < columnIndexList.size(); i++) {                String value = row.getCell(columnIndexList.get(i)).getStringCellValue();                row_w.createCell(i+1).setCellValue(value);            }            for (Row r : sheet) {                if(r.getRowNum() == 0) continue;                Cell cell = r.getCell(filterColumnIndex);                if(cell.getCellTypeEnum() == CellType.STRING) {                     String value = cell.getStringCellValue();                     for(String str : filterItems) {                         if(str.equals(value)) {                             //該行滿足篩選條件                             row_w = sheet_w.createRow(rowIndex);                             row_w.createCell(0).setCellFormula("ROW()-1");                             for (int i = 0; i < columnIndexList.size(); i++) {                                 int index = columnIndexList.get(i);                                 Cell c = r.getCell(index);                                 Cell c_w = row_w.createCell(i+1, c.getCellType());                                 //從原儲存格中繼承儲存格格式,包括內容格式、邊框、顏色、字型。注意:這裡必須先create,不能直接設定其他儲存格的格式                                 CellStyle cs = workbook_w.createCellStyle();                                 cs.cloneStyleFrom(c.getCellStyle());                                 c_w.setCellStyle(cs);                                 //以下是錯誤的方法,Error:This Style does not belong to the supplied Workbook Stlyes Source. Are you trying to assign a style from one workbook to the cell of a differnt workbook?                                 //c_w.setCellStyle(c.getCellStyle());                                 switch (c.getCellTypeEnum()) {                                case _NONE:                                    break;                                case BLANK:                                    break;                                case BOOLEAN:                                    c_w.setCellValue(c.getBooleanCellValue());                                    break;                                case ERROR:                                    c_w.setCellErrorValue(c.getErrorCellValue());                                    break;                                case FORMULA:                                    //唯一的問題就是公式由於是根據儲存格計算,新表可能相應的儲存格存放不同的資料,造成計算結果不同//                                  c_w.setCellFormula(c.getCellFormula());                                    CellValue cellValue = evaluator.evaluate(c);                                    c_w.setCellType(cellValue.getCellType());                                    switch (cellValue.getCellTypeEnum()) {                                    case BOOLEAN:                                        c_w.setCellValue(cellValue.getBooleanValue());                                        break;                                    case ERROR:                                        c_w.setCellErrorValue(cellValue.getErrorValue());                                        break;                                    case NUMERIC:                                        if(DateUtil.isCellDateFormatted(c)) {                                            c_w.setCellValue(c.getDateCellValue());                                        } else {                                            c_w.setCellValue(c.getNumericCellValue());                                        }                                        break;                                    case STRING:                                        c_w.setCellValue(c.getRichStringCellValue());                                        break;                                    default:                                        break;                                    }                                    break;                                case NUMERIC:                                    if(DateUtil.isCellDateFormatted(c)) {                                        c_w.setCellValue(c.getDateCellValue());                                    } else {                                        c_w.setCellValue(c.getNumericCellValue());                                    }                                    break;                                case STRING:                                    c_w.setCellValue(c.getRichStringCellValue());                                    break;                                }                             }                             rowIndex++;                             break;                         }                     }                }            }            fos = new FileOutputStream(targetFileName);            workbook_w.write(fos);        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (EncryptedDocumentException e) {            e.printStackTrace();        } catch (InvalidFormatException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } finally {            if (inp != null) {                try {                    inp.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (workbook != null) {                try {                    workbook.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (workbook_w != null) {                try {                    workbook_w.close();                } catch (IOException e) {                    e.printStackTrace();                }            }            if (fos != null) {                try {                    fos.close();                } catch (IOException e) {                    e.printStackTrace();                }            }        }    }    public static void main(String[] args) {        filter(EXCEL_PATH, "filter.xlsx", new String[] {"姓名","員工號","部門","年齡","入崗時間"}, "姓名", new String[] {"陳七", "張三", "林八", "錢二", "東方不敗"});    }


雖然能基本完成這個任務,但這裡還有一個不完美的地方,那就是公式儲存格。
這裡公式儲存格的處理方式為:計算出該值,然後將其值填入對應單元。
其實更好的做法應該是將公式中的欄位進行映射,映射到新的欄位中。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.