--【可实现以行为单位去重,指定分隔符分列】

我的需求:

  • 嗯,实习中遇到,需要过滤数据然后以指定的列名输出为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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import utils.interfaceutils.InputStreamPeocess1; import java.io.*;
import java.util.*; /**
* @author Liruilong
* @return
* @description 文本写入excel
* @date 2020年04月14日 16:04:20
**/ public class POIUtils { private static final String XLS = "xls";
private static final String XLSX = "xlsx";
private static List<String> fileNameExtension = Arrays.asList(XLS, XLSX); /**
* @param inFile 文件输入 : txt
* @param outFile 文件输出位置 :(文件|目录)
* @param splie 分割符 正则匹配,特殊字符需要转义
* @param append 文件存在时的写入方式
* @param columnName
* @return
* @description 文件转换
* @author Liruilong
* @date 2020年04月18日 11:04:51
**/ public static void txt2Excel(File inFile, File outFile, String splie,boolean append, String... columnName) {
List<String> list = txt2List(inFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fileOutputStream = null;
String fileName = inFile.getName().substring(0, inFile.getName().indexOf("."));
try {
if (!outFile.exists()) {
System.out.println("***************************文件路径错误****************************");
throw new Exception();
} else if (outFile.isDirectory()) {
outFile.mkdirs();
fileOutputStream = new FileOutputStream(outFile.getAbsolutePath() + "\\" + fileName + ".xlsx");
} else {
if (outFile.isFile()) {
String tempFileNameExtension = outFile.getName().substring(outFile.getName().indexOf(".") + 1);
if (fileNameExtension.stream().anyMatch( o ->o.equals(tempFileNameExtension))){
fileOutputStream = new FileOutputStream(outFile,append);
}
fileOutputStream = new FileOutputStream(outFile.getParent() + "\\" + fileName + ".xlsx");
}
}
createExcel(fileName,splie,list,columnName).write(baos);
fileOutputStream.flush();
fileOutputStream.write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* @param inFile 文件输入 : txt
* @param outFile 文件输出位置 :(文件|目录)
* @param splie 分割符 正则匹配,特殊字符需要转义
* @param columnName 列名
* @return
* @description 以默认方式写入
* @author Liruilong
* @date 2020年04月18日 11:04:51
**/ public static void txt2Excel(File inFile, File outFile, String splie, String... columnName) {
List<String> list = txt2List(inFile);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileOutputStream fileOutputStream = null;
String fileName = inFile.getName().substring(0, inFile.getName().indexOf("."));
try {
if (!outFile.exists()) {
System.out.println("***************************文件路径错误****************************");
throw new Exception();
} else if (outFile.isDirectory()) {
outFile.mkdirs();
fileOutputStream = new FileOutputStream(outFile.getAbsolutePath() + "\\" + fileName + ".xlsx");
} else {
if (outFile.isFile()) {
//获取输出文件后缀
String tempFileNameExtension = outFile.getName().substring(outFile.getName().indexOf(".") + 1);
if (fileNameExtension.stream().anyMatch( o ->o.equals(tempFileNameExtension))){
fileOutputStream = new FileOutputStream(outFile,false);
}
fileOutputStream = new FileOutputStream(outFile.getParent() + "\\" + fileName + ".xlsx");
}
}
createExcel(fileName,splie,list,columnName).write(baos);
fileOutputStream.flush();
fileOutputStream.write(baos.toByteArray());
} catch (Exception e) {
e.printStackTrace();
}
} /**
* @param fileName 文件名
* @param splie 分割符 正则匹配,特殊字符需要转义
* @param list 文件转换后的List
* @param columnName 列名
* @return
* @description
* @author Liruilong
* @date 2020年04月18日 11:04:46
**/ public static HSSFWorkbook createExcel(String fileName,String splie,List<String> list,String...columnName) {
//1. 创建一个 Excel 文档
HSSFWorkbook workbook = new HSSFWorkbook();
//2. 创建文档摘要
workbook.createInformationProperties();
//3. 获取并配置文档信息
DocumentSummaryInformation docInfo = workbook.getDocumentSummaryInformation();
//文档类别
docInfo.setCategory(fileName);
//文档管理员
docInfo.setManager("liruilong");
//设置公司信息
docInfo.setCompany("www.liruiong.org");
//4. 获取文档摘要信息
SummaryInformation summInfo = workbook.getSummaryInformation();
//文档标题
summInfo.setTitle(fileName);
//文档作者
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 * 456);
//创建标题行
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]);
}
}
return workbook;
} /**
* @param file
* @param data 每行数据
* @return
* @description 写入excel数据
* @author Liruilong
* @date 2020年04月15日 10:04:40
**/ public static void excelWriter(File file, String... data) {
//获取文件类型
String fileType = file.getName().substring(file.getName().indexOf(".") + 1);
try (POIFSFileSystem poifsFileSystem = new POIFSFileSystem(new FileInputStream(file))) {
Workbook workbook = null;
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(poifsFileSystem);
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(file);
}
Sheet sheetAt = workbook.getSheetAt(0);
Row row = sheetAt.getRow(0);
System.out.println("最后一行的行号为:" + sheetAt.getLastRowNum() + "--记录为:" + row.getLastCellNum());
row = sheetAt.createRow(sheetAt.getLastRowNum() + 1);
for (int i = 0; i < data.length; i++) {
row.createCell(i).setCellValue(data[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* @param file
* @return
* @description 判断文件的Excel类型,输出Excel对象
* @author Liruilong
* @date 2020年04月15日 10:04:37
**/ public static Workbook getWorkbook(File file) {
Workbook workbook = null;
String fileType = file.getName().substring(file.getName().indexOf(".") + 1);
try (FileInputStream fileInputStream = new FileInputStream(file)) {
if (fileType.equalsIgnoreCase(XLS)) {
workbook = new HSSFWorkbook(fileInputStream);
} else if (fileType.equalsIgnoreCase(XLSX)) {
workbook = new XSSFWorkbook(fileInputStream);
}
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
} /**
* @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();
}
} /**
* @param fileParentPath 文件父路径
* @param shilp 分割符
* @return
* @description 以父目录的形式进行转化,默认输出位置,列名,写入方式
* @author Liruilong
* @date 2020年04月18日 10:04:28
**/ public static void dir2Excel(String fileParentPath, String shilp) {
File[] files = new File(fileParentPath).listFiles();
Arrays.stream(files).forEach(f -> {
txt2Excel(f, f, shilp, "");
});
} /**
* @param fileParentPath 输入文件父路径
* @param outParentPath 输出文件父路径
* @param shilp 分割符
* @return
* @description 以指定输出父目录输出,列名默认
* @author Liruilong
* @date 2020年04月18日 10:04:41
**/ public static void dir2Excel(String fileParentPath, String outParentPath, String shilp) {
File[] files = new File(fileParentPath).listFiles();
Arrays.stream(files).forEach(f -> {
txt2Excel(f, new File(outParentPath), shilp, "");
});
} /**
* @param fileParentPath 输入文件父路径
* @param outParentPath 输出文件父路径
* @param shilp 分割符
* @return
* @description 以指定输出父目录输出,列名指定
* @author Liruilong
* @date 2020年04月18日 10:04:23
**/ public static void dir2Excel(String fileParentPath, String outParentPath, String shilp, String... columnName) {
File[] files = new File(fileParentPath).listFiles();
Arrays.stream(files).forEach(f -> {
txt2Excel(f, new File(outParentPath), shilp, columnName);
});
} /**
* @param filePath 文件路径
* @param shilp 分割符
* @return
* @description 单文件转化,指定分割符,
* @author Liruilong
* @date 2020年04月18日 10:04:08
**/ public static void OneTxt2Excel(String filePath, String shilp) {
File file = new File(filePath);
txt2Excel(file, file, shilp,"");
} /**
* @param filePath
* @param outFilePath
* @param shilp
* @param append
* @return
* @description 单文件转化,指定分割符,写入方式
* @author Liruilong
* @date 2020年04月18日 11:04:07
**/ public static void OneTxt2Excel(String filePath, String outFilePath, String shilp, boolean append) {
File file = new File(filePath);
File outFile = new File(outFilePath);
txt2Excel(file, outFile, shilp,append, "");
} public static void main(String[] args) { /*父目录转换
public static void dir2Excel(String)
public static void dir2Excel(String,String)
public static void dir2Excel(String,String,String[])*/ /* 文件转换
public static void OneTxt2Excel(String,String,boolean)
public static void OneTxt2Excel(String)*/
Arrays.stream(POIUtils.class.getMethods()).forEach( m ->{
System.out.println(m.getName());
}); } }
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--

文本表格文件指定分隔符分列转Excel(java实现)的更多相关文章

  1. python读取Excel表格文件

    python读取Excel表格文件,例如获取这个文件的数据 python读取Excel表格文件,需要如下步骤: 1.安装Excel读取数据的库-----xlrd 直接pip install xlrd安 ...

  2. php中读写excel表格文件示例。

    测试环境:php5.6.24.这块没啥兼容问题. 需要更多栗子,请看PHPExcel的examples.还是蛮强大的. 读取excel文件. 第一步.下载开源的PHPExcel的类库文件,官方网站是h ...

  3. pyhton读取 excel表格文件

    2019的第一天,忘记昨日之事,迎接新的明天. excel表格文件办公中常用,如通过Python操作这些数据需导入并有序读取这些数据 特随笔,供以后查阅 代码如下: import xlrd # fil ...

  4. java与Excel (.xls文件) ---使用JXL创建,增添表格文件

    由于一些原因要搞一下excel文件,个人感觉poi太难,所以用了JXL(感觉比较简单). 1.添加外部归档 jxl.jar 2. /** 生成的xls文件第一次需要手动选择EXCEL打开* * */ ...

  5. 【 D3.js 进阶系列 — 1.0 】 CSV 表格文件的读取

    在入门系列的教程中.我们经常使用 d3.json() 函数来读取 json 格式的文件.json 格式非常强大.但对于普通用户可能不太适合,普通用户更喜欢的是用 Microsoft Excel 或 O ...

  6. JAVA之编码---->CSV在文本下是正常的,用EXCEL打开是乱码的问题

    JAVA之编码---->CSV在文本下是正常的,用EXCEL打开是乱码的问题 在JAVA下输出文件流,保存成CSV(用UTF-8)文件,怎么处理用EXCEL下是乱码,但是在记事本等其他软件都是正 ...

  7. [原创]VBA实现汇总excel,将多个Excel文件内容复制到一个Excel文件中

    功能:遍历用户指定的文件夹,把文件夹中所有的excel文件的第一个表格的数据复制到本excel文件中.注意,每个excel文件中有效数据行的判断标准是A列的最后一个有数据的单元格的行号,比如A列到第1 ...

  8. 如何使用免费控件将Word表格中的数据导入到Excel中

    我通常使用MS Excel来存储和处理大量数据,但有时候经常会碰到一个问题—我需要的数据存储在word表格中,而不是在Excel中,这样处理起来非常麻烦,尤其是在数据比较庞大的时候, 这时我迫切地需要 ...

  9. atitit.sql server2008导出导入数据库大的表格文件... oracle mysql

    atitit.sql server2008导出导入数据库大的表格文件... 1. 超过80M的文件是不能在查询分析器中执行的 1 2. Oracle ,mysql大的文件导入 1 2.1. 使用sql ...

随机推荐

  1. Windows Server 2012 R2 域证书服务搭建

    网管大叔说要给每个人颁发一个证书,这个证书很耗电 1.在服务器管理器中添加角色和功能 下一步 下一步 勾选Active Directory证书服务 下一步 下一步 勾选证书颁发机构,证书颁发机构Web ...

  2. css报模块没找到 分析思路 从后往前找,先定位最后blue.less 解决:iview升级4.0 css没改导致编译不过去

    E:\xxx\xxx\xxx\../../../../../../../E:/xxx/xxx/xxx/node_modules/_iview@3.5.4@iview/src/styles/common ...

  3. Druid连接池和springJDbc框架-Java(新手)

    Druid连接池: Druid 由阿里提供 安装步骤: 导包 durid1.0.9 jar包 定义配置文件 properties文件 名字任意位置也任意 加载文件 获得数据库连接池对象 通过Durid ...

  4. js遍历删除对象的key

    // 如果用户没有填写值,则删除对象的key. Object.keys(obj).forEach( (key) => {      if (!obj[key]) { // !obj[key]表示 ...

  5. PHP之从反向删除单链表元素的问题谈起

    在完成一个单链表的删除指定元素的题目中,我发现了一件神奇的事情,php对象赋值给另外一个变量后,可以如同引用传值一般继续利用新的变量来实现链表的链接. 后面经过查证后发现: PHP7.0版本除了对象, ...

  6. shell编程之脚本参数$@,$*,$#,$$,$?的含义

    #首先按顺序解释各个参数的含义 1.$0  表示脚本的文件名, 具体的路径信息和执行命令时的相对位置有关,例如 sakura@mi-OptiPlex-7050:~/sh$ sh args.sh arg ...

  7. MySQL的死锁系列- 锁的类型以及加锁原理

    疫情期间在家工作时,同事使用了 insert into on duplicate key update 语句进行插入去重,但是在测试过程中发现了死锁现象: ERROR 1213 (40001): De ...

  8. HDU 3303 Harmony Forever 前缀和+树状数组||线段树

    Problem Description We believe that every inhabitant of this universe eventually will find a way to ...

  9. 1+1>2:MIT&IBM提出结合符号主义和连接主义的高效、准确新模型

    自人工智能的概念提出以来,关于符号主义和连接主义的争论就不绝于耳.究竟哪一种方式可以实现更好的人工智能?这一问题目前还没有定论.深度学习的快速发展让我们看到连接主义在构建 AI 系统中的优势,但其劣势 ...

  10. 对于一个由0..n的所有数按升序组成的序列,我们要进行一些筛选,每次我们取当前所有数字中从小到大的第奇数位个的数,并将其丢弃。重复这一过程直到最后剩下一个数。请求出最后剩下的数字。

    输入描述: 每组数据一行一个数字,为题目中的n(n小于等于1000). 输出描述: 一行输出最后剩下的数字.我的思路是用两个链表,一个用于存储原数据,一个用于存储要丢掉的数据,再循环从元数据中剔除掉即 ...