Java读取html文件并将其内容保存到excel文件

时间:2017-08-04 23:30:36

标签: java html excel

Html文件代码示例:

button.setBackgroundResource(R.drawable.custom_rouded_button_background);

我需要阅读的信息是<HTML> <HEAD> <TITLE>REPORT</TITLE></HEAD> <BODY> <TITLE>REPORT</TITLE><PRE><H2>################ REPORT ###################</H2><H3>Setup</H3> Item1 1120 <br> Item2 Copy free <br> Item3 8/3/2017 5:44:51 AM <br> Item4 <Press OK> <br> 行。目标是将这些信息保存到excel文件,如下所示

enter image description here

我目前使用BufferedReader来读取html文件,但我不知道如何分隔包含字段和值的行。我试图使用hashmap来保存其字段名称和值,但我无法以正确的方式获取值。我也尝试过Jsoup来摆脱HTML标签,但是自从html文件以来,它让我更加复杂地阅读这行

<br>

任何建议或想法都会有很多帮助。

1 个答案:

答案 0 :(得分:0)

您的解决方案很简单,只需使用String类的util函数,根据您的html内容使用合适的方法来获取您想要的内容。例如,我在这里使用split(String regex),[split(String regex, int limit)](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String,%20int)), trim or subString` ...来做一个简单的技巧

您的示例代码:

public static void main(String[] args) throws IOException {
        String[] modStrings = new String[] { "Item1", "Item2", "Item3", "Item4", "Item5" };
        FileReader reader = new FileReader("html.html");
        BufferedReader br = new BufferedReader(reader);
        String line;
        String[] tempContent = {};
        ArrayList content = new ArrayList();
        HashMap<String, String> modMap = new HashMap<>();
        while ((line = br.readLine()) != null) {
        if (line.contains("<br>")) {
            line = line.substring(line.indexOf("Item1"));
            tempContent = line.split("<br>");
            for (String item : tempContent) {
                if (item.contains("Item")) {
                    String[] itemArr = item.trim().split(" ", 2);
                    String itemName = itemArr[0].trim();
                    String value = itemArr[1].trim();
                    modMap.put(itemName, value);
                }
            }
        }
        }
        for(String key : modMap.keySet()){
            System.out.println(key + ":" + modMap.get(key));
        }
    }