将符号分隔的文本文件txt转换为excel的实现

29 篇文章 1 订阅

文本文件如下:
在这里插入图片描述
现在不好处理,打算将其转换为excel,其中通过冒号分割:line.split(":")
main方法如下:

 public static void main(String[] args) {
     
        String textFilePath = "D:\\zoom\\期刊\\J_Medline\\J_Medline";  // 替换为你的文本文件路径
        String excelFilePath = "D:\\zoom\\期刊\\J_Medline\\output1.xlsx";  // 生成的 Excel 文件路径

        List<String[]> data = new ArrayList<>();

        try (BufferedReader br = new BufferedReader(new FileReader(textFilePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split(":");
                String strip = StringUtils.strip(Arrays.toString(fields), "[]");
                if(!strip.equals("--------------------------------------------------------")){
                    data.add(fields);
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("Sheet1");
            int rowNum = 0;

            for (String[] rowData : data) {
                Row row = sheet.createRow(rowNum++);
                int colNum = 0;
                for (String field : rowData) {
                    Cell cell = row.createCell(colNum++);
                    cell.setCellValue(field);
                }
            }
            try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
                workbook.write(outputStream);
                System.out.println("Excel file created successfully: " + excelFilePath);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

其中去掉了横线----------------------------------------,结果如下:
在这里插入图片描述
相关依赖如下:

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值