首页 > 编程语言 > 详细

文本表格文件指定分隔符分列转Excel(java实现)

时间:2020-04-15 10:36:12      阅读:320      评论:0      收藏:0      [点我收藏+]

我的需求:

  • 嗯,实习中遇到,需要过滤数据然后以指定的列名输出为excel

我是这样解决的:

  • 写出到一个文本或者表格文件然后指定分隔符分列的输出excel,因为要要设计到去重处理。不能直接写入,

我需要做的:

  • 写一个文本以指定分隔符分列为excel的工具类。

之后输出的样子:

  • txt文件,以‘-’作为分割符

技术分享图片

 

  • 执行是这个样子

技术分享图片

  • 输出是这个样子:

技术分享图片

 

 也可以对表格文件以指定的列名分列。

具体的思路使用PIO构造,需要的依赖

 <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.6.0</version>
        </dependency>

具体代码:传递参数为输入文件,输出文件,分割符,列名

package utils;

import org.apache.poi.hpsf.DocumentSummaryInformation;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import utils.interfaceutils.InputStreamPeocess1;

import java.io.*;
import java.util.*;


/**
 * @author Liruilong
 * @description
 * @date 2020年04月14日  16:04:20
 **/

public class POIUtils {

    /**
     * @param inFile     需要转化文件 : txt/xlxs
     * @param outFile    转化后文件位置 :(文件|目录)
     * @param splie      分割符 正则匹配,特殊字符需要转义
     * @param columnName 列名
     * @return
     * @description
     * @author Liruilong
     * @date 2020年04月14日  17:04:58
     **/
    public static void txt2Excel(File inFile, File outFile, String splie, String... columnName) {

        // txt输出list
        List<String> list = txt2List(inFile);
        //字节数组输出流
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileOutputStream fileOutputStream = null;
        // 获取文件名
        String fileName = inFile.getName().substring(0, inFile.getName().indexOf("."));

        //1. 创建一个 Excel 文档
        HSSFWorkbook workbook = new HSSFWorkbook();
        //2. 创建文档摘要
        workbook.createInformationProperties();
        //3. 获取并配置文档信息
        DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation();
        //文档类别
        docInfo.setCategory(inFile.getName());
        //文档管理员
        docInfo.setManager("liruilong");
        //设置公司信息
        docInfo.setCompany("www.liruiong.org");
        //4. 获取文档摘要信息
        SummaryInformation summInfo = workbook.getSummaryInformation();
        //文档标题
        summInfo.setTitle(inFile.getName());
        //文档作者
        summInfo.setAuthor("liruilong");
        // 文档备注
        summInfo.setComments("本文档由 liruilong 提供");
        //5. 创建样式
        //创建标题行的样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillForegroundColor(IndexedColors.YELLOW.index);
        headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        HSSFCellStyle dateCellStyle = workbook.createCellStyle();
        dateCellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy"));
        HSSFSheet sheet = workbook.createSheet(fileName);
        HSSFRow rx = null;
        //构造表格框架
        rx = sheet.createRow(0);
        for (int i = 0; i < columnName.length; i++) {
            //设置列的宽度
            sheet.setColumnWidth(i, 12 * 256);
            //创建标题行
            HSSFCell cx = rx.createCell(i);
            cx.setCellValue(columnName[i]);
            cx.setCellStyle(headerStyle);
        }
        // 填充数据
        for (int i = 0; i < list.size(); i++) {
            HSSFRow row = sheet.createRow(i + 1);
            String[] tempLine = list.get(i).toString().split(splie);
            for (int i1 = 0; i1 < tempLine.length; i1++) {
                row.createCell(i1).setCellValue(tempLine[i1]);
            }
        }
        // 写入文件
        try {
            if (!outFile.exists()) {
                System.out.println("***************************文件错误****************************");
                throw new Exception();
            } else if (outFile.isDirectory()) {
                outFile.mkdirs();
                fileOutputStream = new FileOutputStream(outFile.getAbsolutePath() + "\\" + fileName + ".xlsx");
            } else {
                fileOutputStream = new FileOutputStream(outFile);
            }
            workbook.write(baos);
            fileOutputStream.write(baos.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param file
     * @return
     * @description 文本文件 --》 内存List
     * @author Liruilong
     * @date 2020年04月14日  18:04:01
     **/

    public static List<String> txt2List(File file) {
        String string = null;
        List<String> txtListAll = new ArrayList<>();
        if (!file.exists() || file.isDirectory()) {
            System.out.println("***************************文件错误****************************");
        } else {
            fileToBufferedReader((bufferedReader) -> {
                String str = null;
                StringBuilder stringBuilder = new StringBuilder();
                while ((str = bufferedReader.readLine()) != null) {
                    // TODO 此处可以书写去重逻辑。
                    if (!txtListAll.contains(str)) {
                        txtListAll.add(str);
                    }
                }
            }, file);
        }
        if (txtListAll.size() > 65535) {
            System.out.println("***************************行数太多错误****************************");
        }
        return txtListAll;
    }

    /**
     * @param inputStreamPeocess
     * @param file
     * @return 环绕处理
     * @description
     * @author Liruilong
     * @date 2020年04月14日  16:04:57
     **/

    public static void fileToBufferedReader(InputStreamPeocess1 inputStreamPeocess, File file) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            try (InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream)) {
                try (BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
                    inputStreamPeocess.peocess(bufferedReader);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        /**
         * @param inFile 需要转化文件
         * @param outFile 转化后文键位置
         * @param splie 分割符
         * @param columnName 列名
         **/
    Arrays.stream(new File("C:\\Users\\12249\\Desktop\\样本N(666)\\不能够转化\\").listFiles()).forEach( o ->{
        txt2Excel(o,new File("C:\\Users\\12249\\Desktop\\样本N(666)\\不能够转化"),"\\*","列名1", "列名2", "列名2","列名2");
    });
    }

}
package utils.interfaceutils;

import java.io.BufferedReader;
import java.io.IOException;

/**
 * @Description :
 * @Author: Liruilong
 * @Date: 2020/4/14 16:39
 */
@FunctionalInterface
public interface InputStreamPeocess1 {
    /**
     * @Author Liruilong
     * @Description 方法签名 BufferedReader ->String
     * @Date 15:47 2020/3/17
     * @Param [inputStream]
     * @return com.liruilong.demotext.service.utils.InputStream
     **/

    void peocess(BufferedReader bufferedReader) throws IOException;
}

 

文本表格文件指定分隔符分列转Excel(java实现)

原文:https://www.cnblogs.com/liruilong/p/12703341.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!