1. 程式人生 > >java--Excel讀取及轉XML

java--Excel讀取及轉XML

1 單純的將excel轉xml
下載jdom-2.0.6.jar和操作excel的jxl-2.6.jar架包

/**
     * 將execl轉成xml
     * 
     * @param excelPath
     *            被轉換的excel檔案路徑
     * @param xmlPath
     *            轉換成xml的路徑
     */
    public static void execlConvertXml(String excelPath, String xmlPath) {
        Workbook readwb = null
; try { readwb = Workbook.getWorkbook(new File(excelPath)); Element data = new Element("data");// 建立根節點 Document doc = new Document(data);// 根節點新增到文件中; // 迴圈每個sheet for (int m = 0; m < readwb.getNumberOfSheets(); m++) { Sheet sheet = readwb.getSheet(m); int
rsColumns = sheet.getColumns();// 獲取Sheet表中所包含的總列數 int rsRows = sheet.getRows();// 獲取Sheet表中所包含的總行數 Cell[] firstCells = sheet.getRow(0);// 獲取每個sheet中的第一行標題 // 迴圈每行,從1行開始1開始,第0行為列名 for (int i = 1; i < rsRows; i++) { // 建立行節點;
Element row = new Element("dataDetail"); insertHead(row);// 每一行新增相同的資訊,可忽略 // 迴圈當前行的各單元格 for (int j = 1; j < rsColumns; j++) { Cell cell = sheet.getCell(j, i);// 取出每個單元格 if (cell.getContents() == "") { continue; } Element column = new Element( firstCells[j].getContents());// 建立單元格節點 column.setText(cell.getContents()); row.addContent(column); } data.addContent(row); } } // 將標籤內容格式化 Format format = Format.getPrettyFormat(); XMLOutputter XMLOut = new XMLOutputter(format); XMLOut.output(doc, new FileOutputStream(xmlPath)); } catch (Exception e) { e.printStackTrace(); } finally { readwb.close(); System.out.println("run over"); } }

2 將excel轉成XMl後讀取XML中的資訊
下載dom4j-2.0.1.jar架包,https://dom4j.github.io/

    public static void readXmlContent(String xmlPath) {
        SAXReader reader = new SAXReader();
        try {
            Document document = reader.read(new File(xmlPath));
            Element root = document.getRootElement();//獲取根結點

            List<Element> lstFirstNode = root.elements();//獲取根節點的子節點
            for (Element element1 : lstFirstNode) {
                List<Element> lstThirdNode = element1.elements();//子節點的下一級節點
                for (Element element2 : lstThirdNode) {
                    System.out.print(element2.getName()+"\t"+element2.getTextTrim());
                }
                System.out.println();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            System.out.println("over");
        }
    }
}

生成格式化的XML標籤:

解析xml
<shop name="shop for geeks" location="Tokyo, Japan">
  <computer name="iBook" price="1200$" />
  <comic_book name="Dragon Ball vol 1" price="9$" />
  <geekyness_of_shop price="priceless" />
<op>
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(new FileInputStream("foo.xml"));
Element root = doc.getRootElement();

生成XMl

Element root = new Element("shop");
root.setAttribute("name", "shop for geeks");
root.setAttribute("location", "Tokyo, Japan");
Element item1 = new Element("computer");
item1.setAttribute("name", "iBook");
item1.setAttribute("price", "1200$");
root.addContent(item1);
// perform similar steps for other elements
XMLOutputter outputter = new XMLOutputter();
outputter.output(new Document(root), new FileOutputStream ("foo2.xml"));

3 讀取Excel後將其部分寫入新的excel中,僅支援2003的excel:

/**
     * 將Element寫入到輸出流中
     * 
     * @param element 待寫入的標籤
     * @param outputStream 輸出流位置
     */
    public static void writeToExcel01(Element element, OutputStream outputStream) {
        WritableWorkbook workbook = null;
        try {
            workbook = Workbook.createWorkbook(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        WritableSheet writableSheet = workbook.createSheet("sheet1", 0);// 建立一個sheet

        List<Element> lstRow = element.getChildren();// 所有行
        for (int i = 0; i < lstRow.size(); i++) {
            List<Element> lstElem = lstRow.get(i).getChildren();// 當前行的所有列
            for (int j = 0; j < lstElem.size(); j++) {
                addlabelToSheet(writableSheet,j,i,lstElem.get(j).getText());
            }
        }

        try {
            workbook.write();// 從記憶體中寫入檔案中
            workbook.close();// 關閉資源,釋放記憶體
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 將指點的資訊寫到指定的sheet中,
     * @param writableSheet 可看成是excel中的一個sheet 
     * @param column 列
     * @param row 行
     * @param text 內容
     */
    public static void addlabelToSheet(WritableSheet writableSheet,Integer column,Integer row,String text){
        Label label = new Label(column, row, text);// 第一個引數表示列,第二個表示行
        try {
            writableSheet.addCell(label);// 將生成的單元格新增到工作表中
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

更新2017.8.14日
讀取excel時發現不能讀取2007之後的版本,在網上找到一篇部落格,成功的解決了該問題。
貼大聲部落格地址:http://blog.csdn.net/mmm333zzz/article/details/7962377
成功的解決了問題:
這裡寫圖片描述
自己整理後的程式碼:

public static void main(String[] args) throws Exception {
        // List<List<String>> list = poi.read("d:/aaa.xls");
        List<List<String>> list = convertExcelToList("text.xlsx");
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                System.out.print("第" + (i) + "行");
                List<String> cellList = list.get(i);
                for (int j = 0; j < cellList.size(); j++) {
                    System.out.print("    " + cellList.get(j));
                }
                System.out.println();
            }
        }
    }

    /**
     * 根據檔名讀取excel檔案
     * 
     */
    public static List<List<String>> convertExcelToList(String filePath) {
        List<List<String>> dataLst = new ArrayList<List<String>>();
        InputStream inputStream = null;
        try {
            /** 驗證檔案是否合法 */
            if (!validateExcel(filePath)) {
                System.out.println("excel檔案不合法");
                return null;
            }
            /** 判斷檔案的型別,是2003還是2007 */
            boolean isExcel2003 = true;
            if (WDWUtil.isExcel2007(filePath)) {
                isExcel2003 = false;
            }
            File file = new File(filePath);
            inputStream = new FileInputStream(file);

            /** 根據版本選擇建立Workbook的方式 */
            Workbook wb = null;
            if (isExcel2003) {
                wb = new HSSFWorkbook(inputStream);
            } else {
                wb = new XSSFWorkbook(inputStream);
            }

            Sheet sheet = wb.getSheetAt(0);// 第一個shell
            Integer totalRowsNum = sheet.getPhysicalNumberOfRows();// 得到Excel的行數
            Integer totalColumnNum = 0;// 得到Excel的列數
            if (totalRowsNum >= 1 && sheet.getRow(0) != null) {
                totalColumnNum = sheet.getRow(0).getPhysicalNumberOfCells();
            }
            // 讀取excel各行和各列
            for (int r = 0; r < totalRowsNum; r++) {// 迴圈Excel的行
                Row row = sheet.getRow(r);
                if (row == null) {
                    continue;
                }
                List<String> rowLst = new ArrayList<String>();
                for (int c = 0; c < totalColumnNum; c++) {// 迴圈當前行的列
                    Cell cell = row.getCell(c);
                    String cellValue = "";
                    if (null != cell) {
                        cellValue = judgeType(cell);
                    }
                    rowLst.add(cellValue);
                }
                dataLst.add(rowLst);
            }
            inputStream.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    inputStream = null;
                    e.printStackTrace();
                }
            }
        }
        return dataLst;
    }

    /**
     * 判斷型別,根據型別獲取指定的值返回
     * @param cell
     * @return
     */
    public static String judgeType(Cell cell) {
        String cellValue = "";
        // 以下是判斷資料的型別
        switch (cell.getCellType()) {
        case HSSFCell.CELL_TYPE_NUMERIC: // 數字
            cellValue = cell.getNumericCellValue() + "";
            break;
        case HSSFCell.CELL_TYPE_STRING: // 字串
            cellValue = cell.getStringCellValue();
            break;

        case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
            cellValue = cell.getBooleanCellValue() + "";
            break;

        case HSSFCell.CELL_TYPE_FORMULA: // 公式
            cellValue = cell.getCellFormula() + "";
            break;

        case HSSFCell.CELL_TYPE_BLANK: // 空值
            cellValue = "";
            break;

        case HSSFCell.CELL_TYPE_ERROR: // 故障
            cellValue = "非法字元";
            break;

        default:
            cellValue = "未知型別";
            break;
        }
        return cellValue;
    }

    /**
     * 
     * @描述:驗證excel檔案
     */
    public static boolean validateExcel(String filePath) {
        /** 檢查檔名是否為空或者是否是Excel格式的檔案 */
        if (filePath == null
                || !(isExcel2003(filePath) || isExcel2007(filePath))) {
            return false;
        }
        /** 檢查檔案是否存在 */
        File file = new File(filePath);
        if (file == null || !file.exists()) {
            return false;
        }
        return true;
    }

    /**
     * @描述:是否是2003的excel,返回true是2003
     */
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /**
     * @描述:是否是2007的excel,返回true是2007
     */
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }