poi 读取本地文件写入Excel

小脚本

  • 需求:读取已存在的.txt文件,并将其写入本地Excel中;

.txt文件格式,每行存在五个字段以':::'分隔,对应excel每行五列:

WINDOWS_NT_IS_STARTING_UP:::Windows NT是启动:::系统:::系统:::[{"key":"eventId","values":["512"]}]
WINDOWS_IS_SHUTTING_DOWN:::窗户是关闭的:::系统:::系统:::[{"key":"eventId","values":["513"]}]
AN_AUTHENTICATION_PACKAGE_HAS_BEEN_LOADED_BY_THE_LOCAL_SECURITY_AUTHORITY:::身份验证包被当地安全部门:::系统:::系统:::[{"key":"eventId","values":["514"]}]
A_TRUSTED_LOGON_PROCESS_HAS_REGISTERED_WITH_THE_LOCAL_SECURITY_AUTHORITY:::一个可信登录过程与当地安全机关登记:::系统:::系统:::[{"key":"eventId","values":["515"]}]
INTERNAL_RESOURCES_ALLOCATED_FOR_THE_QUEUING_OF_AUDIT_MESSAGES_HAVE_BEEN_EXHAUSTED,_LEADING_TO_THE_LOSS_OF_SOME_AUDITS:::内部资源分配给审计消息的队列已经筋疲力尽,导致的损失一些审计:::系统:::系统:::[{"key":"eventId","values":["516"]}]
THE_AUDIT_LOG_WAS_CLEARED:::审计日志被清除:::系统:::系统:::[{"key":"eventId","values":["517"]}]
  • 思路:读取.txt文件每一行内容,并将其转换成List,然后将其写入已存在的Excel表格中
  • 代码:

pom.xml依赖:


    org.apache.poi
    poi
    3.14


    org.apache.poi
    poi-ooxml
    3.14

变量定义:

private static final String XLS = "xls";
private static final String XLSX = "xlsx";

.txt读取与转换:

//读取本地文件
    private static List readFile(){
        //将读取到的数据放到list中
        ArrayList valList = new ArrayList();
        FileInputStream fis = null;
        InputStreamReader isr = null;
        //包装InputStreamReader,提高处理性能
        BufferedReader br = null;
        try {
            //每一行数据
            String str = "";
            fis = new FileInputStream("D:\\work\\data\\Windows事件数据完整版2018-12-7(不含关联端口).txt");// FileInputStream
            // 从文件系统中的某个文件中获取字节
            // InputStreamReader 是字节流通向字符流的桥梁,
            isr = new InputStreamReader(fis);
            // 从字符输入流中读取文件中的内容,封装了一个new InputStreamReader的对象
            br = new BufferedReader(isr);
            while ((str = br.readLine()) != null) {
                valList.add(str);
            }
        } catch (FileNotFoundException e) {
            System.out.println("找不到指定文件");
        } catch (IOException e) {
            System.out.println("读取文件失败");
        } finally {
            try {
                if(br!=null){ br.close(); }
                if(isr != null){ isr.close(); }
                if(fis != null){ fis.close(); }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return listToListMap(valList);
    }

 

private static List listToListMap(List list){
        List listMap = new ArrayList();
        for (String s: list) {
            Map map = new HashMap();
            String[] split = s.split(":::");
            map.put("name",split[0]);
            map.put("cnName",split[1]);
            map.put("Category",split[2]);
            map.put("subCategory",split[3]);
            map.put("matching_fields",split[4]);
            listMap.add(map);
        }
        return listMap;
    }

 调用:

public static void main(String[] args) {
        writeExcel(readFile(),5,"D:/工作簿1.xlsx");
}

写入Excel:

/**
     *  写入Excel
     * @param dataList 写入Excel 的数据
     * @param cloumn 总列数
     * @param finalXlsxPath 写入路径
     */
    private static void writeExcel(List dataList, int cloumn,String finalXlsxPath){
        OutputStream out = null;
        try {
            File finalXlsxFile = new File(finalXlsxPath);
            Workbook workBook = getWorkbok(finalXlsxFile);
           // workBook.setSheetName(0,"Windows Events");
            // sheet 工作页
            Sheet sheet = workBook.getSheetAt(0);
            //获取Excel最后一行
            int rowNumber = sheet.getLastRowNum();
            //empty
            for (int i = 1; i <= rowNumber; i++) {
                Row row = sheet.getRow(i);
                sheet.removeRow(row);
            }
            for (int j = 0; j < dataList.size(); j++) {
                // 创建一行:从第二行开始,跳过属性列
                Row row = sheet.createRow(j + 1);
                // 得到要插入的每一条记录
                Map dataMap = dataList.get(j);
                String name = dataMap.get("name").toString();
                String cnName = dataMap.get("cnName").toString();
                String category = dataMap.get("Category").toString();
                String subCategory = dataMap.get("subCategory").toString();
                String matchingFields = dataMap.get("matching_fields").toString();
                for (int k = 0; k <= cloumn; k++) {
                    // 在一行内循环
                    Cell first = row.createCell(0);
                    first.setCellValue(name);

                    Cell second = row.createCell(1);
                    second.setCellValue(cnName);

                    Cell third = row.createCell(2);
                    third.setCellValue(category);

                    Cell cell3 = row.createCell(3);
                    cell3.setCellValue(subCategory);

                    Cell cell4 = row.createCell(4);
                    cell4.setCellValue(matchingFields);
                }
            }
            // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
            out =  new FileOutputStream(finalXlsxPath);
            workBook.write(out);
        } catch (Exception e) {
            System.out.println("error error" + e);
        } finally{
            try {
                if(out != null){
                    out.flush();
                    out.close();
                    System.out.println("数据导出成功");
                }
            } catch (IOException e) {
                System.out.println("error error error" + e);
            }
        }
    }
//判断Excel格式(在此有点鸡肋,当做功能拓展~_~)
    public static Workbook getWorkbok(File file) throws IOException{
        Workbook wb = null;
        FileInputStream in = new FileInputStream(file);
        if(file.getName().endsWith(XLS)){     //Excel 2003
            wb = new HSSFWorkbook(in);
        }else if(file.getName().endsWith(XLSX)){    // Excel 2007/2010
            wb = new XSSFWorkbook(in);
        }
        return wb;
    }

缺陷:导入的excel必须存在

你可能感兴趣的:(poi,java,笔记)